context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Palaso.Data;
using Palaso.DictionaryServices.Model;
using Palaso.Lift;
using Palaso.Lift.Options;
using Palaso.Lift.Parsing;
using Palaso.Text;
namespace Palaso.DictionaryServices.Lift
{
/// <summary>
/// This class is called by the LiftParser, as it encounters each element of a lift file.
/// There is at least one other ILexiconMerger, used in FLEX.
///
/// NB: In WeSay, we don't really use this to "merge in" elements, since we start from
/// scratch each time we read a file. But in FLEx it is currently used that way, hence
/// we haven't renamed the interface (ILexiconMerger).
/// </summary>
///
public class LexEntryFromLiftBuilder:
ILexiconMerger<PalasoDataObject, LexEntry, LexSense, LexExampleSentence>,
IDisposable
{
/// <summary>
/// Subscribe to this event in order to do something (or do something to an entry) as soon as it has been parsed in.
/// WeSay uses this to populate definitions from glosses.
/// </summary>
public event EventHandler<EntryEvent> AfterEntryRead;
public class EntryEventArgs: EventArgs
{
public readonly LexEntry Entry;
public EntryEventArgs(LexEntry entry)
{
this.Entry = entry;
}
}
public event EventHandler<EntryEventArgs> EntryCreatedEvent = delegate { };
private readonly IList<string> _expectedOptionCollectionTraits;
private readonly MemoryDataMapper<LexEntry> _dataMapper;
private readonly OptionsList _semanticDomainsList;
public LexEntryFromLiftBuilder(MemoryDataMapper<LexEntry> dataMapper, OptionsList semanticDomainsList)
{
ExpectedOptionTraits = new List<string>();
_expectedOptionCollectionTraits = new List<string>();
_dataMapper = dataMapper;
_semanticDomainsList = semanticDomainsList;
}
public LexEntry GetOrMakeEntry(Extensible eInfo, int order)
{
LexEntry entry = null;
if (eInfo.CreationTime == default(DateTime))
{
eInfo.CreationTime = PreciseDateTime.UtcNow;
}
if (eInfo.ModificationTime == default(DateTime))
{
eInfo.ModificationTime = PreciseDateTime.UtcNow;
}
entry = _dataMapper.CreateItem();
entry.Id = eInfo.Id;
entry.Guid = eInfo.Guid;
entry.CreationTime = eInfo.CreationTime;
entry.ModificationTime = eInfo.ModificationTime;
if (_dataMapper.LastModified < entry.ModificationTime)
{
_dataMapper.LastModified = entry.ModificationTime;
}
entry.ModifiedTimeIsLocked = true; //while we build it up
entry.OrderForRoundTripping = order;
return entry;
}
#region ILexiconMerger<PalasoDataObject,LexEntry,LexSense,LexExampleSentence> Members
public void EntryWasDeleted(Extensible info, DateTime dateDeleted)
{
//there isn't anything we need to do; we just don't import it
// since we always update file in place, the info will still stay in the lift file
// even though we don't import it.
}
#endregion
#if merging
private static bool CanSafelyPruneMerge(Extensible eInfo, LexEntry entry)
{
return entry != null
&& entry.ModificationTime == eInfo.ModificationTime
&& entry.ModificationTime.Kind != DateTimeKind.Unspecified
&& eInfo.ModificationTime.Kind != DateTimeKind.Unspecified;
}
#endif
public LexSense GetOrMakeSense(LexEntry entry, Extensible eInfo, string rawXml)
{
//nb, has no guid or dates
LexSense s = new LexSense(entry);
s.Id = eInfo.Id;
entry.Senses.Add(s);
return s;
}
public LexSense GetOrMakeSubsense(LexSense sense, Extensible info, string rawXml)
{
sense.GetOrCreateProperty<EmbeddedXmlCollection>("subSense").Values.Add(rawXml);
return null;
}
public LexExampleSentence GetOrMakeExample(LexSense sense, Extensible eInfo)
{
LexExampleSentence ex = new LexExampleSentence(sense);
sense.ExampleSentences.Add(ex);
return ex;
}
public void MergeInLexemeForm(LexEntry entry, LiftMultiText forms)
{
MergeIn(entry.LexicalForm, forms);
}
public void MergeInCitationForm(LexEntry entry, LiftMultiText contents)
{
AddOrAppendMultiTextProperty(entry,
contents,
LexEntry.WellKnownProperties.Citation,
null);
}
public PalasoDataObject MergeInPronunciation(LexEntry entry,
LiftMultiText contents,
string rawXml)
{
entry.GetOrCreateProperty<EmbeddedXmlCollection>("pronunciation").Values.Add(rawXml);
return null;
}
public PalasoDataObject MergeInVariant(LexEntry entry, LiftMultiText contents, string rawXml)
{
entry.GetOrCreateProperty<EmbeddedXmlCollection>("variant").Values.Add(rawXml);
return null;
}
public void MergeInGloss(LexSense sense, LiftMultiText forms)
{
sense.Gloss.MergeInWithAppend(MultiText.Create(forms.AsSimpleStrings), "; ");
AddAnnotationsToMultiText(forms, sense.Gloss);
}
private static void AddAnnotationsToMultiText(LiftMultiText forms, MultiTextBase text)
{
foreach (Annotation annotation in forms.Annotations)
{
if (annotation.Name == "flag")
{
text.SetAnnotationOfAlternativeIsStarred(annotation.LanguageHint,
int.Parse(annotation.Value) > 0);
}
else
{
//log dropped
}
}
}
public void MergeInExampleForm(LexExampleSentence example, LiftMultiText forms)
//, string optionalSource)
{
MergeIn(example.Sentence, forms);
}
public void MergeInTranslationForm(LexExampleSentence example,
string type,
LiftMultiText forms,
string rawXml)
{
bool alreadyHaveAPrimaryTranslation = example.Translation != null &&
!string.IsNullOrEmpty(
example.Translation.GetFirstAlternative());
/* bool typeIsCompatibleWithWeSayPrimaryTranslation = string.IsNullOrEmpty(type) ||
type.ToLower() == "free translation"; //this is the default style in FLEx
* */
//WeSay's model only allows for one translation just grab the first translation
if (!alreadyHaveAPrimaryTranslation /*&& typeIsCompatibleWithWeSayPrimaryTranslation*/)
{
MergeIn(example.Translation, forms);
example.TranslationType = type;
}
else
{
example.GetOrCreateProperty<EmbeddedXmlCollection>(PalasoDataObject.GetEmbeddedXmlNameForProperty(LexExampleSentence.WellKnownProperties.Translation)).Values.Add(rawXml);
}
}
public void MergeInSource(LexExampleSentence example, string source)
{
OptionRef o =
example.GetOrCreateProperty<OptionRef>(
LexExampleSentence.WellKnownProperties.Source);
o.Value = source;
}
public void MergeInDefinition(LexSense sense, LiftMultiText contents)
{
AddOrAppendMultiTextProperty(sense,
contents,
LexSense.WellKnownProperties.Definition,
null);
}
public void MergeInPicture(LexSense sense, string href, LiftMultiText caption)
{
//nb 1: we're limiting ourselves to one picture per sense, here:
//nb 2: the name and case must match the fieldName
PictureRef pict = sense.GetOrCreateProperty<PictureRef>("Picture");
pict.Value = href;
if (caption != null)
{
pict.Caption = MultiText.Create(caption.AsSimpleStrings);
}
}
/// <summary>
/// Handle LIFT's "note" entity
/// </summary>
/// <remarks>The difficult thing here is we don't handle anything but a default note.
/// Any other kind, we put in the xml residue for round-tripping.</remarks>
public void MergeInNote(PalasoDataObject extensible, string type, LiftMultiText contents, string rawXml)
{
var noteProperty = extensible.GetProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
bool alreadyHaveAOne= !MultiText.IsEmpty(noteProperty);
bool weCanHandleThisType = string.IsNullOrEmpty(type) ||type == "general";
if (!alreadyHaveAOne && weCanHandleThisType)
{
List<String> writingSystemAlternatives = new List<string>(contents.Count);
foreach (KeyValuePair<string, string> pair in contents.AsSimpleStrings)
{
writingSystemAlternatives.Add(pair.Key);
}
noteProperty = extensible.GetOrCreateProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
MergeIn(noteProperty, contents);
}
else //residue
{
var residue = extensible.GetOrCreateProperty<EmbeddedXmlCollection>(PalasoDataObject.GetEmbeddedXmlNameForProperty(PalasoDataObject.WellKnownProperties.Note));
residue.Values.Add(rawXml);
// var r = extensible.GetProperty<EmbeddedXmlCollection>(PalasoDataObject.GetEmbeddedXmlNameForProperty(PalasoDataObject.WellKnownProperties.Note));
// Debug.Assert(r != null);
}
}
public PalasoDataObject GetOrMakeParentReversal(PalasoDataObject parent,
LiftMultiText contents,
string type)
{
return null; // we'll get what we need from the rawxml of MergeInReversal
}
public PalasoDataObject MergeInReversal(LexSense sense,
PalasoDataObject parent,
LiftMultiText contents,
string type,
string rawXml)
{
sense.GetOrCreateProperty<EmbeddedXmlCollection>("reversal").Values.Add(rawXml);
return null;
}
public PalasoDataObject MergeInEtymology(LexEntry entry,
string source,
string type,
LiftMultiText form,
LiftMultiText gloss,
string rawXml)
{
entry.GetOrCreateProperty<EmbeddedXmlCollection>("etymology").Values.Add(rawXml);
return null;
}
public void ProcessRangeElement(string range,
string id,
string guid,
string parent,
LiftMultiText description,
LiftMultiText label,
LiftMultiText abbrev,
string rawXml) {}
public void ProcessFieldDefinition(string tag, LiftMultiText description) {}
public void MergeInGrammaticalInfo(PalasoDataObject senseOrReversal,
string val,
List<Trait> traits)
{
LexSense sense = senseOrReversal as LexSense;
if (sense == null)
{
return; //todo: preserve grammatical info on reversal, when we hand reversals
}
OptionRef o =
sense.GetOrCreateProperty<OptionRef>(LexSense.WellKnownProperties.PartOfSpeech);
o.Value = val;
if (traits != null)
{
foreach (Trait trait in traits)
{
if (trait.Name == "flag" && int.Parse(trait.Value) > 0)
{
o.IsStarred = true;
}
else
{
o.EmbeddedXmlElements.Add(string.Format(@"<trait name='{0}' value='{1}'/>", trait.Name, trait.Value));
}
}
}
}
private static void AddOrAppendMultiTextProperty(PalasoDataObject dataObject,
LiftMultiText contents,
string propertyName,
string noticeToPrependIfNotEmpty)
{
MultiText mt = dataObject.GetOrCreateProperty<MultiText>(propertyName);
mt.MergeInWithAppend(MultiText.Create(contents),
string.IsNullOrEmpty(noticeToPrependIfNotEmpty)
? "; "
: noticeToPrependIfNotEmpty);
AddAnnotationsToMultiText(contents, mt);
//dataObject.GetOrCreateProperty<string>(propertyName) mt));
}
/*
private static void AddMultiTextProperty(PalasoDataObject dataObject, LiftMultiText contents, string propertyName)
{
dataObject.Properties.Add(
new KeyValuePair<string, object>(propertyName,
MultiText.Create(contents)));
}
*/
/// <summary>
/// Handle LIFT's "field" entity which can be found on any subclass of "extensible"
/// </summary>
public void MergeInField(PalasoDataObject extensible,
string typeAttribute,
DateTime dateCreated,
DateTime dateModified,
LiftMultiText contents,
List<Trait> traits)
{
MultiText t = MultiText.Create(contents.AsSimpleStrings);
//enchance: instead of KeyValuePair, make a LiftField class, so we can either keep the
// other field stuff as xml (in order to round-trip it) or model it.
extensible.Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>(typeAttribute, t));
if (traits != null)
{
foreach (var trait in traits)
{
t.EmbeddedXmlElements.Add(string.Format(@"<trait name='{0}' value='{1}'/>", trait.Name, trait.Value));
}
}
}
/// <summary>
/// Handle LIFT's "trait" entity,
/// which can be found on any subclass of "extensible", on any "field", and as
/// a subclass of "annotation".
/// </summary>
public void MergeInTrait(PalasoDataObject extensible, Trait trait)
{
if (String.IsNullOrEmpty(trait.Name))
{
//"log skipping..."
return;
}
if (ExpectedOptionTraits.Contains(trait.Name))
{
OptionRef o = extensible.GetOrCreateProperty<OptionRef>(trait.Name);
o.Value = trait.Value.Trim();
}
else if (trait.Name.StartsWith("flag-"))
{
extensible.SetFlag(trait.Name);
}
// if it is unknown assume it is a collection.
else //if (ExpectedOptionCollectionTraits.Contains(trait.Name))
{
var key = trait.Value.Trim();
OptionRefCollection refs =
extensible.GetOrCreateProperty<OptionRefCollection>(trait.Name);
if(trait.Name == LexSense.WellKnownProperties.SemanticDomainDdp4)
{
if (_semanticDomainsList!=null && _semanticDomainsList.GetOptionFromKey(key) == null)
{
var match =_semanticDomainsList.Options.FirstOrDefault(option => option.Key.StartsWith(key));
if(match !=null)
{
refs.Add(match.Key);
return;
}
}
}
refs.Add(key);
}
//else
//{
// //"log skipping..."
//}
}
public void MergeInRelation(PalasoDataObject extensible,
string relationFieldId,
string targetId,
string rawXml)
{
if (String.IsNullOrEmpty(relationFieldId))
{
return; //"log skipping..."
}
//the "field name" of a relation equals the name of the relation type
LexRelationCollection collection =
extensible.GetOrCreateProperty<LexRelationCollection>(relationFieldId);
LexRelation relation = new LexRelation(relationFieldId, targetId, extensible);
if (!string.IsNullOrEmpty(rawXml))
{
var dom = new XmlDocument();
dom.LoadXml(rawXml);
foreach (XmlNode child in dom.FirstChild.ChildNodes)
{
relation.EmbeddedXmlElements.Add(child.OuterXml);
}
}
collection.Relations.Add(relation);
}
public IEnumerable<string> ExpectedOptionTraits
{
get; set;
}
public IList<string> ExpectedOptionCollectionTraits
{
get { return _expectedOptionCollectionTraits; }
}
// public ProgressState ProgressState
// {
// set
// {
// _progressState = value;
// }
// }
private static void MergeIn(MultiTextBase multiText, LiftMultiText forms)
{
multiText.MergeIn(MultiText.Create(forms.AsSimpleStrings, forms.AllSpans));
AddAnnotationsToMultiText(forms, multiText);
}
public void Dispose()
{
//_entries.Dispose();
}
#region ILexiconMerger<PalasoDataObject,LexEntry,LexSense,LexExampleSentence> Members
public void FinishEntry(LexEntry entry)
{
entry.GetOrCreateId(false);
if (AfterEntryRead != null)
{
AfterEntryRead.Invoke(entry, new EntryEvent(entry));
}
// PostProcessSenses(entry);
//_dataMapper.FinishCreateEntry(entry);
entry.ModifiedTimeIsLocked = false;
entry.Clean();
}
public class EntryEvent : EventArgs
{
public LexEntry Entry { get; set; }
public EntryEvent(LexEntry entry)
{
Entry = entry;
}
}
//
/// <summary>
/// We do this because in linguist tools, there is a distinction that we don't want to
/// normally make in WeSay. There, "gloss" is the first pass at a definition, but its
/// really just for interlinearlization. That isn't a distinction we want our user
/// to bother with.
/// </summary>
/// <param name="entry"></param>
// private void PostProcessSenses(LexEntry entry)
// {
// foreach (LexSense sense in entry.Senses)
// {
// CopyOverGlossesIfDefinitionsMissing(sense);
// FixUpOldLiteralMeaningMistake(entry, sense);
// }
// }
public void MergeInMedia(PalasoDataObject pronunciation, string href, LiftMultiText caption)
{
// review: Currently ignore media. See WS-1128
}
#endregion
}
}
| |
// -----------------------------------------------------------------------------
// Calculator Example for Rainer Hessmer's C# port of
// Samek's Quantum Hierarchical State Machine.
//
// Author: David Shields (david@shields.net)
// This code is adapted from Samek's C example.
// See the following site for the statechart:
// http://www.quantum-leaps.com/cookbook/recipes.htm
//
// References:
// Practical Statecharts in C/C++; Quantum Programming for Embedded Systems
// Author: Miro Samek, Ph.D.
// http://www.quantum-leaps.com/book.htm
//
// Rainer Hessmer, Ph.D. (rainer@hessmer.org)
// http://www.hessmer.org/dev/qhsm/
// -----------------------------------------------------------------------------
using System;
using qf4net;
namespace CalculatorHSM
{
// Define preprocessor variable STATIC_TRANS in order to use the implementation of the calculator that
// uses static transitions which can be used even in cases where another state machine is derived from this
// state machine
/// <summary>
/// Calculator state machine example for Rainer Hessmer's C# port of HQSM
/// </summary>
public sealed class Calc : QHsm
{
#if (STATIC_TRANS)
#region Boiler plate static stuff
private static new TransitionChainStore s_TransitionChainStore =
new TransitionChainStore(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static Calc()
{
s_TransitionChainStore.ShrinkToActualSize();
}
/// <summary>
/// Getter for an optional <see cref="TransitionChainStore"/> that can hold cached
/// <see cref="TransitionChain"/> objects that are used to optimize static transitions.
/// </summary>
protected override TransitionChainStore TransChainStore
{
get { return s_TransitionChainStore; }
}
#endregion
#endif
//communication with main form is via these events:
public delegate void CalcDisplayHandler(object sender, CalcDisplayEventArgs e);
public event CalcDisplayHandler DisplayValue;
public event CalcDisplayHandler DisplayState;
private bool isHandled;
public bool IsHandled
{
get{return isHandled;}
set{isHandled = value;}
}//IsHandled
private string myDisplay;
private double myOperand1;
private double myOperand2;
private char myOperator;
private const int PRECISION = 14;
private QState Calculate;
private QState Ready;
private QState Result;
private QState Begin;
private QState Negated1;
private QState Operand1;
private QState Zero1;
private QState Int1;
private QState Frac1;
private QState OpEntered;
private QState Negated2;
private QState Operand2;
private QState Zero2;
private QState Int2;
private QState Frac2;
private QState Final;
#if (STATIC_TRANS)
private static int s_TranIdx_Calculate_Calculate = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Calculate_Final = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoCalculate(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("calc");
return null;
case (int)QSignals.Init:
Clear();
InitializeState(Ready);
return null;
case (int)CalcSignals.ClearAll:
Clear();
#if (STATIC_TRANS)
TransitionTo(Calculate, s_TranIdx_Calculate_Calculate);
#else
TransitionTo(Calculate);
#endif
return null;
case (int)CalcSignals.Quit:
#if (STATIC_TRANS)
TransitionTo(Final, s_TranIdx_Calculate_Final);
#else
TransitionTo(Final);
#endif
return null;
}
if (qevent.QSignal >= (int)QSignals.UserSig)
{
isHandled = false;
}
return this.TopState;
}
#if (STATIC_TRANS)
private static int s_TranIdx_Ready_Zero1 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Ready_Int1 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Ready_Frac1 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Ready_OpEntered = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoReady(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("ready");
return null;
case (int)QSignals.Init:
InitializeState(Begin);
return null;
case (int)CalcSignals.ZeroDigit:
Clear();
#if (STATIC_TRANS)
TransitionTo(Zero1, s_TranIdx_Ready_Zero1);
#else
TransitionTo(Zero1);
#endif
return null;
case (int)CalcSignals.NonZeroDigit:
Clear();
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Int1, s_TranIdx_Ready_Int1);
#else
TransitionTo(Int1);
#endif
return null;
case (int)CalcSignals.DecimalPoint:
Clear();
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Frac1, s_TranIdx_Ready_Frac1);
#else
TransitionTo(Frac1);
#endif
return null;
case (int)CalcSignals.Operator:
this.myOperand1 = double.Parse(myDisplay);
myOperator = ((CalcEvent)qevent).KeyChar;
#if (STATIC_TRANS)
TransitionTo(OpEntered, s_TranIdx_Ready_OpEntered);
#else
TransitionTo(OpEntered);
#endif
return null;
}
return Calculate;
}
private QState DoResult(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("result");
Eval();
return null;
}
return Ready;
}
#if (STATIC_TRANS)
private static int s_TranIdx_Begin_Negated1 = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoBegin(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("begin");
return null;
case (int)CalcSignals.Operator:
if (((CalcEvent)qevent).KeyChar == '-')
{
#if (STATIC_TRANS)
TransitionTo(Negated1, s_TranIdx_Begin_Negated1);
#else
TransitionTo(Negated1);
#endif
return null; // event handled
}
//Uncomment the follow "else-if" block to get the same
//behavior as the C version. It was commented out for
//the following reason:
//
//Looking for a unary "+" introduces a small inconsistency:
//Multiplication and division operators are accepted with
//operand1 defaulting to zero. However, the addition operator
//does not behave in the same way.
//
//else if (((CalcEvent)qevent).KeyChar == '+')
//{ // unary "+"
// return null; // event handled
//}
//
//
//One alternative is to ignore '+' '*' and '/' so they all behave
//consistently
//
break; // event unhandled!
}
return Ready;
}
#if (STATIC_TRANS)
private static int s_TranIdx_Negated1_Begin = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Negated1_Zero1 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Negated1_Int1 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Negated1_Frac1 = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoNegated1(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("negated1");
Negate();
return null;
case (int)CalcSignals.ClearEntry:
Clear();
#if (STATIC_TRANS)
TransitionTo(Begin, s_TranIdx_Negated1_Begin);
#else
TransitionTo(Begin);
#endif
return null;
case (int)CalcSignals.ZeroDigit:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Zero1, s_TranIdx_Negated1_Zero1);
#else
TransitionTo(Zero1);
#endif
return null;
case (int)CalcSignals.NonZeroDigit:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Int1, s_TranIdx_Negated1_Int1);
#else
TransitionTo(Int1);
#endif
return null;
case (int)CalcSignals.DecimalPoint:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Frac1, s_TranIdx_Negated1_Frac1);
#else
TransitionTo(Frac1);
#endif
return null;
}
return Calculate;
}
#if (STATIC_TRANS)
private static int s_TranIdx_Operand1_Begin = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Operand1_OpEntered = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoOperand1(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("operand1");
return null;
case (int)CalcSignals.ClearEntry:
Clear();
#if (STATIC_TRANS)
TransitionTo(Begin, s_TranIdx_Operand1_Begin);
#else
TransitionTo(Begin);
#endif
return null;
case (int)CalcSignals.Operator:
this.myOperand1 = double.Parse(myDisplay);
myOperator = ((CalcEvent)qevent).KeyChar;
#if (STATIC_TRANS)
TransitionTo(OpEntered, s_TranIdx_Operand1_OpEntered);
#else
TransitionTo(OpEntered);
#endif
return null;
}
return Calculate;
}
#if (STATIC_TRANS)
private static int s_TranIdx_Zero1_Int1 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Zero1_Frac1 = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoZero1(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("zero1");
return null;
case (int)CalcSignals.NonZeroDigit:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Int1, s_TranIdx_Zero1_Int1);
#else
TransitionTo(Int1);
#endif
return null;
case (int)CalcSignals.DecimalPoint:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Frac1, s_TranIdx_Zero1_Frac1);
#else
TransitionTo(Frac1);
#endif
return null;
}
return Operand1;
}
#if (STATIC_TRANS)
private static int s_TranIdx_Int1_Frac1 = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoInt1(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("int1");
return null;
case (int)CalcSignals.ZeroDigit:
case (int)CalcSignals.NonZeroDigit:
Insert(((CalcEvent)qevent).KeyChar);
return null;
case (int)CalcSignals.DecimalPoint:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Frac1, s_TranIdx_Int1_Frac1);
#else
TransitionTo(Frac1);
#endif
return null;
}
return Operand1;
}
private QState DoFrac1(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("frac1");
return null;
case (int)CalcSignals.ZeroDigit:
case (int)CalcSignals.NonZeroDigit:
Insert(((CalcEvent)qevent).KeyChar);
return null;
}
return Operand1;
}
#if (STATIC_TRANS)
private static int s_TranIdx_OpEntered_Negated2 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_OpEntered_Zero2 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_OpEntered_Int2 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_OpEntered_Frac2 = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoOpEntered(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("opEntered");
return null;
case (int)CalcSignals.Operator:
if (((CalcEvent)qevent).KeyChar == '-')
{
Clear();
#if (STATIC_TRANS)
TransitionTo(Negated2, s_TranIdx_OpEntered_Negated2);
#else
TransitionTo(Negated2);
#endif
}
return null;
case (int)CalcSignals.ZeroDigit:
Clear();
#if (STATIC_TRANS)
TransitionTo(Zero2, s_TranIdx_OpEntered_Zero2);
#else
TransitionTo(Zero2);
#endif
return null;
case (int)CalcSignals.NonZeroDigit:
Clear();
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Int2, s_TranIdx_OpEntered_Int2);
#else
TransitionTo(Int2);
#endif
return null;
case (int)CalcSignals.DecimalPoint:
Clear();
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Frac2, s_TranIdx_OpEntered_Frac2);
#else
TransitionTo(Frac2);
#endif
return null;
}
return Calculate;
}
#if (STATIC_TRANS)
private static int s_TranIdx_Negated2_OpEntered = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Negated2_Zero2 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Negated2_Int2 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Negated2_Frac2 = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoNegated2(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("negated2");
Negate();
return null;
case (int)CalcSignals.ClearEntry:
#if (STATIC_TRANS)
TransitionTo(OpEntered, s_TranIdx_Negated2_OpEntered);
#else
TransitionTo(OpEntered);
#endif
return null;
case (int)CalcSignals.ZeroDigit:
#if (STATIC_TRANS)
TransitionTo(Zero2, s_TranIdx_Negated2_Zero2);
#else
TransitionTo(Zero2);
#endif
return null;
case (int)CalcSignals.NonZeroDigit:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Int2, s_TranIdx_Negated2_Int2);
#else
TransitionTo(Int2);
#endif
return null;
case (int)CalcSignals.DecimalPoint:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Frac2, s_TranIdx_Negated2_Frac2);
#else
TransitionTo(Frac2);
#endif
return null;
}
return Calculate;
}
#if (STATIC_TRANS)
private static int s_TranIdx_Operand2_OpEntered = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Operand2_Result = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoOperand2(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("operand2");
return null;
case (int)CalcSignals.ClearEntry:
Clear();
#if (STATIC_TRANS)
TransitionTo(OpEntered, s_TranIdx_Operand2_OpEntered);
#else
TransitionTo(OpEntered);
#endif
return null;
case (int)CalcSignals.Operator:
this.myOperand2 = double.Parse(myDisplay);
Eval();
this.myOperand1 = double.Parse(myDisplay);
myOperator = ((CalcEvent)qevent).KeyChar;
#if (STATIC_TRANS)
TransitionTo(OpEntered, s_TranIdx_Operand2_OpEntered);
#else
TransitionTo(OpEntered);
#endif
return null;
case (int)CalcSignals.EqualSign:
this.myOperand2 = double.Parse(myDisplay);
#if (STATIC_TRANS)
TransitionTo(Result, s_TranIdx_Operand2_Result);
#else
TransitionTo(Result);
#endif
return null;
}
return Calculate;
}
#if (STATIC_TRANS)
private static int s_TranIdx_Zero2_Int2 = s_TransitionChainStore.GetOpenSlot();
private static int s_TranIdx_Zero2_Frac2 = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoZero2(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("zero2");
return null;
case (int)CalcSignals.NonZeroDigit:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Int2, s_TranIdx_Zero2_Int2);
#else
TransitionTo(Int2);
#endif
return null;
case (int)CalcSignals.DecimalPoint:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Frac2, s_TranIdx_Zero2_Frac2);
#else
TransitionTo(Frac2);
#endif
return null;
}
return Operand2;
}
#if (STATIC_TRANS)
private static int s_TranIdx_Int2_Frac2 = s_TransitionChainStore.GetOpenSlot();
#endif
private QState DoInt2(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("int2");
return null;
case (int)CalcSignals.ZeroDigit:
case (int)CalcSignals.NonZeroDigit:
Insert(((CalcEvent)qevent).KeyChar);
return null;
case (int)CalcSignals.DecimalPoint:
Insert(((CalcEvent)qevent).KeyChar);
#if (STATIC_TRANS)
TransitionTo(Frac2, s_TranIdx_Int2_Frac2);
#else
TransitionTo(Frac2);
#endif
return null;
}
return Operand2;
}
private QState DoFrac2(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("frac2");
return null;
case (int)CalcSignals.ZeroDigit:
case (int)CalcSignals.NonZeroDigit:
Insert(((CalcEvent)qevent).KeyChar);
return null;
}
return Operand2;
}
//UNDONE: revise this code
private QState DoFinal(IQEvent qevent)
{
switch (qevent.QSignal)
{
case (int)QSignals.Entry:
OnDisplayState("HSM terminated");
singleton = null;
CalcForm.Instance.Close();
System.Windows.Forms.Application.Exit();
return null;
}
return this.TopState;
}
private void Clear()
{
this.myDisplay = " 0";
OnDisplayValue(myDisplay);
}//Clear
private void Insert(char keyChar)
{
if (this.myDisplay.Length < PRECISION)
{
if (keyChar != '.')//TODO: clean this logic up
{
if (myDisplay == " 0")
{
this.myDisplay = " ";
}
else if (myDisplay == "-0")
{
this.myDisplay = "-";
}
}
this.myDisplay += keyChar.ToString();
OnDisplayValue(myDisplay);
}
}
private void Negate()
{
string temp = myDisplay.Remove(0, 1);
myDisplay = temp.Insert(0, "-");
OnDisplayValue(myDisplay);
}
private void Eval()
{
double r = double.NaN;
switch (myOperator)
{
case '+':
r = myOperand1 + myOperand2;
break;
case '-':
r = myOperand1 - myOperand2;
break;
case '*':
r = myOperand1 * myOperand2;
break;
case '/':
if (myOperand2 != 0.0)
{
r = myOperand1 / myOperand2;
}
else
{
System.Windows.Forms.MessageBox.Show("Cannot Divide by 0", "Calculator HSM",
System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
r = 0.0;
}
break;
default:
System.Diagnostics.Debug.Assert(false);
break;
}
if (-1.0e10 < r && r < 1.0e10)
{
//sprintf(myDisplay, "%24.11g", r);
myDisplay = r.ToString();//TODO: add formatting
}
else
{
System.Windows.Forms.MessageBox.Show("Result out of range", "Calculator HSM",
System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
Clear();
}
OnDisplayValue(myDisplay);
}
private void OnDisplayState(string stateInfo)
{
if (DisplayState != null)
{
DisplayState(this, new CalcDisplayEventArgs(stateInfo));
}
}//OnDisplayState
private void OnDisplayValue(string valueInfo)
{
if (DisplayValue != null)
{
DisplayValue(this, new CalcDisplayEventArgs(valueInfo));
}
}//OnDisplayValue
/// <summary>
/// Is called inside of the function Init to give the deriving class a chance to
/// initialize the state machine.
/// </summary>
protected override void InitializeStateMachine()
{
InitializeState(Calculate); // initial transition
}
private Calc()
{
Calculate = new QState(this.DoCalculate);
Ready = new QState(this.DoReady);
Result = new QState(this.DoResult);
Begin = new QState(this.DoBegin);
Negated1 = new QState(this.DoNegated1);
Operand1 = new QState(this.DoOperand1);
Zero1 = new QState(this.DoZero1);
Int1 = new QState(this.DoInt1);
Frac1 = new QState(this.DoFrac1);
OpEntered = new QState(this.DoOpEntered);
Negated2 = new QState(this.DoNegated2);
Operand2 = new QState(this.DoOperand2);
Zero2 = new QState(this.DoZero2);
Int2 = new QState(this.DoInt2);
Frac2 = new QState(this.DoFrac2);
Final = new QState(this.DoFinal);
}
//
//Thread-safe implementation of singleton as a property
//
private static volatile Calc singleton = null;
private static object sync = new object();//for static lock
public static Calc Instance
{
get
{
if (singleton == null)
{
lock (sync)
{
if (singleton == null)
{
singleton = new Calc();
singleton.Init();
}
}
}
return singleton;
}
}//Instance
}//class Calc
public class CalcDisplayEventArgs : EventArgs
{
private string s;
public string Message { get { return s; } }
public CalcDisplayEventArgs(string message) { s = message;}
}
}//namespace
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Text;
/// <summary>
/// Game Jolt API main class.
/// </summary>
public class GJAPI : MonoBehaviour
{
#region Singleton Pattern
/// <summary>
/// The GJAPI instance.
/// </summary>
static GJAPI instance;
/// <summary>
/// Gets the GJAPI instance.
/// </summary>
/// <value>
/// The GJAPI instance.
/// </value>
public static GJAPI Instance
{
get
{
if (instance == null)
{
instance = new GameObject ("_GameJoltAPI").AddComponent<GJAPI> ();
DontDestroyOnLoad (instance.gameObject);
}
return instance;
}
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the application quit.
/// </summary>
void OnDestroy ()
{
StopAllCoroutines ();
user = null;
users = null;
sessions = null;
trophies = null;
scores = null;
data = null;
instance = null;
Debug.Log ("GJAPI: Quit");
}
#endregion Singleton Pattern
#region GameJolt API Paths
/// <summary>
/// REST API paths.
/// </summary>
const string
PROTOCOL = "http://",
API_ROOT = "gamejolt.com/api/game/";
#endregion GameJolt API Paths
#region API Properties
int gameId = 0;
/// <summary>
/// Gets the game identifier.
/// </summary>
/// <value>
/// The game identifier.
/// </value>
public static int GameID
{
get { return Instance.gameId; }
}
string privateKey = string.Empty;
/// <summary>
/// Gets the game private key.
/// </summary>
/// <value>
/// The game private key.
/// </value>
public static string PrivateKey
{
get { return Instance.privateKey; }
}
bool verbose = true;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="GJAPI"/> is verbose.
/// </summary>
/// <value>
/// <c>true</c> if verbose; otherwise, <c>false</c>.
/// </value>
public static bool Verbose
{
get { return Instance.verbose; }
set { Instance.verbose = value; }
}
int version = 0;
/// <summary>
/// Gets or sets the API version.
/// </summary>
/// <value>
/// The API version.
/// </value>
public static int Version
{
get { return Instance.version; }
set { Instance.version = value; }
}
float timeout = 5f;
/// <summary>
/// Gets or sets the timeout length for API calls.
/// </summary>
/// <value>
/// The timeout length.
/// </value>
public static float Timeout
{
get { return Instance.timeout; }
set { Instance.timeout = value; }
}
#endregion API Properties
#region API User
GJUser user = null;
/// <summary>
/// Gets the user.
/// </summary>
/// <value>
/// The user.
/// </value>
public static GJUser User
{
get { return Instance.user; }
set { Instance.user = value; }
}
#endregion API User
#region API Groups
private GJUsersMethods users;
/// <summary>
/// Gets the users methods group.
/// </summary>
/// <value>
/// The users methods group.
/// </value>
public static GJUsersMethods Users
{
get
{
if (Instance.users == null)
{
Instance.users = new GJUsersMethods ();
}
return Instance.users;
}
}
private GJSessionsMethods sessions;
/// <summary>
/// Gets the sessions methods group.
/// </summary>
/// <value>
/// The sessions methods group.
/// </value>
public static GJSessionsMethods Sessions
{
get
{
if (Instance.sessions == null)
{
Instance.sessions = new GJSessionsMethods ();
}
return Instance.sessions;
}
}
private GJTrophiesMethods trophies;
/// <summary>
/// Gets the trophies methods group.
/// </summary>
/// <value>
/// The trophies methods group.
/// </value>
public static GJTrophiesMethods Trophies
{
get
{
if (Instance.trophies == null)
{
Instance.trophies = new GJTrophiesMethods ();
}
return Instance.trophies;
}
}
private GJScoresMethods scores;
/// <summary>
/// Gets the scores methods group.
/// </summary>
/// <value>
/// The scores methods group.
/// </value>
public static GJScoresMethods Scores
{
get
{
if (Instance.scores == null)
{
Instance.scores = new GJScoresMethods ();
}
return Instance.scores;
}
}
private GJDataMehods data;
/// <summary>
/// Gets the data methods group.
/// </summary>
/// <value>
/// The data methods group.
/// </value>
public static GJDataMehods Data
{
get
{
if (Instance.data == null)
{
Instance.data = new GJDataMehods ();
}
return Instance.data;
}
}
#endregion API Groups
#region General
// <summary>
/// Init the GJAPI with the specified gameId, privateKey, verbose and version.
/// </summary>
/// <param name='gameId'>
/// The Game ID.
/// </param>
/// <param name='privateKey'>
/// The Game Private Key.
/// </param>
/// <param name='verbose'>
/// A value indicating whether this <see cref="GJAPI"/> is verbose. Default true.
/// </param>
/// <param name='version'>
/// The API version. Default 1.
/// </param>
public static void Init (int gameId, string privateKey, bool verbose = true, int version = 1)
{
Instance.gameId = gameId;
Instance.privateKey = privateKey.Trim ();
Instance.verbose = verbose;
Instance.version = version;
Instance.user = null;
Instance.GJDebug ("Initialisation complete.\n" + Instance.ToString());
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="GJAPI"/>.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents the current <see cref="GJAPI"/>.
/// </returns>
public override string ToString ()
{
StringBuilder msg = new StringBuilder();
msg.AppendLine (" [GJAPI]");
msg.AppendFormat ("Game ID: {0}\n", Instance.gameId.ToString ());
#if UNITY_EDITOR
msg.AppendFormat ("Private Key: {0}\n", Instance.privateKey);
#else
msg.Append ("Private Key: [FILTERED]\n");
#endif
msg.AppendFormat ("Verbose: {0}\n", Instance.verbose.ToString ());
msg.AppendFormat ("Version: {0}\n", Instance.version.ToString ());
return msg.ToString ();
}
#endregion General
// Most of Internal Methods need to be public so API groups can access them.
// However, they are not static so it is needed to do GJAPI.Instance.MethodName instead of GJAPI.MethodName
// It may help users not to get confused with methods they shouldn't call.
#region Internal Methods
/// <summary>
/// Send a request to the Game Jolt REST API.
/// </summary>
/// <param name='method'>
/// The request method.
/// </param>
/// <param name='parameters'>
/// The parameters.
/// </param>
/// <param name='requireVerified'>
/// A value indicating whether a verified user is required.
/// </param>
/// <param name='OnResponseComplete'>
/// The method to call when the request is completed.
/// </param>
public void Request (string method, Dictionary<string,string> parameters, bool requireVerified = false, Action<string> OnResponseComplete = null)
{
if (gameId == 0 || privateKey == string.Empty || version == 0)
{
GJDebug ("Please initialise GameJolt API first.", LogType.Error);
if (OnResponseComplete != null)
{
OnResponseComplete ("Error:\nAPI needs to be initialised first.");
}
return;
}
if (parameters == null)
{
parameters = new Dictionary<string, string>();
}
if (requireVerified)
{
if (this.user == null)
{
GJDebug ("Authentification required for " + method, LogType.Error);
if (OnResponseComplete != null)
{
OnResponseComplete ("Error:\nThe method " + method + " requires authentification.");
}
return;
}
else
{
parameters.Add ("username", this.user.Name);
parameters.Add ("user_token", this.user.Token);
}
}
string url = GetRequestURL (method, parameters);
StartCoroutine (OpenURLAndGetResponse (url, OnResponseComplete));
}
/// /// <summary>
/// Send a request to the Game Jolt REST API.
/// </summary>
/// <param name='method'>
/// The request method.
/// </param>
/// <param name='parameters'>
/// The parameters.
/// </param>
/// </param>
/// <param name='postParameters'>
/// The POST parameters.
/// </param>
/// <param name='requireVerified'>
/// A value indicating whether a verified user is required.
/// </param>
/// <param name='OnResponseComplete'>
/// The method to call when the request is completed.
/// </param>
public void Request (string method, Dictionary<string,string> parameters, Dictionary<string,string> postParameters, bool requireVerified = false, Action<string> OnResponseComplete = null)
{
if (gameId == 0 || privateKey == string.Empty || version == 0)
{
GJDebug ("Please initialise GameJolt API first.", LogType.Error);
if (OnResponseComplete != null)
{
OnResponseComplete ("Error:\nAPI needs to be initialised first.");
}
return;
}
if (parameters == null)
{
parameters = new Dictionary<string, string>();
}
if (requireVerified)
{
if (this.user == null)
{
GJDebug ("Authentification required for " + method, LogType.Error);
if (OnResponseComplete != null)
{
OnResponseComplete ("Error:\nThe method " + method + " requires authentification.");
}
return;
}
else
{
parameters.Add ("username", this.user.Name);
parameters.Add ("user_token", this.user.Token);
}
}
string url = GetRequestURL (method, parameters);
StartCoroutine (OpenURLAndGetResponse (url, postParameters, OnResponseComplete));
}
/// <summary>
/// Gets the formated URL for the method with the parameters.
/// </summary>
/// <returns>
/// The request URL.
/// </returns>
/// <param name='method'>
/// The method.
/// </param>
/// <param name='parameters'>
/// The parameters.
/// </param>
string GetRequestURL (string method, Dictionary<string,string> parameters)
{
StringBuilder url = new StringBuilder ();
url.Append (PROTOCOL);
url.Append (API_ROOT);
url.Append ("v");
url.Append (this.version);
url.Append ("/");
url.Append (method);
url.Append ("?game_id=");
url.Append (this.gameId);
foreach (KeyValuePair<string,string> parameter in parameters)
{
url.Append ("&");
url.Append (parameter.Key);
url.Append ("=");
url.Append (parameter.Value.Replace (" ", "%20"));
}
string signature = GetSignature (url.ToString ());
url.Append ("&signature=");
url.Append (signature);
return url.ToString();
}
/// <summary>
/// Gets the request signature.
/// </summary>
/// <returns>
/// The signature.
/// </returns>
/// <param name='input'>
/// The base request URL.
/// </param>
string GetSignature (string input)
{
string signature = MD5 (input + this.privateKey);
// Append zeroes (0) if the signature isn't 32 characters long.
if (signature.Length != 32)
{
signature += new string ('0', 32 - signature.Length);
}
return signature;
}
/// <summary>
/// Encrypt the input string to MD5.
/// </summary>
/// <returns>
/// The encrypted string to MD5.
/// </returns>
/// <param name='input'>
/// The string to encrypt.
/// </param>
/// <remarks>
/// This method is taken from the first version of the Unity Game Jolt API and was written by Ashley Gwinnell and Daniel Twomey.
/// </remarks>
string MD5 (string input)
{
// WP8 and Windows Metro fix kindly provided by runewake2 [http://gamejolt.com/profile/runewake2/2008/]
#if UNITY_WP8 || UNITY_METRO
byte[] data = MD5Core.GetHash(input, System.Text.Encoding.ASCII);
#else
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider ();
byte [] data = System.Text.Encoding.ASCII.GetBytes (input);
data = x.ComputeHash (data);
#endif
string ret = "";
for (int i=0; i < data.Length; i++)
ret += data [i].ToString("x2").ToLower();
return ret;
}
/// <summary>
/// Opens the URL wait for the response.
/// </summary>
/// <returns>
/// The response.
/// </returns>
/// <param name='url'>
/// The URL to open.
/// </param>
/// <param name='OnResponseComplete'>
/// The method to call when the response is recieved.
/// </param>
IEnumerator OpenURLAndGetResponse (string url, Action<string> OnResponseComplete = null)
{
GJDebug ("Opening URL: " + url);
WWW www = new WWW (url);
float callTimeout = Time.time + timeout;
string msg = null;
while (!www.isDone)
{
if (Time.time > callTimeout)
{
GJDebug ("Timeout opening URL:\n" + url, LogType.Error);
msg = "Timeout";
break;
}
yield return new WaitForEndOfFrame ();
}
if (www.error != null)
{
GJDebug ("Error opening URL:\n" + www.error, LogType.Error);
msg = www.error;
}
if (OnResponseComplete != null)
{
// If msg is not null, it means something went wrong.
// Thus, we shouldn't read www.text because it's not ready.
OnResponseComplete (msg ?? www.text);
}
}
/// <summary>
/// Opens the URL wait for the response.
/// </summary>
/// <returns>
/// The response.
/// </returns>
/// <param name='url'>
/// The URL to open.
/// </param>
/// <param name='postParameters'>
/// The POST parameters.
/// </param>
/// <param name='OnResponseComplete'>
/// The method to call when the response is recieved.
/// </param>
IEnumerator OpenURLAndGetResponse (string url, Dictionary<string,string> postParameters, Action<string> OnResponseComplete = null)
{
StringBuilder debugMsg = new StringBuilder ();
debugMsg.AppendFormat ("Opening URL with post parameters: {0}\n", url);
if (postParameters == null || postParameters.Count == 0)
{
GJDebug ("Post parameters is null. Can't make the request.", LogType.Error);
yield break;
}
WWWForm form = new WWWForm ();
foreach (KeyValuePair<string,string> postParameter in postParameters)
{
debugMsg.AppendFormat ("Post parameter: {0}: {1}\n", postParameter.Key, postParameter.Value);
form.AddField (postParameter.Key, postParameter.Value);
}
GJDebug (debugMsg.ToString ());
WWW www = new WWW (url, form);
float callTimeout = Time.time + 5f;
string msg = null;
while (!www.isDone)
{
if (Time.time > callTimeout)
{
GJDebug ("Timeout opening URL:\n" + url, LogType.Error);
msg = "Timeout";
break;
}
yield return new WaitForEndOfFrame ();
}
if (www.error != null)
{
GJDebug ("Error opening URL:\n" + www.error, LogType.Error);
msg = www.error;
}
if (OnResponseComplete != null)
{
// If msg is not null, it means something went wrong.
// Thus, we shouldn't read www.text because it's not ready.
OnResponseComplete (msg ?? www.text);
}
}
/// <summary>
/// Determines whether the response is successful.
/// </summary>
/// <returns>
/// <c>true</c> if the response is successful; otherwise, <c>false</c>.
/// </returns>
/// <param name='response'>
/// The response.
/// </param>
public bool IsResponseSuccessful (string response)
{
string [] lines = response.Split ('\n');
return lines [0].Trim().Equals ("success:\"true\"");
}
/// <summary>
/// Determines whether the dump response is successful.
/// </summary>
/// <returns>
/// <c>true</c> if the dump response is successful; otherwise, <c>false</c>.
/// </returns>
/// <param name='response'>
/// The dump response. Because dump response can be up to 16 MB, it is passed as a reference. However, the method won't modify it.
/// </param>
public bool IsDumpResponseSuccessful (ref string response)
{
int returnIndex = response.IndexOf ('\n');
if (returnIndex == -1)
{
GJDebug ("Wrong response format. Can't read response.", LogType.Error);
return false;
}
else
{
string success = response.Substring (0, returnIndex).Trim ();
return success == "SUCCESS";
}
}
/// <summary>
/// Converts the responses to a dictionary.
/// </summary>
/// <returns>
/// The dictionary.
/// </returns>
/// <param name='response'>
/// The response.
/// </param>
/// <param name='addIndexToKey'>
/// Add index to key. Set to true if the response is expected to have duplicated keys.
/// </param>
public Dictionary<string, string> ResponseToDictionary (string response, bool addIndexToKey = false)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
int colonIndex = 0;
string key = string.Empty;
string val = string.Empty;
string [] lines = response.Split ('\n');
int count = lines.Length;
for (int i = 0; i < count; i++)
{
if (lines [i] != string.Empty)
{
// The format of each line of the response should be key:"value"
colonIndex = lines [i].IndexOf (':');
if (colonIndex == -1)
{
GJDebug ("Wrong line format. The following line of the response will be skipped: " + lines [i], LogType.Warning);
}
else
{
key = lines [i].Substring (0, colonIndex);
val = lines [i].Substring (colonIndex + 1);
val = val.Trim().Trim ('"');
if (addIndexToKey)
{
dictionary.Add (key + i, val);
}
else
{
dictionary.Add (key, val);
}
}
}
}
return dictionary;
}
/// <summary>
/// Converts the responses to a dictionaries.
/// </summary>
/// <returns>
/// The dictionaries.
/// </returns>
/// <param name='response'>
/// The response.
/// </param>
/// <param name='addIndexToKey'>
/// Add index to key. Set to true if the response is expected to have duplicated keys.
/// </param>
public Dictionary<string,string> [] ResponseToDictionaries (string response, bool addIndexToKey = false)
{
// Using json/xml responses when retriving multiple object would be less cpu expensive
// but we want to avoid the need of adding heavy libraries (especially for browser game).
int colonIndex = 0;
int numberOfObjects = 0;
int dictionaryIndex = 0;
string key = string.Empty;
string val = string.Empty;
string firstKey = string.Empty;
string [] lines = response.Split ('\n');
int count = lines.Length;
// First, we need to know how many objects got returned.
for (int i = 0; i < count; i++)
{
if (lines [i] != string.Empty)
{
colonIndex = lines [i].IndexOf (':');
if (colonIndex != -1)
{
key = lines [i].Substring (0, colonIndex);
if (key != "success" && key != "message")
{
if (firstKey == string.Empty)
{
firstKey = key;
numberOfObjects++;
}
else if (firstKey == key)
{
numberOfObjects++;
}
}
}
}
}
firstKey = string.Empty; // Reset
// Now, we can initialise the right number of dictionaries.
Dictionary<string,string> [] dictionaries = new Dictionary<string, string> [numberOfObjects];
for (int i = 0; i < numberOfObjects; i++)
{
dictionaries [i] = new Dictionary<string,string>();
}
// Finaly, we can populate them.
for (int i = 0; i < count; i++)
{
if (lines [i] != string.Empty)
{
colonIndex = lines [i].IndexOf (':');
if (colonIndex == 1)
{
GJDebug ("Wrong line format. The following line of the response will be skipped: " + lines [i], LogType.Warning);
}
else
{
key = lines [i].Substring (0, colonIndex);
val = lines [i].Substring (colonIndex + 1);
val = val.Trim().Trim ('"');
if (key != "success" && key != "message")
{
if (firstKey == string.Empty)
{
firstKey = key;
}
else if (firstKey == key)
{
dictionaryIndex++;
}
}
if (addIndexToKey)
{
dictionaries [dictionaryIndex].Add (key + i, val);
}
else
{
dictionaries [dictionaryIndex].Add (key, val);
}
}
}
}
return dictionaries;
}
/// <summary>
/// Remove unwanted keys from the dictionary.
/// </summary>
/// <param name='dictionary'>
/// The cleaned dictionary.
/// </param>
/// <param name='keysToClean'>
/// The keys to remove from the dictionary. By default, "success" and "message".
/// </param>
public void CleanDictionary (ref Dictionary<string, string> dictionary, string [] keysToClean = null)
{
// We can't use a populated array as optional parameter unless it's null. We then populate the array in the method.
if (keysToClean == null)
{
keysToClean = new string [] { "success", "message" };
}
int count = keysToClean.Length;
for (int i = 0; i < count; i++)
{
if (dictionary.ContainsKey (keysToClean [i]))
{
dictionary.Remove (keysToClean [i]);
}
}
}
/// <summary>
/// Remove unwanted keys from the dictionaries.
/// </summary>
/// <param name='dictionary'>
/// The cleaned dictionaries.
/// </param>
/// <param name='keysToClean'>
/// The keys to remove from the dictionaries. By default, "success" and "message".
/// </param>
public void CleanDictionaries (ref Dictionary<string,string> [] dictionaries, string [] keysToClean = null)
{
int count = dictionaries.Length;
for (int i = 0; i < count; i++)
{
CleanDictionary (ref dictionaries [i], keysToClean);
}
}
/// <summary>
/// Converts the dump response to string.
/// </summary>
/// <param name='response'>
/// The dump response. Because dump response can be up to 16 MB, it is passed as a reference. However, the method won't modify it.
/// </param>
/// <param name='data'>
/// The dumpt data. Because the data can be up to 16 MB, it is passed as out.
/// </param>
public void DumpResponseToString (ref string response, out string data)
{
int returnIndex = response.IndexOf ('\n');
if (returnIndex == -1)
{
GJDebug ("Wrong response format. Can't read response.", LogType.Error);
data = string.Empty;
}
else
{
data = response.Substring (returnIndex + 1);
}
}
/// <summary>
/// Print debug information to the console only if the API is verbose.
/// </summary>
/// <param name='message'>
/// The message.
/// </param>
/// <param name='type'>
/// The message type. See <see cref="UnityEngine.LogType"/>.
/// </param>
public void GJDebug (string message, LogType type = LogType.Log)
{
if (!verbose)
{
return;
}
switch (type)
{
case LogType.Log:
default:
Debug.Log ("GJAPI: " + message);
break;
case LogType.Warning:
Debug.LogWarning ("GJAPI: " + message);
break;
case LogType.Error:
Debug.LogError ("GJAPI: " + message);
break;
}
}
#endregion Internal Methods
}
| |
//------------------------------------------------------------------------------
// <copyright file="ValidationSummary.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System.ComponentModel;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Web;
using System.Web.ModelBinding;
using System.Web.Util;
/// <devdoc>
/// <para>Displays a summary of all validation errors of
/// a page in a list, bulletted list, or single paragraph format. The errors can be displayed inline
/// and/or in a popup message box.</para>
/// </devdoc>
[Designer("System.Web.UI.Design.WebControls.ValidationSummaryDesigner, " + AssemblyRef.SystemDesign)]
public class ValidationSummary : WebControl {
private const String breakTag = "b";
private bool renderUplevel;
private bool wasForeColorSet = false;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.ValidationSummary'/> class.</para>
/// </devdoc>
public ValidationSummary() : base(HtmlTextWriterTag.Div) {
renderUplevel = false;
}
private bool IsUnobtrusive {
get {
return (Page != null && Page.UnobtrusiveValidationMode != UnobtrusiveValidationMode.None);
}
}
/// <devdoc>
/// <para>Gets or sets the display mode of the validation summary.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(ValidationSummaryDisplayMode.BulletList),
WebSysDescription(SR.ValidationSummary_DisplayMode)
]
public ValidationSummaryDisplayMode DisplayMode {
get {
object o = ViewState["DisplayMode"];
return((o == null) ? ValidationSummaryDisplayMode.BulletList : (ValidationSummaryDisplayMode)o);
}
set {
if (value < ValidationSummaryDisplayMode.List || value > ValidationSummaryDisplayMode.SingleParagraph) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["DisplayMode"] = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[
WebCategory("Behavior"),
Themeable(false),
DefaultValue(true),
WebSysDescription(SR.ValidationSummary_EnableClientScript)
]
public bool EnableClientScript {
get {
object o = ViewState["EnableClientScript"];
return((o == null) ? true : (bool)o);
}
set {
ViewState["EnableClientScript"] = value;
}
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the validation
/// summary from validators should be shown. Default value is true.</para>
/// </devdoc>
[
WebCategory("Behavior"),
Themeable(false),
DefaultValue(true),
WebSysDescription(SR.ValidationSummary_ShowValidationErrors)
]
public bool ShowValidationErrors {
get {
object o = ViewState["ShowValidationErrors"];
return ((o == null) ? true : (bool)o);
}
set {
ViewState["ShowValidationErrors"] = value;
}
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the model state
/// errors from a data operation should be shown. Default value is true.</para>
/// </devdoc>
[
WebCategory("Behavior"),
Themeable(false),
DefaultValue(true),
WebSysDescription(SR.ValidationSummary_ShowModelStateErrors)
]
public bool ShowModelStateErrors {
get {
object o = ViewState["ShowModelStateErrors"];
return ((o == null) ? true : (bool)o);
}
set {
ViewState["ShowModelStateErrors"] = value;
}
}
/// <devdoc>
/// <para>Gets or sets the foreground color
/// (typically the color of the text) of the control.</para>
/// </devdoc>
[
DefaultValue(typeof(Color), "Red")
]
public override Color ForeColor {
get {
return base.ForeColor;
}
set {
wasForeColorSet = true;
base.ForeColor = value;
}
}
/// <devdoc>
/// <para>Gets or sets the header text to be displayed at the top
/// of the summary.</para>
/// </devdoc>
[
Localizable(true),
WebCategory("Appearance"),
DefaultValue(""),
WebSysDescription(SR.ValidationSummary_HeaderText)
]
public string HeaderText {
get {
object o = ViewState["HeaderText"];
return((o == null) ? String.Empty : (string)o);
}
set {
ViewState["HeaderText"] = value;
}
}
public override bool SupportsDisabledAttribute {
get {
return RenderingCompatibility < VersionUtil.Framework40;
}
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the validation
/// summary is to be displayed in a pop-up message box.</para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(false),
WebSysDescription(SR.ValidationSummary_ShowMessageBox)
]
public bool ShowMessageBox {
get {
object o = ViewState["ShowMessageBox"];
return((o == null) ? false : (bool)o);
}
set {
ViewState["ShowMessageBox"] = value;
}
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the validation
/// summary is to be displayed inline.</para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(true),
WebSysDescription(SR.ValidationSummary_ShowSummary)
]
public bool ShowSummary {
get {
object o = ViewState["ShowSummary"];
return((o == null) ? true : (bool)o);
}
set {
ViewState["ShowSummary"] = value;
}
}
[
WebCategory("Behavior"),
Themeable(false),
DefaultValue(""),
WebSysDescription(SR.ValidationSummary_ValidationGroup)
]
public virtual string ValidationGroup {
get {
string s = (string)ViewState["ValidationGroup"];
return((s == null) ? string.Empty : s);
}
set {
ViewState["ValidationGroup"] = value;
}
}
/// <internalonly/>
/// <devdoc>
/// AddAttributesToRender method.
/// </devdoc>
protected override void AddAttributesToRender(HtmlTextWriter writer) {
if (renderUplevel) {
// We always want validation cotnrols to have an id on the client
EnsureID();
string id = ClientID;
// DevDiv 33149: A backward compat. switch for Everett rendering
HtmlTextWriter expandoAttributeWriter = (EnableLegacyRendering || IsUnobtrusive) ? writer : null;
if (IsUnobtrusive) {
Attributes["data-valsummary"] = "true";
}
if (HeaderText.Length > 0 ) {
BaseValidator.AddExpandoAttribute(this, expandoAttributeWriter, id, "headertext", HeaderText, true);
}
if (ShowMessageBox) {
BaseValidator.AddExpandoAttribute(this, expandoAttributeWriter, id, "showmessagebox", "True", false);
}
if (!ShowSummary) {
BaseValidator.AddExpandoAttribute(this, expandoAttributeWriter, id, "showsummary", "False", false);
}
if (DisplayMode != ValidationSummaryDisplayMode.BulletList) {
BaseValidator.AddExpandoAttribute(this, expandoAttributeWriter, id, "displaymode", PropertyConverter.EnumToString(typeof(ValidationSummaryDisplayMode), DisplayMode), false);
}
if (ValidationGroup.Length > 0) {
BaseValidator.AddExpandoAttribute(this, expandoAttributeWriter, id, "validationGroup", ValidationGroup, true);
}
}
base.AddAttributesToRender(writer);
}
internal String[] GetErrorMessages(out bool inError) {
// Fetch errors from the Page
List<string> errorDescriptions = new List<string>();
inError = false;
if (ShowValidationErrors) {
// see if we are in error and how many messages there are
ValidatorCollection validators = Page.GetValidators(ValidationGroup);
for (int i = 0; i < validators.Count; i++) {
IValidator val = validators[i];
if (!val.IsValid) {
inError = true;
if (!String.IsNullOrEmpty(val.ErrorMessage)) {
errorDescriptions.Add(String.Copy(val.ErrorMessage));
}
else {
Debug.Assert(true, "Not all messages were found!");
}
}
}
}
if (ShowModelStateErrors) {
ModelStateDictionary modelState = Page.ModelState;
if (!modelState.IsValid) {
inError = true;
foreach (KeyValuePair<string, ModelState> pair in modelState) {
foreach (ModelError error in pair.Value.Errors) {
if (!String.IsNullOrEmpty(error.ErrorMessage)) {
errorDescriptions.Add(error.ErrorMessage);
}
}
}
}
}
return errorDescriptions.ToArray();
}
/// <internalonly/>
/// <devdoc>
/// <para> Dynamically setting the Default ForeColor</para>
/// </devdoc>
protected internal override void OnInit(EventArgs e) {
base.OnInit(e);
if (!wasForeColorSet && (RenderingCompatibility < VersionUtil.Framework40)) {
// If the ForeColor wasn't already set, try to set our dynamic default value
ForeColor = Color.Red;
}
}
/// <internalonly/>
/// <devdoc>
/// PreRender method.
/// </devdoc>
protected internal override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
// Act like invisible if disabled
if (!Enabled) {
return;
}
// work out uplevelness now
Page page = Page;
if (page != null && page.RequestInternal != null) {
renderUplevel = (EnableClientScript && ShowValidationErrors
&& page.Request.Browser.W3CDomVersion.Major >= 1
&& page.Request.Browser.EcmaScriptVersion.CompareTo(new Version(1, 2)) >= 0);
}
if (renderUplevel && !IsUnobtrusive) {
const string arrayName = "Page_ValidationSummaries";
string element = "document.getElementById(\"" + ClientID + "\")";
// Cannot use the overloads of Register* that take a Control, since these methods only work with AJAX 3.5,
// and we need to support Validators in AJAX 1.0 (Windows OS Bugs 2015831).
if (!Page.IsPartialRenderingSupported) {
Page.ClientScript.RegisterArrayDeclaration(arrayName, element);
}
else {
ValidatorCompatibilityHelper.RegisterArrayDeclaration(this, arrayName, element);
// Register a dispose script to make sure we clean up the page if we get destroyed
// during an async postback.
// We should technically use the ScriptManager.RegisterDispose() method here, but the original implementation
// of Validators in AJAX 1.0 manually attached a dispose expando. We added this code back in the product
// late in the Orcas cycle, and we didn't want to take the risk of using RegisterDispose() instead.
// (Windows OS Bugs 2015831)
ValidatorCompatibilityHelper.RegisterStartupScript(this, typeof(ValidationSummary), ClientID + "_DisposeScript",
String.Format(
CultureInfo.InvariantCulture,
@"
(function(id) {{
var e = document.getElementById(id);
if (e) {{
e.dispose = function() {{
Array.remove({1}, document.getElementById(id));
}}
e = null;
}}
}})('{0}');
",
ClientID, arrayName), true);
}
}
}
/// <internalonly/>
/// <devdoc>
/// Render method.
/// </devdoc>
protected internal override void Render(HtmlTextWriter writer) {
string [] errorDescriptions;
bool displayContents;
if (DesignMode) {
// Dummy Error state
errorDescriptions = new string [] {
SR.GetString(SR.ValSummary_error_message_1),
SR.GetString(SR.ValSummary_error_message_2),
};
displayContents = true;
renderUplevel = false;
}
else {
// Act like invisible if disabled
if (!Enabled) {
return;
}
bool inError;
errorDescriptions = GetErrorMessages(out inError);
displayContents = (ShowSummary && inError);
// Make sure tags are hidden if there are no contents
if (!displayContents && renderUplevel) {
Style["display"] = "none";
}
}
// Make sure we are in a form tag with runat=server.
if (Page != null) {
Page.VerifyRenderingInServerForm(this);
}
bool displayTags = renderUplevel ? true : displayContents;
if (displayTags) {
RenderBeginTag(writer);
}
if (displayContents) {
string headerSep;
string first;
string pre;
string post;
string final;
switch (DisplayMode) {
case ValidationSummaryDisplayMode.List:
headerSep = breakTag;
first = String.Empty;
pre = String.Empty;
post = breakTag;
final = String.Empty;
break;
case ValidationSummaryDisplayMode.BulletList:
headerSep = String.Empty;
first = "<ul>";
pre = "<li>";
post = "</li>";
final = "</ul>";
break;
case ValidationSummaryDisplayMode.SingleParagraph:
headerSep = " ";
first = String.Empty;
pre = String.Empty;
post = " ";
final = breakTag;
break;
default:
Debug.Fail("Invalid DisplayMode!");
goto
case ValidationSummaryDisplayMode.BulletList;
}
if (HeaderText.Length > 0) {
writer.Write(HeaderText);
WriteBreakIfPresent(writer, headerSep);
}
if (errorDescriptions != null) {
writer.Write(first);
for (int i = 0; i < errorDescriptions.Length; i++) {
Debug.Assert(errorDescriptions[i] != null && errorDescriptions[i].Length > 0, "Bad Error Messages");
writer.Write(pre);
writer.Write(errorDescriptions[i]);
WriteBreakIfPresent(writer, post);
}
WriteBreakIfPresent(writer, final);
}
}
if (displayTags) {
RenderEndTag(writer);
}
}
internal bool ShouldSerializeForeColor() {
Color defaultForeColor = (RenderingCompatibility < VersionUtil.Framework40) ? Color.Red : Color.Empty;
return defaultForeColor != ForeColor;
}
private void WriteBreakIfPresent(HtmlTextWriter writer, String text) {
if (text == breakTag) {
if (EnableLegacyRendering) {
writer.WriteObsoleteBreak();
}
else {
writer.WriteBreak();
}
}
else {
writer.Write(text);
}
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace System
{
/// <summary>Provides access to and processing of a terminfo database.</summary>
internal static class TermInfo
{
internal enum WellKnownNumbers
{
Columns = 0,
Lines = 2,
MaxColors = 13,
}
internal enum WellKnownStrings
{
Bell = 1,
Clear = 5,
ClrEol = 6,
CursorAddress = 10,
CursorLeft = 14,
CursorPositionReport = 294,
OrigPairs = 297,
OrigColors = 298,
SetAnsiForeground = 359,
SetAnsiBackground = 360,
CursorInvisible = 13,
CursorVisible = 16,
FromStatusLine = 47,
ToStatusLine = 135,
KeyBackspace = 55,
KeyClear = 57,
KeyDelete = 59,
KeyDown = 61,
KeyF1 = 66,
KeyF10 = 67,
KeyF2 = 68,
KeyF3 = 69,
KeyF4 = 70,
KeyF5 = 71,
KeyF6 = 72,
KeyF7 = 73,
KeyF8 = 74,
KeyF9 = 75,
KeyHome = 76,
KeyInsert = 77,
KeyLeft = 79,
KeyPageDown = 81,
KeyPageUp = 82,
KeyRight = 83,
KeyScrollForward = 84,
KeyScrollReverse = 85,
KeyUp = 87,
KeypadXmit = 89,
KeyBackTab = 148,
KeyBegin = 158,
KeyEnd = 164,
KeyEnter = 165,
KeyHelp = 168,
KeyPrint = 176,
KeySBegin = 186,
KeySDelete = 191,
KeySelect = 193,
KeySHelp = 198,
KeySHome = 199,
KeySLeft = 201,
KeySPrint = 207,
KeySRight = 210,
KeyF11 = 216,
KeyF12 = 217,
KeyF13 = 218,
KeyF14 = 219,
KeyF15 = 220,
KeyF16 = 221,
KeyF17 = 222,
KeyF18 = 223,
KeyF19 = 224,
KeyF20 = 225,
KeyF21 = 226,
KeyF22 = 227,
KeyF23 = 228,
KeyF24 = 229,
}
/// <summary>Provides a terminfo database.</summary>
internal sealed class Database
{
/// <summary>The name of the terminfo file.</summary>
private readonly string _term;
/// <summary>Raw data of the database instance.</summary>
private readonly byte[] _data;
/// <summary>The number of bytes in the names section of the database.</summary>
private readonly int _nameSectionNumBytes;
/// <summary>The number of bytes in the Booleans section of the database.</summary>
private readonly int _boolSectionNumBytes;
/// <summary>The number of integers in the numbers section of the database.</summary>
private readonly int _numberSectionNumInts;
/// <summary>The number of offsets in the strings section of the database.</summary>
private readonly int _stringSectionNumOffsets;
/// <summary>The number of bytes in the strings table of the database.</summary>
private readonly int _stringTableNumBytes;
/// <summary>Whether or not to read the number section as 32-bit integers.</summary>
private readonly bool _readAs32Bit;
/// <summary>The size of the integers on the number section.</summary>
private readonly int _sizeOfInt;
/// <summary>Extended / user-defined entries in the terminfo database.</summary>
private readonly Dictionary<string, string> _extendedStrings;
/// <summary>Initializes the database instance.</summary>
/// <param name="term">The name of the terminal.</param>
/// <param name="data">The data from the terminfo file.</param>
private Database(string term, byte[] data)
{
_term = term;
_data = data;
const int MagicLegacyNumber = 0x11A; // magic number octal 0432 for legacy ncurses terminfo
const int Magic32BitNumber = 0x21E; // magic number octal 01036 for new ncruses terminfo
short magic = ReadInt16(data, 0);
_readAs32Bit =
magic == MagicLegacyNumber ? false :
magic == Magic32BitNumber ? true :
throw new InvalidOperationException(SR.Format(SR.IO_TermInfoInvalidMagicNumber, string.Concat("O" + Convert.ToString(magic, 8)))); // magic number was not recognized. Printing the magic number in octal.
_sizeOfInt = (_readAs32Bit) ? 4 : 2;
_nameSectionNumBytes = ReadInt16(data, 2);
_boolSectionNumBytes = ReadInt16(data, 4);
_numberSectionNumInts = ReadInt16(data, 6);
_stringSectionNumOffsets = ReadInt16(data, 8);
_stringTableNumBytes = ReadInt16(data, 10);
if (_nameSectionNumBytes < 0 ||
_boolSectionNumBytes < 0 ||
_numberSectionNumInts < 0 ||
_stringSectionNumOffsets < 0 ||
_stringTableNumBytes < 0)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
// In addition to the main section of bools, numbers, and strings, there is also
// an "extended" section. This section contains additional entries that don't
// have well-known indices, and are instead named mappings. As such, we parse
// all of this data now rather than on each request, as the mapping is fairly complicated.
// This function relies on the data stored above, so it's the last thing we run.
// (Note that the extended section also includes other Booleans and numbers, but we don't
// have any need for those now, so we don't parse them.)
int extendedBeginning = RoundUpToEven(StringsTableOffset + _stringTableNumBytes);
_extendedStrings = ParseExtendedStrings(data, extendedBeginning, _readAs32Bit) ?? new Dictionary<string, string>();
}
/// <summary>The name of the associated terminfo, if any.</summary>
public string Term { get { return _term; } }
/// <summary>Read the database for the current terminal as specified by the "TERM" environment variable.</summary>
/// <returns>The database, or null if it could not be found.</returns>
internal static Database? ReadActiveDatabase()
{
string? term = Environment.GetEnvironmentVariable("TERM");
return !string.IsNullOrEmpty(term) ? ReadDatabase(term) : null;
}
/// <summary>
/// The default locations in which to search for terminfo databases.
/// This is the ordering of well-known locations used by ncurses.
/// </summary>
private static readonly string[] _terminfoLocations = new string[] {
"/etc/terminfo",
"/lib/terminfo",
"/usr/share/terminfo",
"/usr/share/misc/terminfo"
};
/// <summary>Read the database for the specified terminal.</summary>
/// <param name="term">The identifier for the terminal.</param>
/// <returns>The database, or null if it could not be found.</returns>
private static Database? ReadDatabase(string term)
{
// This follows the same search order as prescribed by ncurses.
Database? db;
// First try a location specified in the TERMINFO environment variable.
string? terminfo = Environment.GetEnvironmentVariable("TERMINFO");
if (!string.IsNullOrWhiteSpace(terminfo) && (db = ReadDatabase(term, terminfo)) != null)
{
return db;
}
// Then try in the user's home directory.
string? home = PersistedFiles.GetHomeDirectory();
if (!string.IsNullOrWhiteSpace(home) && (db = ReadDatabase(term, home + "/.terminfo")) != null)
{
return db;
}
// Then try a set of well-known locations.
foreach (string terminfoLocation in _terminfoLocations)
{
if ((db = ReadDatabase(term, terminfoLocation)) != null)
{
return db;
}
}
// Couldn't find one
return null;
}
/// <summary>Attempt to open as readonly the specified file path.</summary>
/// <param name="filePath">The path to the file to open.</param>
/// <param name="fd">If successful, the opened file descriptor; otherwise, -1.</param>
/// <returns>true if the file was successfully opened; otherwise, false.</returns>
private static bool TryOpen(string filePath, [NotNullWhen(true)] out SafeFileHandle? fd)
{
fd = Interop.Sys.Open(filePath, Interop.Sys.OpenFlags.O_RDONLY | Interop.Sys.OpenFlags.O_CLOEXEC, 0);
if (fd.IsInvalid)
{
// Don't throw in this case, as we'll be polling multiple locations looking for the file.
fd = null;
return false;
}
return true;
}
/// <summary>Read the database for the specified terminal from the specified directory.</summary>
/// <param name="term">The identifier for the terminal.</param>
/// <param name="directoryPath">The path to the directory containing terminfo database files.</param>
/// <returns>The database, or null if it could not be found.</returns>
private static Database? ReadDatabase(string? term, string? directoryPath)
{
if (string.IsNullOrEmpty(term) || string.IsNullOrEmpty(directoryPath))
{
return null;
}
SafeFileHandle? fd;
if (!TryOpen(directoryPath + "/" + term[0].ToString() + "/" + term, out fd) && // /directory/termFirstLetter/term (Linux)
!TryOpen(directoryPath + "/" + ((int)term[0]).ToString("X") + "/" + term, out fd)) // /directory/termFirstLetterAsHex/term (Mac)
{
return null;
}
using (fd)
{
// Read in all of the terminfo data
long termInfoLength = Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_END)); // jump to the end to get the file length
Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_SET)); // reset back to beginning
const int MaxTermInfoLength = 4096; // according to the term and tic man pages, 4096 is the terminfo file size max
const int HeaderLength = 12;
if (termInfoLength <= HeaderLength || termInfoLength > MaxTermInfoLength)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
int fileLen = (int)termInfoLength;
byte[] data = new byte[fileLen];
if (ConsolePal.Read(fd, data, 0, fileLen) != fileLen)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
// Create the database from the data
return new Database(term, data);
}
}
/// <summary>The offset into data where the names section begins.</summary>
private const int NamesOffset = 12; // comes right after the header, which is always 12 bytes
/// <summary>The offset into data where the Booleans section begins.</summary>
private int BooleansOffset { get { return NamesOffset + _nameSectionNumBytes; } } // after the names section
/// <summary>The offset into data where the numbers section begins.</summary>
private int NumbersOffset { get { return RoundUpToEven(BooleansOffset + _boolSectionNumBytes); } } // after the Booleans section, at an even position
/// <summary>
/// The offset into data where the string offsets section begins. We index into this section
/// to find the location within the strings table where a string value exists.
/// </summary>
private int StringOffsetsOffset { get { return NumbersOffset + (_numberSectionNumInts * _sizeOfInt); } }
/// <summary>The offset into data where the string table exists.</summary>
private int StringsTableOffset { get { return StringOffsetsOffset + (_stringSectionNumOffsets * 2); } }
/// <summary>Gets a string from the strings section by the string's well-known index.</summary>
/// <param name="stringTableIndex">The index of the string to find.</param>
/// <returns>The string if it's in the database; otherwise, null.</returns>
public string? GetString(WellKnownStrings stringTableIndex)
{
int index = (int)stringTableIndex;
Debug.Assert(index >= 0);
if (index >= _stringSectionNumOffsets)
{
// Some terminfo files may not contain enough entries to actually
// have the requested one.
return null;
}
int tableIndex = ReadInt16(_data, StringOffsetsOffset + (index * 2));
if (tableIndex == -1)
{
// Some terminfo files may have enough entries, but may not actually
// have it filled in for this particular string.
return null;
}
return ReadString(_data, StringsTableOffset + tableIndex);
}
/// <summary>Gets a string from the extended strings section.</summary>
/// <param name="name">The name of the string as contained in the extended names section.</param>
/// <returns>The string if it's in the database; otherwise, null.</returns>
public string? GetExtendedString(string name)
{
Debug.Assert(name != null);
string? value;
return _extendedStrings.TryGetValue(name, out value) ?
value :
null;
}
/// <summary>Gets a number from the numbers section by the number's well-known index.</summary>
/// <param name="numberIndex">The index of the string to find.</param>
/// <returns>The number if it's in the database; otherwise, -1.</returns>
public int GetNumber(WellKnownNumbers numberIndex)
{
int index = (int)numberIndex;
Debug.Assert(index >= 0);
if (index >= _numberSectionNumInts)
{
// Some terminfo files may not contain enough entries to actually
// have the requested one.
return -1;
}
return ReadInt(_data, NumbersOffset + (index * _sizeOfInt), _readAs32Bit);
}
/// <summary>Parses the extended string information from the terminfo data.</summary>
/// <returns>
/// A dictionary of the name to value mapping. As this section of the terminfo isn't as well
/// defined as the earlier portions, and may not even exist, the parsing is more lenient about
/// errors, returning an empty collection rather than throwing.
/// </returns>
private static Dictionary<string, string>? ParseExtendedStrings(byte[] data, int extendedBeginning, bool readAs32Bit)
{
const int ExtendedHeaderSize = 10;
int sizeOfIntValuesInBytes = (readAs32Bit) ? 4 : 2;
if (extendedBeginning + ExtendedHeaderSize >= data.Length)
{
// Exit out as there's no extended information.
return null;
}
// Read in extended counts, and exit out if we got any incorrect info
int extendedBoolCount = ReadInt16(data, extendedBeginning);
int extendedNumberCount = ReadInt16(data, extendedBeginning + (2 * 1));
int extendedStringCount = ReadInt16(data, extendedBeginning + (2 * 2));
int extendedStringNumOffsets = ReadInt16(data, extendedBeginning + (2 * 3));
int extendedStringTableByteSize = ReadInt16(data, extendedBeginning + (2 * 4));
if (extendedBoolCount < 0 ||
extendedNumberCount < 0 ||
extendedStringCount < 0 ||
extendedStringNumOffsets < 0 ||
extendedStringTableByteSize < 0)
{
// The extended header contained invalid data. Bail.
return null;
}
// Skip over the extended bools. We don't need them now and can add this in later
// if needed. Also skip over extended numbers, for the same reason.
// Get the location where the extended string offsets begin. These point into
// the extended string table.
int extendedOffsetsStart =
extendedBeginning + // go past the normal data
ExtendedHeaderSize + // and past the extended header
RoundUpToEven(extendedBoolCount) + // and past all of the extended Booleans
(extendedNumberCount * sizeOfIntValuesInBytes); // and past all of the extended numbers
// Get the location where the extended string table begins. This area contains
// null-terminated strings.
int extendedStringTableStart =
extendedOffsetsStart +
(extendedStringCount * 2) + // and past all of the string offsets
((extendedBoolCount + extendedNumberCount + extendedStringCount) * 2); // and past all of the name offsets
// Get the location where the extended string table ends. We shouldn't read past this.
int extendedStringTableEnd =
extendedStringTableStart +
extendedStringTableByteSize;
if (extendedStringTableEnd > data.Length)
{
// We don't have enough data to parse everything. Bail.
return null;
}
// Now we need to parse all of the extended string values. These aren't necessarily
// "in order", meaning the offsets aren't guaranteed to be increasing. Instead, we parse
// the offsets in order, pulling out each string it references and storing them into our
// results list in the order of the offsets.
var values = new List<string>(extendedStringCount);
int lastEnd = 0;
for (int i = 0; i < extendedStringCount; i++)
{
int offset = extendedStringTableStart + ReadInt16(data, extendedOffsetsStart + (i * 2));
if (offset < 0 || offset >= data.Length)
{
// If the offset is invalid, bail.
return null;
}
// Add the string
int end = FindNullTerminator(data, offset);
values.Add(Encoding.ASCII.GetString(data, offset, end - offset));
// Keep track of where the last string ends. The name strings will come after that.
lastEnd = Math.Max(end, lastEnd);
}
// Now parse all of the names.
var names = new List<string>(extendedBoolCount + extendedNumberCount + extendedStringCount);
for (int pos = lastEnd + 1; pos < extendedStringTableEnd; pos++)
{
int end = FindNullTerminator(data, pos);
names.Add(Encoding.ASCII.GetString(data, pos, end - pos));
pos = end;
}
// The names are in order for the Booleans, then the numbers, and then the strings.
// Skip over the bools and numbers, and associate the names with the values.
var extendedStrings = new Dictionary<string, string>(extendedStringCount);
for (int iName = extendedBoolCount + extendedNumberCount, iValue = 0;
iName < names.Count && iValue < values.Count;
iName++, iValue++)
{
extendedStrings.Add(names[iName], values[iValue]);
}
return extendedStrings;
}
private static int RoundUpToEven(int i) { return i % 2 == 1 ? i + 1 : i; }
/// <summary>Read a 16-bit or 32-bit value from the buffer starting at the specified position.</summary>
/// <param name="buffer">The buffer from which to read.</param>
/// <param name="pos">The position at which to read.</param>
/// <param name="readAs32Bit">Whether or not to read value as 32-bit. Will read as 16-bit if set to false.</param>
/// <returns>The value read.</returns>
private static int ReadInt(byte[] buffer, int pos, bool readAs32Bit) =>
readAs32Bit ? ReadInt32(buffer, pos) : ReadInt16(buffer, pos);
/// <summary>Read a 16-bit value from the buffer starting at the specified position.</summary>
/// <param name="buffer">The buffer from which to read.</param>
/// <param name="pos">The position at which to read.</param>
/// <returns>The 16-bit value read.</returns>
private static short ReadInt16(byte[] buffer, int pos)
{
return unchecked((short)
((((int)buffer[pos + 1]) << 8) |
((int)buffer[pos] & 0xff)));
}
/// <summary>Read a 32-bit value from the buffer starting at the specified position.</summary>
/// <param name="buffer">The buffer from which to read.</param>
/// <param name="pos">The position at which to read.</param>
/// <returns>The 32-bit value read.</returns>
private static int ReadInt32(byte[] buffer, int pos)
{
return (int)((buffer[pos] & 0xff) |
buffer[pos + 1] << 8 |
buffer[pos + 2] << 16 |
buffer[pos + 3] << 24);
}
/// <summary>Reads a string from the buffer starting at the specified position.</summary>
/// <param name="buffer">The buffer from which to read.</param>
/// <param name="pos">The position at which to read.</param>
/// <returns>The string read from the specified position.</returns>
private static string ReadString(byte[] buffer, int pos)
{
int end = FindNullTerminator(buffer, pos);
return Encoding.ASCII.GetString(buffer, pos, end - pos);
}
/// <summary>Finds the null-terminator for a string that begins at the specified position.</summary>
private static int FindNullTerminator(byte[] buffer, int pos)
{
int termPos = pos;
while (termPos < buffer.Length && buffer[termPos] != '\0') termPos++;
return termPos;
}
}
/// <summary>Provides support for evaluating parameterized terminfo database format strings.</summary>
internal static class ParameterizedStrings
{
/// <summary>A cached stack to use to avoid allocating a new stack object for every evaluation.</summary>
[ThreadStatic]
private static Stack<FormatParam>? t_cachedStack;
/// <summary>A cached array of arguments to use to avoid allocating a new array object for every evaluation.</summary>
[ThreadStatic]
private static FormatParam[]? t_cachedOneElementArgsArray;
/// <summary>A cached array of arguments to use to avoid allocating a new array object for every evaluation.</summary>
[ThreadStatic]
private static FormatParam[]? t_cachedTwoElementArgsArray;
/// <summary>Evaluates a terminfo formatting string, using the supplied argument.</summary>
/// <param name="format">The format string.</param>
/// <param name="arg">The argument to the format string.</param>
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, FormatParam arg)
{
FormatParam[]? args = t_cachedOneElementArgsArray;
if (args == null)
{
t_cachedOneElementArgsArray = args = new FormatParam[1];
}
args[0] = arg;
return Evaluate(format, args);
}
/// <summary>Evaluates a terminfo formatting string, using the supplied arguments.</summary>
/// <param name="format">The format string.</param>
/// <param name="arg1">The first argument to the format string.</param>
/// <param name="arg2">The second argument to the format string.</param>
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, FormatParam arg1, FormatParam arg2)
{
FormatParam[]? args = t_cachedTwoElementArgsArray;
if (args == null)
{
t_cachedTwoElementArgsArray = args = new FormatParam[2];
}
args[0] = arg1;
args[1] = arg2;
return Evaluate(format, args);
}
/// <summary>Evaluates a terminfo formatting string, using the supplied arguments.</summary>
/// <param name="format">The format string.</param>
/// <param name="args">The arguments to the format string.</param>
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, params FormatParam[] args)
{
if (format == null)
{
throw new ArgumentNullException(nameof(format));
}
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
// Initialize the stack to use for processing.
Stack<FormatParam>? stack = t_cachedStack;
if (stack == null)
{
t_cachedStack = stack = new Stack<FormatParam>();
}
else
{
stack.Clear();
}
// "dynamic" and "static" variables are much less often used (the "dynamic" and "static"
// terminology appears to just refer to two different collections rather than to any semantic
// meaning). As such, we'll only initialize them if we really need them.
FormatParam[]? dynamicVars = null, staticVars = null;
int pos = 0;
return EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars);
// EvaluateInternal may throw IndexOutOfRangeException and InvalidOperationException
// if the format string is malformed or if it's inconsistent with the parameters provided.
}
/// <summary>Evaluates a terminfo formatting string, using the supplied arguments and processing data structures.</summary>
/// <param name="format">The format string.</param>
/// <param name="pos">The position in <paramref name="format"/> to start processing.</param>
/// <param name="args">The arguments to the format string.</param>
/// <param name="stack">The stack to use as the format string is evaluated.</param>
/// <param name="dynamicVars">A lazily-initialized collection of variables.</param>
/// <param name="staticVars">A lazily-initialized collection of variables.</param>
/// <returns>
/// The formatted string; this may be empty if the evaluation didn't yield any output.
/// The evaluation stack will have a 1 at the top if all processing was completed at invoked level
/// of recursion, and a 0 at the top if we're still inside of a conditional that requires more processing.
/// </returns>
private static string EvaluateInternal(
string format, ref int pos, FormatParam[] args, Stack<FormatParam> stack,
ref FormatParam[]? dynamicVars, ref FormatParam[]? staticVars)
{
// Create a StringBuilder to store the output of this processing. We use the format's length as an
// approximation of an upper-bound for how large the output will be, though with parameter processing,
// this is just an estimate, sometimes way over, sometimes under.
StringBuilder output = StringBuilderCache.Acquire(format.Length);
// Format strings support conditionals, including the equivalent of "if ... then ..." and
// "if ... then ... else ...", as well as "if ... then ... else ... then ..."
// and so on, where an else clause can not only be evaluated for string output but also
// as a conditional used to determine whether to evaluate a subsequent then clause.
// We use recursion to process these subsequent parts, and we track whether we're processing
// at the same level of the initial if clause (or whether we're nested).
bool sawIfConditional = false;
// Process each character in the format string, starting from the position passed in.
for (; pos < format.Length; pos++)
{
// '%' is the escape character for a special sequence to be evaluated.
// Anything else just gets pushed to output.
if (format[pos] != '%')
{
output.Append(format[pos]);
continue;
}
// We have a special parameter sequence to process. Now we need
// to look at what comes after the '%'.
++pos;
switch (format[pos])
{
// Output appending operations
case '%': // Output the escaped '%'
output.Append('%');
break;
case 'c': // Pop the stack and output it as a char
output.Append((char)stack.Pop().Int32);
break;
case 's': // Pop the stack and output it as a string
output.Append(stack.Pop().String);
break;
case 'd': // Pop the stack and output it as an integer
output.Append(stack.Pop().Int32);
break;
case 'o':
case 'X':
case 'x':
case ':':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// printf strings of the format "%[[:]flags][width[.precision]][doxXs]" are allowed
// (with a ':' used in front of flags to help differentiate from binary operations, as flags can
// include '-' and '+'). While above we've special-cased common usage (e.g. %d, %s),
// for more complicated expressions we delegate to printf.
int printfEnd = pos;
for (; printfEnd < format.Length; printfEnd++) // find the end of the printf format string
{
char ec = format[printfEnd];
if (ec == 'd' || ec == 'o' || ec == 'x' || ec == 'X' || ec == 's')
{
break;
}
}
if (printfEnd >= format.Length)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
string printfFormat = format.Substring(pos - 1, printfEnd - pos + 2); // extract the format string
if (printfFormat.Length > 1 && printfFormat[1] == ':')
{
printfFormat = printfFormat.Remove(1, 1);
}
output.Append(FormatPrintF(printfFormat, stack.Pop().Object)); // do the printf formatting and append its output
break;
// Stack pushing operations
case 'p': // Push the specified parameter (1-based) onto the stack
pos++;
Debug.Assert(format[pos] >= '0' && format[pos] <= '9');
stack.Push(args[format[pos] - '1']);
break;
case 'l': // Pop a string and push its length
stack.Push(stack.Pop().String.Length);
break;
case '{': // Push integer literal, enclosed between braces
pos++;
int intLit = 0;
while (format[pos] != '}')
{
Debug.Assert(format[pos] >= '0' && format[pos] <= '9');
intLit = (intLit * 10) + (format[pos] - '0');
pos++;
}
stack.Push(intLit);
break;
case '\'': // Push literal character, enclosed between single quotes
stack.Push((int)format[pos + 1]);
Debug.Assert(format[pos + 2] == '\'');
pos += 2;
break;
// Storing and retrieving "static" and "dynamic" variables
case 'P': // Pop a value and store it into either static or dynamic variables based on whether the a-z variable is capitalized
pos++;
int setIndex;
FormatParam[] targetVars = GetDynamicOrStaticVariables(format[pos], ref dynamicVars, ref staticVars, out setIndex);
targetVars[setIndex] = stack.Pop();
break;
case 'g': // Push a static or dynamic variable; which is based on whether the a-z variable is capitalized
pos++;
int getIndex;
FormatParam[] sourceVars = GetDynamicOrStaticVariables(format[pos], ref dynamicVars, ref staticVars, out getIndex);
stack.Push(sourceVars[getIndex]);
break;
// Binary operations
case '+':
case '-':
case '*':
case '/':
case 'm':
case '^': // arithmetic
case '&':
case '|': // bitwise
case '=':
case '>':
case '<': // comparison
case 'A':
case 'O': // logical
int second = stack.Pop().Int32; // it's a stack... the second value was pushed last
int first = stack.Pop().Int32;
char c = format[pos];
stack.Push(
c == '+' ? (first + second) :
c == '-' ? (first - second) :
c == '*' ? (first * second) :
c == '/' ? (first / second) :
c == 'm' ? (first % second) :
c == '^' ? (first ^ second) :
c == '&' ? (first & second) :
c == '|' ? (first | second) :
c == '=' ? AsInt(first == second) :
c == '>' ? AsInt(first > second) :
c == '<' ? AsInt(first < second) :
c == 'A' ? AsInt(AsBool(first) && AsBool(second)) :
c == 'O' ? AsInt(AsBool(first) || AsBool(second)) :
0); // not possible; we just validated above
break;
// Unary operations
case '!':
case '~':
int value = stack.Pop().Int32;
stack.Push(
format[pos] == '!' ? AsInt(!AsBool(value)) :
~value);
break;
// Some terminfo files appear to have a fairly liberal interpretation of %i. The spec states that %i increments the first two arguments,
// but some uses occur when there's only a single argument. To make sure we accommodate these files, we increment the values
// of up to (but not requiring) two arguments.
case 'i':
if (args.Length > 0)
{
args[0] = 1 + args[0].Int32;
if (args.Length > 1)
args[1] = 1 + args[1].Int32;
}
break;
// Conditional of the form %? if-part %t then-part %e else-part %;
// The "%e else-part" is optional.
case '?':
sawIfConditional = true;
break;
case 't':
// We hit the end of the if-part and are about to start the then-part.
// The if-part left its result on the stack; pop and evaluate.
bool conditionalResult = AsBool(stack.Pop().Int32);
// Regardless of whether it's true, run the then-part to get past it.
// If the conditional was true, output the then results.
pos++;
string thenResult = EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars);
if (conditionalResult)
{
output.Append(thenResult);
}
Debug.Assert(format[pos] == 'e' || format[pos] == ';');
// We're past the then; the top of the stack should now be a Boolean
// indicating whether this conditional has more to be processed (an else clause).
if (!AsBool(stack.Pop().Int32))
{
// Process the else clause, and if the conditional was false, output the else results.
pos++;
string elseResult = EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars);
if (!conditionalResult)
{
output.Append(elseResult);
}
// Now we should be done (any subsequent elseif logic will have been handled in the recursive call).
if (!AsBool(stack.Pop().Int32))
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
}
// If we're in a nested processing, return to our parent.
if (!sawIfConditional)
{
stack.Push(1);
return StringBuilderCache.GetStringAndRelease(output);
}
// Otherwise, we're done processing the conditional in its entirety.
sawIfConditional = false;
break;
case 'e':
case ';':
// Let our caller know why we're exiting, whether due to the end of the conditional or an else branch.
stack.Push(AsInt(format[pos] == ';'));
return StringBuilderCache.GetStringAndRelease(output);
// Anything else is an error
default:
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
}
stack.Push(1);
return StringBuilderCache.GetStringAndRelease(output);
}
/// <summary>Converts an Int32 to a Boolean, with 0 meaning false and all non-zero values meaning true.</summary>
/// <param name="i">The integer value to convert.</param>
/// <returns>true if the integer was non-zero; otherwise, false.</returns>
private static bool AsBool(int i) { return i != 0; }
/// <summary>Converts a Boolean to an Int32, with true meaning 1 and false meaning 0.</summary>
/// <param name="b">The Boolean value to convert.</param>
/// <returns>1 if the Boolean is true; otherwise, 0.</returns>
private static int AsInt(bool b) { return b ? 1 : 0; }
/// <summary>Formats an argument into a printf-style format string.</summary>
/// <param name="format">The printf-style format string.</param>
/// <param name="arg">The argument to format. This must be an Int32 or a String.</param>
/// <returns>The formatted string.</returns>
private static unsafe string FormatPrintF(string format, object arg)
{
Debug.Assert(arg is string || arg is int);
// Determine how much space is needed to store the formatted string.
string? stringArg = arg as string;
int neededLength = stringArg != null ?
Interop.Sys.SNPrintF(null, 0, format, stringArg) :
Interop.Sys.SNPrintF(null, 0, format, (int)arg);
if (neededLength == 0)
{
return string.Empty;
}
if (neededLength < 0)
{
throw new InvalidOperationException(SR.InvalidOperation_PrintF);
}
// Allocate the needed space, format into it, and return the data as a string.
byte[] bytes = new byte[neededLength + 1]; // extra byte for the null terminator
fixed (byte* ptr = &bytes[0])
{
int length = stringArg != null ?
Interop.Sys.SNPrintF(ptr, bytes.Length, format, stringArg) :
Interop.Sys.SNPrintF(ptr, bytes.Length, format, (int)arg);
if (length != neededLength)
{
throw new InvalidOperationException(SR.InvalidOperation_PrintF);
}
}
return Encoding.ASCII.GetString(bytes, 0, neededLength);
}
/// <summary>Gets the lazily-initialized dynamic or static variables collection, based on the supplied variable name.</summary>
/// <param name="c">The name of the variable.</param>
/// <param name="dynamicVars">The lazily-initialized dynamic variables collection.</param>
/// <param name="staticVars">The lazily-initialized static variables collection.</param>
/// <param name="index">The index to use to index into the variables.</param>
/// <returns>The variables collection.</returns>
private static FormatParam[] GetDynamicOrStaticVariables(
char c, ref FormatParam[]? dynamicVars, ref FormatParam[]? staticVars, out int index)
{
if (c >= 'A' && c <= 'Z')
{
index = c - 'A';
return staticVars ?? (staticVars = new FormatParam[26]); // one slot for each letter of alphabet
}
else if (c >= 'a' && c <= 'z')
{
index = c - 'a';
return dynamicVars ?? (dynamicVars = new FormatParam[26]); // one slot for each letter of alphabet
}
else throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
/// <summary>
/// Represents a parameter to a terminfo formatting string.
/// It is a discriminated union of either an integer or a string,
/// with characters represented as integers.
/// </summary>
public readonly struct FormatParam
{
/// <summary>The integer stored in the parameter.</summary>
private readonly int _int32;
/// <summary>The string stored in the parameter.</summary>
private readonly string? _string; // null means an Int32 is stored
/// <summary>Initializes the parameter with an integer value.</summary>
/// <param name="value">The value to be stored in the parameter.</param>
public FormatParam(int value) : this(value, null) { }
/// <summary>Initializes the parameter with a string value.</summary>
/// <param name="value">The value to be stored in the parameter.</param>
public FormatParam(string? value) : this(0, value ?? string.Empty) { }
/// <summary>Initializes the parameter.</summary>
/// <param name="intValue">The integer value.</param>
/// <param name="stringValue">The string value.</param>
private FormatParam(int intValue, string? stringValue)
{
_int32 = intValue;
_string = stringValue;
}
/// <summary>Implicit converts an integer into a parameter.</summary>
public static implicit operator FormatParam(int value)
{
return new FormatParam(value);
}
/// <summary>Implicit converts a string into a parameter.</summary>
public static implicit operator FormatParam(string? value)
{
return new FormatParam(value);
}
/// <summary>Gets the integer value of the parameter. If a string was stored, 0 is returned.</summary>
public int Int32 { get { return _int32; } }
/// <summary>Gets the string value of the parameter. If an Int32 or a null String were stored, an empty string is returned.</summary>
public string String { get { return _string ?? string.Empty; } }
/// <summary>Gets the string or the integer value as an object.</summary>
public object Object { get { return _string ?? (object)_int32; } }
}
}
}
}
| |
namespace WMATC.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Events",
c => new
{
EventId = c.Int(nullable: false, identity: true),
Title = c.String(),
EventDate = c.DateTime(nullable: false),
ListLockDate = c.DateTime(nullable: false),
ImageURL = c.String(),
})
.PrimaryKey(t => t.EventId);
CreateTable(
"dbo.Factions",
c => new
{
FactionId = c.Int(nullable: false, identity: true),
Title = c.String(),
ImageURL = c.String(),
})
.PrimaryKey(t => t.FactionId);
CreateTable(
"dbo.Matchups",
c => new
{
MatchupId = c.Int(nullable: false, identity: true),
RoundTeamMatchupId = c.Int(nullable: false),
Player1Id = c.Int(nullable: false),
Player2Id = c.Int(nullable: false),
WinnerId = c.Int(),
Player1List = c.Int(),
Player2List = c.Int(),
Player1CP = c.Int(),
Player2CP = c.Int(),
Player1APD = c.Int(),
Player2APD = c.Int(),
VictoryCondition = c.String(),
})
.PrimaryKey(t => t.MatchupId)
.ForeignKey("dbo.Players", t => t.Player1Id, cascadeDelete: false)
.ForeignKey("dbo.Players", t => t.Player2Id, cascadeDelete: false)
.ForeignKey("dbo.RoundTeamMatchups", t => t.RoundTeamMatchupId, cascadeDelete: true)
.ForeignKey("dbo.Players", t => t.WinnerId)
.Index(t => t.RoundTeamMatchupId)
.Index(t => t.Player1Id)
.Index(t => t.Player2Id)
.Index(t => t.WinnerId);
CreateTable(
"dbo.Players",
c => new
{
PlayerId = c.Int(nullable: false, identity: true),
Name = c.String(),
FactionId = c.Int(),
Caster1 = c.String(),
List1 = c.String(),
Caster2 = c.String(),
List2 = c.String(),
TeamId = c.Int(nullable: false),
})
.PrimaryKey(t => t.PlayerId)
.ForeignKey("dbo.Factions", t => t.FactionId)
.ForeignKey("dbo.Teams", t => t.TeamId, cascadeDelete: true)
.Index(t => t.FactionId)
.Index(t => t.TeamId);
CreateTable(
"dbo.Teams",
c => new
{
TeamId = c.Int(nullable: false, identity: true),
Name = c.String(),
ImgURL = c.String(),
EventId = c.Int(nullable: false),
PairedDownRound = c.Int(),
ByeRound = c.Int(),
})
.PrimaryKey(t => t.TeamId)
.ForeignKey("dbo.Events", t => t.EventId, cascadeDelete: true)
.Index(t => t.EventId);
CreateTable(
"dbo.RoundTeamMatchups",
c => new
{
RoundTeamMatchupId = c.Int(nullable: false, identity: true),
RoundId = c.Int(nullable: false),
Team1Id = c.Int(nullable: false),
Team2Id = c.Int(nullable: false),
TableZone = c.Int(),
})
.PrimaryKey(t => t.RoundTeamMatchupId)
.ForeignKey("dbo.Rounds", t => t.RoundId, cascadeDelete: true)
.ForeignKey("dbo.Teams", t => t.Team1Id, cascadeDelete: false)
.ForeignKey("dbo.Teams", t => t.Team2Id, cascadeDelete: false)
.Index(t => t.RoundId)
.Index(t => t.Team1Id)
.Index(t => t.Team2Id);
CreateTable(
"dbo.Rounds",
c => new
{
RoundId = c.Int(nullable: false, identity: true),
Sequence = c.Int(nullable: false),
Scenario = c.String(),
EventId = c.Int(nullable: false),
})
.PrimaryKey(t => t.RoundId)
.ForeignKey("dbo.Events", t => t.EventId, cascadeDelete: true)
.Index(t => t.EventId);
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex");
CreateTable(
"dbo.AspNetUserRoles",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
RoleId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true)
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.RoleId);
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
CreateTable(
"dbo.AspNetUserClaims",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128),
ClaimType = c.String(),
ClaimValue = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUserLogins",
c => new
{
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 128),
UserId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
}
public override void Down()
{
DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles");
DropForeignKey("dbo.Matchups", "WinnerId", "dbo.Players");
DropForeignKey("dbo.Matchups", "RoundTeamMatchupId", "dbo.RoundTeamMatchups");
DropForeignKey("dbo.RoundTeamMatchups", "Team2Id", "dbo.Teams");
DropForeignKey("dbo.RoundTeamMatchups", "Team1Id", "dbo.Teams");
DropForeignKey("dbo.RoundTeamMatchups", "RoundId", "dbo.Rounds");
DropForeignKey("dbo.Rounds", "EventId", "dbo.Events");
DropForeignKey("dbo.Matchups", "Player2Id", "dbo.Players");
DropForeignKey("dbo.Matchups", "Player1Id", "dbo.Players");
DropForeignKey("dbo.Players", "TeamId", "dbo.Teams");
DropForeignKey("dbo.Teams", "EventId", "dbo.Events");
DropForeignKey("dbo.Players", "FactionId", "dbo.Factions");
DropIndex("dbo.AspNetUserLogins", new[] { "UserId" });
DropIndex("dbo.AspNetUserClaims", new[] { "UserId" });
DropIndex("dbo.AspNetUsers", "UserNameIndex");
DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" });
DropIndex("dbo.AspNetUserRoles", new[] { "UserId" });
DropIndex("dbo.AspNetRoles", "RoleNameIndex");
DropIndex("dbo.Rounds", new[] { "EventId" });
DropIndex("dbo.RoundTeamMatchups", new[] { "Team2Id" });
DropIndex("dbo.RoundTeamMatchups", new[] { "Team1Id" });
DropIndex("dbo.RoundTeamMatchups", new[] { "RoundId" });
DropIndex("dbo.Teams", new[] { "EventId" });
DropIndex("dbo.Players", new[] { "TeamId" });
DropIndex("dbo.Players", new[] { "FactionId" });
DropIndex("dbo.Matchups", new[] { "WinnerId" });
DropIndex("dbo.Matchups", new[] { "Player2Id" });
DropIndex("dbo.Matchups", new[] { "Player1Id" });
DropIndex("dbo.Matchups", new[] { "RoundTeamMatchupId" });
DropTable("dbo.AspNetUserLogins");
DropTable("dbo.AspNetUserClaims");
DropTable("dbo.AspNetUsers");
DropTable("dbo.AspNetUserRoles");
DropTable("dbo.AspNetRoles");
DropTable("dbo.Rounds");
DropTable("dbo.RoundTeamMatchups");
DropTable("dbo.Teams");
DropTable("dbo.Players");
DropTable("dbo.Matchups");
DropTable("dbo.Factions");
DropTable("dbo.Events");
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009, 2013 Oracle and/or its affiliates. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using NUnit.Framework;
using BerkeleyDB;
namespace CsharpAPITest
{
[TestFixture]
public class HashDatabaseTest : CSharpTestFixture
{
[TestFixtureSetUp]
public void SetUpTestFixture()
{
testFixtureName = "HashDatabaseTest";
base.SetUpTestfixture();
}
[Test]
public void TestCompactWithoutTxn() {
int i, nRecs;
nRecs = 10000;
testName = "TestCompactWithoutTxn";
SetUpTest(true);
string hashDBFileName = testHome + "/" + testName + ".db";
HashDatabaseConfig hashDBConfig = new HashDatabaseConfig();
hashDBConfig.Creation = CreatePolicy.ALWAYS;
// The minimum page size
hashDBConfig.PageSize = 512;
hashDBConfig.HashComparison =
new EntryComparisonDelegate(dbIntCompare);
using (HashDatabase hashDB = HashDatabase.Open(
hashDBFileName, hashDBConfig)) {
DatabaseEntry key;
DatabaseEntry data;
// Fill the database with entries from 0 to 9999
for (i = 0; i < nRecs; i++) {
key = new DatabaseEntry(BitConverter.GetBytes(i));
data = new DatabaseEntry(BitConverter.GetBytes(i));
hashDB.Put(key, data);
}
/*
* Delete entries below 500, between 3000 and
* 5000 and above 7000
*/
for (i = 0; i < nRecs; i++)
if (i < 500 || i > 7000 || (i < 5000 && i > 3000)) {
key = new DatabaseEntry(BitConverter.GetBytes(i));
hashDB.Delete(key);
}
hashDB.Sync();
long fileSize = new FileInfo(hashDBFileName).Length;
// Compact database
CompactConfig cCfg = new CompactConfig();
cCfg.FillPercentage = 30;
cCfg.Pages = 10;
cCfg.Timeout = 1000;
cCfg.TruncatePages = true;
cCfg.start = new DatabaseEntry(BitConverter.GetBytes(1));
cCfg.stop = new DatabaseEntry(BitConverter.GetBytes(7000));
CompactData compactData = hashDB.Compact(cCfg);
Assert.IsFalse((compactData.Deadlocks == 0) &&
(compactData.Levels == 0) &&
(compactData.PagesExamined == 0) &&
(compactData.PagesFreed == 0) &&
(compactData.PagesTruncated == 0));
hashDB.Sync();
long compactedFileSize = new FileInfo(hashDBFileName).Length;
Assert.Less(compactedFileSize, fileSize);
}
}
[Test]
public void TestHashComparison()
{
testName = "TestHashComparison";
SetUpTest(true);
string dbFileName = testHome + "/" + testName + ".db";
HashDatabaseConfig dbConfig = new HashDatabaseConfig();
dbConfig.Creation = CreatePolicy.IF_NEEDED;
dbConfig.HashComparison = new EntryComparisonDelegate(EntryComparison);
HashDatabase db = HashDatabase.Open(dbFileName,dbConfig);
int ret;
/*
* Comparison gets the value that lowest byte of the
* former dbt minus that of the latter one.
*/
ret = db.Compare(new DatabaseEntry(BitConverter.GetBytes(2)),
new DatabaseEntry(BitConverter.GetBytes(2)));
Assert.AreEqual(0, ret);
ret = db.Compare(new DatabaseEntry(BitConverter.GetBytes(256)),
new DatabaseEntry(BitConverter.GetBytes(1)));
Assert.Greater(0, ret);
db.Close();
}
public int EntryComparison(DatabaseEntry dbt1,
DatabaseEntry dbt2)
{
return dbt1.Data[0] - dbt2.Data[0];
}
[Test]
public void TestHashFunction()
{
testName = "TestHashFunction";
SetUpTest(true);
string dbFileName = testHome + "/" + testName + ".db";
HashDatabaseConfig dbConfig = new HashDatabaseConfig();
dbConfig.Creation = CreatePolicy.IF_NEEDED;
dbConfig.HashFunction = new HashFunctionDelegate(HashFunction);
HashDatabase db = HashDatabase.Open(dbFileName, dbConfig);
// Hash function will change the lowest byte to 0;
uint data = db.HashFunction(BitConverter.GetBytes(1));
Assert.AreEqual(0, data);
db.Close();
}
public uint HashFunction(byte[] data)
{
data[0] = 0;
return BitConverter.ToUInt32(data, 0);
}
[Test]
public void TestOpenExistingHashDB()
{
testName = "TestOpenExistingHashDB";
SetUpTest(true);
string dbFileName = testHome + "/" + testName + ".db";
HashDatabaseConfig hashConfig =
new HashDatabaseConfig();
hashConfig.Creation = CreatePolicy.ALWAYS;
HashDatabase hashDB = HashDatabase.Open(dbFileName, hashConfig);
hashDB.Close();
DatabaseConfig dbConfig = new DatabaseConfig();
Database db = Database.Open(dbFileName, dbConfig);
Assert.AreEqual(db.Type, DatabaseType.HASH);
db.Close();
}
[Test]
public void TestOpenNewHashDB()
{
testName = "TestOpenNewHashDB";
SetUpTest(true);
string dbFileName = testHome + "/" + testName + ".db";
XmlElement xmlElem = Configuration.TestSetUp(testFixtureName, testName);
HashDatabaseConfig hashConfig = new HashDatabaseConfig();
HashDatabaseConfigTest.Config(xmlElem, ref hashConfig, true);
HashDatabase hashDB = HashDatabase.Open(dbFileName, hashConfig);
Confirm(xmlElem, hashDB, true);
hashDB.Close();
}
[Test, ExpectedException(typeof(ExpectedTestException))]
public void TestPutNoDuplicateWithUnsortedDuplicate()
{
testName = "TestPutNoDuplicateWithUnsortedDuplicate";
SetUpTest(true);
string dbFileName = testHome + "/" + testName + ".db";
HashDatabaseConfig hashConfig = new HashDatabaseConfig();
hashConfig.Creation = CreatePolicy.ALWAYS;
hashConfig.Duplicates = DuplicatesPolicy.UNSORTED;
hashConfig.ErrorPrefix = testName;
HashDatabase hashDB = HashDatabase.Open(dbFileName, hashConfig);
DatabaseEntry key, data;
key = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("1"));
data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("1"));
try
{
hashDB.PutNoDuplicate(key, data);
}
catch (DatabaseException)
{
throw new ExpectedTestException();
}
finally
{
hashDB.Close();
}
}
[Test, ExpectedException(typeof(ExpectedTestException))]
public void TestKeyExistException()
{
testName = "TestKeyExistException";
SetUpTest(true);
string dbFileName = testHome + "/" + testName + ".db";
HashDatabaseConfig hashConfig = new HashDatabaseConfig();
hashConfig.Creation = CreatePolicy.ALWAYS;
hashConfig.Duplicates = DuplicatesPolicy.SORTED;
HashDatabase hashDB = HashDatabase.Open(dbFileName, hashConfig);
// Put the same record into db twice.
DatabaseEntry key, data;
key = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("1"));
data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("1"));
try
{
hashDB.PutNoDuplicate(key, data);
hashDB.PutNoDuplicate(key, data);
}
catch (KeyExistException)
{
throw new ExpectedTestException();
}
finally
{
hashDB.Close();
}
}
[Test]
public void TestPutNoDuplicate()
{
testName = "TestPutNoDuplicate";
SetUpTest(true);
string dbFileName = testHome + "/" + testName + ".db";
HashDatabaseConfig hashConfig =
new HashDatabaseConfig();
hashConfig.Creation = CreatePolicy.ALWAYS;
hashConfig.Duplicates = DuplicatesPolicy.SORTED;
hashConfig.TableSize = 20;
HashDatabase hashDB = HashDatabase.Open(dbFileName, hashConfig);
DatabaseEntry key, data;
for (int i = 1; i <= 10; i++)
{
key = new DatabaseEntry(BitConverter.GetBytes(i));
data = new DatabaseEntry(BitConverter.GetBytes(i));
hashDB.PutNoDuplicate(key, data);
}
Assert.IsTrue(hashDB.Exists(
new DatabaseEntry(BitConverter.GetBytes((int)5))));
hashDB.Close();
}
[Test, ExpectedException(typeof(ExpectedTestException))]
public void TestPutNoDuplicateWithTxn()
{
testName = "TestPutNoDuplicateWithTxn";
SetUpTest(true);
// Open an environment.
DatabaseEnvironmentConfig envConfig =
new DatabaseEnvironmentConfig();
envConfig.Create = true;
envConfig.UseLogging = true;
envConfig.UseMPool = true;
envConfig.UseTxns = true;
DatabaseEnvironment env = DatabaseEnvironment.Open(
testHome, envConfig);
// Open a hash database within a transaction.
Transaction txn = env.BeginTransaction();
HashDatabaseConfig dbConfig = new HashDatabaseConfig();
dbConfig.Creation = CreatePolicy.IF_NEEDED;
dbConfig.Duplicates = DuplicatesPolicy.SORTED;
dbConfig.Env = env;
HashDatabase db = HashDatabase.Open(testName + ".db", dbConfig, txn);
DatabaseEntry dbt = new DatabaseEntry(BitConverter.GetBytes((int)100));
db.PutNoDuplicate(dbt, dbt, txn);
try
{
db.PutNoDuplicate(dbt, dbt, txn);
}
catch (KeyExistException)
{
throw new ExpectedTestException();
}
finally
{
// Close all.
db.Close();
txn.Commit();
env.Close();
}
}
[Test]
public void TestStats()
{
testName = "TestStats";
SetUpTest(true);
string dbFileName = testHome + "/" + testName + ".db";
HashDatabaseConfig dbConfig = new HashDatabaseConfig();
ConfigCase1(dbConfig);
HashDatabase db = HashDatabase.Open(dbFileName, dbConfig);
HashStats stats = db.Stats();
HashStats fastStats = db.FastStats();
ConfirmStatsPart1Case1(stats);
ConfirmStatsPart1Case1(fastStats);
// Put 100 records into the database.
PutRecordCase1(db, null);
stats = db.Stats();
ConfirmStatsPart2Case1(stats);
// Delete some data to get some free pages.
byte[] bigArray = new byte[262144];
db.Delete(new DatabaseEntry(bigArray));
stats = db.Stats();
ConfirmStatsPart3Case1(stats);
db.Close();
}
[Test]
public void TestStatsInTxn()
{
testName = "TestStatsInTxn";
SetUpTest(true);
StatsInTxn(testHome, testName, false);
}
[Test]
public void TestStatsWithIsolation()
{
testName = "TestStatsWithIsolation";
SetUpTest(true);
StatsInTxn(testHome, testName, true);
}
private int dbIntCompare(DatabaseEntry dbt1, DatabaseEntry dbt2) {
int a, b;
a = BitConverter.ToInt32(dbt1.Data, 0);
b = BitConverter.ToInt32(dbt2.Data, 0);
return a - b;
}
public void StatsInTxn(string home, string name, bool ifIsolation)
{
DatabaseEnvironmentConfig envConfig =
new DatabaseEnvironmentConfig();
EnvConfigCase1(envConfig);
DatabaseEnvironment env = DatabaseEnvironment.Open(home, envConfig);
Transaction openTxn = env.BeginTransaction();
HashDatabaseConfig dbConfig = new HashDatabaseConfig();
ConfigCase1(dbConfig);
dbConfig.Env = env;
HashDatabase db = HashDatabase.Open(name + ".db", dbConfig, openTxn);
openTxn.Commit();
Transaction statsTxn = env.BeginTransaction();
HashStats stats;
HashStats fastStats;
if (ifIsolation == false)
{
stats = db.Stats(statsTxn);
fastStats = db.Stats(statsTxn);
}
else
{
stats = db.Stats(statsTxn, Isolation.DEGREE_ONE);
fastStats = db.Stats(statsTxn, Isolation.DEGREE_ONE);
}
ConfirmStatsPart1Case1(stats);
// Put 100 records into the database.
PutRecordCase1(db, statsTxn);
if (ifIsolation == false)
stats = db.Stats(statsTxn);
else
stats = db.Stats(statsTxn, Isolation.DEGREE_TWO);
ConfirmStatsPart2Case1(stats);
// Delete some data to get some free pages.
byte[] bigArray = new byte[262144];
db.Delete(new DatabaseEntry(bigArray), statsTxn);
if (ifIsolation == false)
stats = db.Stats(statsTxn);
else
stats = db.Stats(statsTxn, Isolation.DEGREE_THREE);
ConfirmStatsPart3Case1(stats);
statsTxn.Commit();
db.Close();
env.Close();
}
public void EnvConfigCase1(DatabaseEnvironmentConfig cfg)
{
cfg.Create = true;
cfg.UseTxns = true;
cfg.UseMPool = true;
cfg.UseLogging = true;
}
public void ConfigCase1(HashDatabaseConfig dbConfig)
{
dbConfig.Creation = CreatePolicy.IF_NEEDED;
dbConfig.Duplicates = DuplicatesPolicy.UNSORTED;
dbConfig.FillFactor = 10;
dbConfig.TableSize = 20;
dbConfig.PageSize = 4096;
}
public void PutRecordCase1(HashDatabase db, Transaction txn)
{
byte[] bigArray = new byte[262144];
for (int i = 0; i < 50; i++)
{
if (txn == null)
db.Put(new DatabaseEntry(BitConverter.GetBytes(i)),
new DatabaseEntry(BitConverter.GetBytes(i)));
else
db.Put(new DatabaseEntry(BitConverter.GetBytes(i)),
new DatabaseEntry(BitConverter.GetBytes(i)), txn);
}
for (int i = 50; i < 100; i++)
{
if (txn == null)
db.Put(new DatabaseEntry(bigArray),
new DatabaseEntry(bigArray));
else
db.Put(new DatabaseEntry(bigArray),
new DatabaseEntry(bigArray), txn);
}
}
public void ConfirmStatsPart1Case1(HashStats stats)
{
Assert.AreEqual(10, stats.FillFactor);
Assert.AreEqual(4096, stats.PageSize);
Assert.AreNotEqual(0, stats.Version);
}
public void ConfirmStatsPart2Case1(HashStats stats)
{
Assert.AreNotEqual(0, stats.BigPages);
Assert.AreNotEqual(0, stats.BigPagesFreeBytes);
Assert.AreNotEqual(0, stats.BucketPagesFreeBytes);
Assert.AreNotEqual(0, stats.DuplicatePages);
Assert.AreNotEqual(0, stats.DuplicatePagesFreeBytes);
Assert.AreNotEqual(0, stats.MagicNumber);
Assert.AreNotEqual(0, stats.MetadataFlags);
Assert.AreEqual(100, stats.nData);
Assert.AreNotEqual(0, stats.nHashBuckets);
Assert.AreEqual(51, stats.nKeys);
Assert.AreNotEqual(0, stats.nPages);
Assert.AreEqual(0, stats.OverflowPages);
Assert.AreEqual(0, stats.OverflowPagesFreeBytes);
}
public void ConfirmStatsPart3Case1(HashStats stats)
{
Assert.AreNotEqual(0, stats.FreePages);
}
public static void Confirm(XmlElement xmlElem,
HashDatabase hashDB, bool compulsory)
{
DatabaseTest.Confirm(xmlElem, hashDB, compulsory);
Configuration.ConfirmCreatePolicy(xmlElem,
"Creation", hashDB.Creation, compulsory);
Configuration.ConfirmDuplicatesPolicy(xmlElem,
"Duplicates", hashDB.Duplicates, compulsory);
Configuration.ConfirmUint(xmlElem,
"FillFactor", hashDB.FillFactor, compulsory);
Configuration.ConfirmUint(xmlElem,
"NumElements", hashDB.TableSize,
compulsory);
Assert.AreEqual(DatabaseType.HASH, hashDB.Type);
string type = hashDB.Type.ToString();
Assert.IsNotNull(type);
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// DefaultIfEmptyQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// This operator just exposes elements directly from the underlying data source, if
/// it's not empty, or yields a single default element if the data source is empty.
/// There is a minimal amount of synchronization at the beginning, until all partitions
/// have registered whether their stream is empty or not. Once the 0th partition knows
/// that at least one other partition is non-empty, it may proceed. Otherwise, it is
/// the 0th partition which yields the default value.
/// </summary>
/// <typeparam name="TSource"></typeparam>
internal sealed class DefaultIfEmptyQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource>
{
private readonly TSource _defaultValue; // The default value to use (if empty).
//---------------------------------------------------------------------------------------
// Initializes a new reverse operator.
//
// Arguments:
// child - the child whose data we will reverse
//
internal DefaultIfEmptyQueryOperator(IEnumerable<TSource> child, TSource defaultValue)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
_defaultValue = defaultValue;
SetOrdinalIndexState(ExchangeUtilities.Worse(Child.OrdinalIndexState, OrdinalIndexState.Correct));
}
//---------------------------------------------------------------------------------------
// 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, preferStriping);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
// Generate the shared data.
Shared<int> sharedEmptyCount = new Shared<int>(0);
CountdownEvent sharedLatch = new CountdownEvent(partitionCount - 1);
PartitionedStream<TSource, TKey> outputStream =
new PartitionedStream<TSource, TKey>(partitionCount, inputStream.KeyComparer, OrdinalIndexState);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new DefaultIfEmptyQueryOperatorEnumerator<TKey>(
inputStream[i], _defaultValue, i, partitionCount, sharedEmptyCount, sharedLatch, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token)
{
return Child.AsSequentialQuery(token).DefaultIfEmpty(_defaultValue);
}
//---------------------------------------------------------------------------------------
// 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 false; }
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for executing the default-if-empty operation.
//
private class DefaultIfEmptyQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TSource, TKey>
{
private QueryOperatorEnumerator<TSource, TKey> _source; // The data source to enumerate.
private bool _lookedForEmpty; // Whether this partition has looked for empty yet.
private int _partitionIndex; // This enumerator's partition index.
private int _partitionCount; // The number of partitions.
private TSource _defaultValue; // The default value if the 0th partition is empty.
// Data shared among partitions.
private Shared<int> _sharedEmptyCount; // The number of empty partitions.
private CountdownEvent _sharedLatch; // Shared latch, signaled when partitions process the 1st item.
private CancellationToken _cancelToken; // Token used to cancel this operator.
//---------------------------------------------------------------------------------------
// Instantiates a new select enumerator.
//
internal DefaultIfEmptyQueryOperatorEnumerator(
QueryOperatorEnumerator<TSource, TKey> source, TSource defaultValue, int partitionIndex, int partitionCount,
Shared<int> sharedEmptyCount, CountdownEvent sharedLatch, CancellationToken cancelToken)
{
Debug.Assert(source != null);
Debug.Assert(0 <= partitionIndex && partitionIndex < partitionCount);
Debug.Assert(partitionCount > 0);
Debug.Assert(sharedEmptyCount != null);
Debug.Assert(sharedLatch != null);
_source = source;
_defaultValue = defaultValue;
_partitionIndex = partitionIndex;
_partitionCount = partitionCount;
_sharedEmptyCount = sharedEmptyCount;
_sharedLatch = sharedLatch;
_cancelToken = cancelToken;
}
//---------------------------------------------------------------------------------------
// Straightforward IEnumerator<T> methods.
//
internal override bool MoveNext(ref TSource currentElement, ref TKey currentKey)
{
Debug.Assert(_source != null);
bool moveNextResult = _source.MoveNext(ref currentElement, ref currentKey);
// There is special logic the first time this function is called.
if (!_lookedForEmpty)
{
// Ensure we don't enter this loop again.
_lookedForEmpty = true;
if (!moveNextResult)
{
if (_partitionIndex == 0)
{
// If this is the 0th partition, we must wait for all others. Note: we could
// actually do a wait-any here: if at least one other partition finds an element,
// there is strictly no need to wait. But this would require extra coordination
// which may or may not be worth the trouble.
_sharedLatch.Wait(_cancelToken);
_sharedLatch.Dispose();
// Now see if there were any other partitions with data.
if (_sharedEmptyCount.Value == _partitionCount - 1)
{
// No data, we will yield the default value.
currentElement = _defaultValue;
currentKey = default(TKey);
return true;
}
else
{
// Another partition has data, we are done.
return false;
}
}
else
{
// Not the 0th partition, we will increment the shared empty counter.
Interlocked.Increment(ref _sharedEmptyCount.Value);
}
}
// Every partition (but the 0th) will signal the latch the first time.
if (_partitionIndex != 0)
{
_sharedLatch.Signal();
}
}
return moveNextResult;
}
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Internal;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// inner command class used to manage the sub pipelines
/// it determines which command should process the incoming objects
/// based on the object type
///
/// This class is the implementation class for out-console and out-file
/// </summary>
internal sealed class OutputManagerInner : ImplementationCommandBase
{
#region tracer
[TraceSource("format_out_OutputManagerInner", "OutputManagerInner")]
internal static PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutputManagerInner", "OutputManagerInner");
#endregion tracer
#region LineOutput
internal LineOutput LineOutput
{
set
{
lock (_syncRoot)
{
_lo = value;
if (_isStopped)
{
_lo.StopProcessing();
}
}
}
}
private LineOutput _lo = null;
#endregion
/// <summary>
/// handler for processing each object coming through the pipeline
/// it forwards the call to the pipeline manager object
/// </summary>
internal override void ProcessRecord()
{
PSObject so = this.ReadObject();
if (so == null || so == AutomationNull.Value)
{
return;
}
// on demand initialization when the first pipeline
// object is initialized
if (_mgr == null)
{
_mgr = new SubPipelineManager();
_mgr.Initialize(_lo, this.OuterCmdlet().Context);
}
#if false
// if the object supports IEnumerable,
// unpack the object and process each member separately
IEnumerable e = PSObjectHelper.GetEnumerable (so);
if (e == null)
{
this.mgr.Process (so);
}
else
{
foreach (object obj in e)
{
this.mgr.Process (PSObjectHelper.AsPSObject (obj));
}
}
#else
_mgr.Process(so);
#endif
}
/// <summary>
/// handler for processing shut down. It forwards the call to the
/// pipeline manager object
/// </summary>
internal override void EndProcessing()
{
// shut down only if we ever processed a pipeline object
if (_mgr != null)
_mgr.ShutDown();
}
internal override void StopProcessing()
{
lock (_syncRoot)
{
if (_lo != null)
{
_lo.StopProcessing();
}
_isStopped = true;
}
}
/// <summary>
/// make sure we dispose of the sub pipeline manager
/// </summary>
protected override void InternalDispose()
{
base.InternalDispose();
if (_mgr != null)
{
_mgr.Dispose();
_mgr = null;
}
}
/// <summary>
/// instance of the pipeline manager object
/// </summary>
private SubPipelineManager _mgr = null;
/// <summary>
/// True if the cmdlet has been stopped
/// </summary>
private bool _isStopped = false;
/// <summary>
/// Lock object
/// </summary>
private object _syncRoot = new object();
}
/// <summary>
/// object managing the sub-pipelines that execute
/// different output commands (or different instances of the
/// default one)
/// </summary>
internal sealed class SubPipelineManager : IDisposable
{
/// <summary>
/// entry defining a command to be run in a separate pipeline
/// </summary>
private sealed class CommandEntry : IDisposable
{
/// <summary>
/// instance of pipeline wrapper object
/// </summary>
internal CommandWrapper command = new CommandWrapper();
/// <summary>
///
/// </summary>
/// <param name="typeName">ETS type name of the object to process</param>
/// <returns>true if there is a match</returns>
internal bool AppliesToType(string typeName)
{
foreach (String s in _applicableTypes)
{
if (string.Equals(s, typeName, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>
/// just dispose of the inner command wrapper
/// </summary>
public void Dispose()
{
if (this.command == null)
return;
this.command.Dispose();
this.command = null;
}
/// <summary>
/// ordered list of ETS type names this object is handling
/// </summary>
private StringCollection _applicableTypes = new StringCollection();
}
/// <summary>
/// Initialize the pipeline manager before any object is processed
/// </summary>
/// <param name="lineOutput">LineOutput to pass to the child pipelines</param>
/// <param name="context">ExecutionContext to pass to the child pipelines</param>
internal void Initialize(LineOutput lineOutput, ExecutionContext context)
{
_lo = lineOutput;
InitializeCommandsHardWired(context);
}
/// <summary>
/// hard wired registration helper for specialized types
/// </summary>
/// <param name="context">ExecutionContext to pass to the child pipeline</param>
private void InitializeCommandsHardWired(ExecutionContext context)
{
// set the default handler
RegisterCommandDefault(context, "out-lineoutput", typeof(OutLineOutputCommand));
/*
NOTE:
This is the spot where we could add new specialized handlers for
additional types. Adding a handler here would cause a new sub-pipeline
to be created.
For example, the following line would add a new handler named "out-foobar"
to be invoked when the incoming object type is "MyNamespace.Whatever.FooBar"
RegisterCommandForTypes (context, "out-foobar", new string[] { "MyNamespace.Whatever.FooBar" });
And the method can be like this:
private void RegisterCommandForTypes (ExecutionContext context, string commandName, Type commandType, string[] types)
{
CommandEntry ce = new CommandEntry ();
ce.command.Initialize (context, commandName, commandType);
ce.command.AddNamedParameter ("LineOutput", this.lo);
for (int k = 0; k < types.Length; k++)
{
ce.AddApplicableType (types[k]);
}
this.commandEntryList.Add (ce);
}
*/
}
/// <summary>
/// register the default output command
/// </summary>
/// <param name="context">ExecutionContext to pass to the child pipeline</param>
/// <param name="commandName">name of the command to execute</param>
/// <param name="commandType">Type of the command to execute</param>
private void RegisterCommandDefault(ExecutionContext context, string commandName, Type commandType)
{
CommandEntry ce = new CommandEntry();
ce.command.Initialize(context, commandName, commandType);
ce.command.AddNamedParameter("LineOutput", _lo);
_defaultCommandEntry = ce;
}
/// <summary>
/// process an incoming parent pipeline object
/// </summary>
/// <param name="so">pipeline object to process</param>
internal void Process(PSObject so)
{
// select which pipeline should handle the object
CommandEntry ce = this.GetActiveCommandEntry(so);
Diagnostics.Assert(ce != null, "CommandEntry ce must not be null");
// delegate the processing
ce.command.Process(so);
}
/// <summary>
/// shut down the child pipelines
/// </summary>
internal void ShutDown()
{
// we assume that command entries are never null
foreach (CommandEntry ce in _commandEntryList)
{
Diagnostics.Assert(ce != null, "ce != null");
ce.command.ShutDown();
ce.command = null;
}
// we assume we always have a default command entry
Diagnostics.Assert(_defaultCommandEntry != null, "defaultCommandEntry != null");
_defaultCommandEntry.command.ShutDown();
_defaultCommandEntry.command = null;
}
public void Dispose()
{
// we assume that command entries are never null
foreach (CommandEntry ce in _commandEntryList)
{
Diagnostics.Assert(ce != null, "ce != null");
ce.Dispose();
}
// we assume we always have a default command entry
Diagnostics.Assert(_defaultCommandEntry != null, "defaultCommandEntry != null");
_defaultCommandEntry.Dispose();
}
/// <summary>
/// it selects the applicable out command (it can be the default one)
/// to process the current pipeline object
/// </summary>
/// <param name="so">pipeline object to be processed</param>
/// <returns>applicable command entry</returns>
private CommandEntry GetActiveCommandEntry(PSObject so)
{
string typeName = PSObjectHelper.PSObjectIsOfExactType(so.InternalTypeNames);
foreach (CommandEntry ce in _commandEntryList)
{
if (ce.AppliesToType(typeName))
return ce;
}
// falied any match: return the default handler
return _defaultCommandEntry;
}
private LineOutput _lo = null;
/// <summary>
/// list of command entries, each with a set of applicable types
/// </summary>
private List<CommandEntry> _commandEntryList = new List<CommandEntry>();
/// <summary>
/// default command entry to be executed when all type matches fail
/// </summary>
private CommandEntry _defaultCommandEntry = new CommandEntry();
}
}
| |
//
// Copyright (c) 2008-2019 the Urho3D project.
// Copyright (c) 2017-2020 the rbfx project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Urho3DNet
{
/// 3x3 matrix for rotation and scaling.
[StructLayout(LayoutKind.Sequential)]
public struct Matrix3 : IEquatable<Matrix3>
{
/// Construct from values or identity matrix by default.
public Matrix3(float v00 = 1, float v01 = 0, float v02 = 0,
float v10 = 0, float v11 = 1, float v12 = 0,
float v20 = 0, float v21 = 0, float v22 = 1)
{
M00 = v00;
M01 = v01;
M02 = v02;
M10 = v10;
M11 = v11;
M12 = v12;
M20 = v20;
M21 = v21;
M22 = v22;
}
/// Construct from a float array.
public Matrix3(IReadOnlyList<float> data)
{
M00 = data[0];
M01 = data[1];
M02 = data[2];
M10 = data[3];
M11 = data[4];
M12 = data[5];
M20 = data[6];
M21 = data[7];
M22 = data[8];
}
/// Test for equality with another matrix without epsilon.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(in Matrix3 lhs, in Matrix3 rhs)
{
return 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;
}
/// Test for inequality with another matrix without epsilon.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(in Matrix3 lhs, in Matrix3 rhs)
{
return !(lhs == rhs);
}
/// Multiply a Vector3.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(in Matrix3 lhs, in Vector3 rhs)
{
return new Vector3(
lhs.M00 * rhs.X + lhs.M01 * rhs.Y + lhs.M02 * rhs.Z,
lhs.M10 * rhs.X + lhs.M11 * rhs.Y + lhs.M12 * rhs.Z,
lhs.M20 * rhs.X + lhs.M21 * rhs.Y + lhs.M22 * rhs.Z
);
}
/// Add a matrix.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Matrix3 operator +(in Matrix3 lhs, in Matrix3 rhs)
{
return new Matrix3(
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
);
}
/// Subtract a matrix.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Matrix3 operator -(in Matrix3 lhs, in Matrix3 rhs)
{
return new Matrix3(
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
);
}
/// Multiply with a scalar.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Matrix3 operator *(in Matrix3 lhs, float rhs)
{
return new Matrix3(
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
);
}
/// Multiply a matrix.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Matrix3 operator *(in Matrix3 lhs, in Matrix3 rhs)
{
return new Matrix3(
lhs.M00 * rhs.M00 + lhs.M01 * rhs.M10 + lhs.M02 * rhs.M20,
lhs.M00 * rhs.M01 + lhs.M01 * rhs.M11 + lhs.M02 * rhs.M21,
lhs.M00 * rhs.M02 + lhs.M01 * rhs.M12 + lhs.M02 * rhs.M22,
lhs.M10 * rhs.M00 + lhs.M11 * rhs.M10 + lhs.M12 * rhs.M20,
lhs.M10 * rhs.M01 + lhs.M11 * rhs.M11 + lhs.M12 * rhs.M21,
lhs.M10 * rhs.M02 + lhs.M11 * rhs.M12 + lhs.M12 * rhs.M22,
lhs.M20 * rhs.M00 + lhs.M21 * rhs.M10 + lhs.M22 * rhs.M20,
lhs.M20 * rhs.M01 + lhs.M21 * rhs.M11 + lhs.M22 * rhs.M21,
lhs.M20 * rhs.M02 + lhs.M21 * rhs.M12 + lhs.M22 * rhs.M22
);
}
/// Multiply a 3x3 matrix with a scalar.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Matrix3 operator *(float lhs, in Matrix3 rhs)
{
return rhs * lhs;
}
/// Set scaling elements.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetScale(in Vector3 scale)
{
M00 = scale.X;
M11 = scale.Y;
M22 = scale.Z;
}
/// Set uniform scaling elements.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetScale(float scale)
{
M00 = scale;
M11 = scale;
M22 = scale;
}
/// Return the scaling part.
public Vector3 Scale => new Vector3(
(float) Math.Sqrt(M00 * M00 + M10 * M10 + M20 * M20),
(float) Math.Sqrt(M01 * M01 + M11 * M11 + M21 * M21),
(float) Math.Sqrt(M02 * M02 + M12 * M12 + M22 * M22)
);
/// Return the scaling part with the sign. Reference rotation matrix is required to avoid ambiguity.
public Vector3 SignedScale(in Matrix3 rotation)
{
return new Vector3(
rotation.M00 * M00 + rotation.M10 * M10 + rotation.M20 * M20,
rotation.M01 * M01 + rotation.M11 * M11 + rotation.M21 * M21,
rotation.M02 * M02 + rotation.M12 * M12 + rotation.M22 * M22
);
}
/// Return transposed.
public Matrix3 Transposed => new Matrix3(M00, M10, M20, M01, M11, M21, M02, M12, M22);
/// Return scaled by a vector.
public Matrix3 Scaled(in Vector3 scale)
{
return new Matrix3(
M00 * scale.X,
M01 * scale.Y,
M02 * scale.Z,
M10 * scale.X,
M11 * scale.Y,
M12 * scale.Z,
M20 * scale.X,
M21 * scale.Y,
M22 * scale.Z
);
}
/// Test for equality with another matrix with epsilon.
public bool Equals(Matrix3 rhs)
{
return this == rhs;
}
public override bool Equals(object obj)
{
return obj is Matrix3 other && Equals(other);
}
/// Return inverse.
public Matrix3 Inverse()
{
float det = M00 * M11 * M22 +
M10 * M21 * M02 +
M20 * M01 * M12 -
M20 * M11 * M02 -
M10 * M01 * M22 -
M00 * M21 * M12;
float invDet = 1.0f / det;
return new Matrix3(
(M11 * M22 - M21 * M12) * invDet,
-(M01 * M22 - M21 * M02) * invDet,
(M01 * M12 - M11 * M02) * invDet,
-(M10 * M22 - M20 * M12) * invDet,
(M00 * M22 - M20 * M02) * invDet,
-(M00 * M12 - M10 * M02) * invDet,
(M10 * M21 - M20 * M11) * invDet,
-(M00 * M21 - M20 * M01) * invDet,
(M00 * M11 - M10 * M01) * invDet
);
}
/// Return float data.
public float[] Data()
=> new[] {M00, M01, M02, M10, M11, M12, M20, M21, M22};
/// Return matrix element.
public float this[int i, int j]
{
get
{
unsafe
{
fixed (float* p = &M00)
{
return p[i * 3 + j];
}
}
}
set
{
unsafe
{
fixed (float* p = &M00)
{
p[i * 3 + j] = value;
}
}
}
}
/// Return matrix row.
public Vector3 Row(int i)
{
return new Vector3(this[i, 0], this[i, 1], this[i, 2]);
}
/// Return matrix column.
public Vector3 Column(int j)
{
return new Vector3(this[0, j], this[1, j], this[2, j]);
}
/// Return as string.
public override string ToString()
{
return $"{M00} {M01} {M02} {M10} {M11} {M12} {M20} {M21} {M22}";
}
public float M00;
public float M01;
public float M02;
public float M10;
public float M11;
public float M12;
public float M20;
public float M21;
public float M22;
/// Bulk transpose matrices.
public static unsafe void BulkTranspose(float* dest, float* src, int count)
{
for (int i = 0; i < count; ++i)
{
dest[0] = src[0];
dest[1] = src[3];
dest[2] = src[6];
dest[3] = src[1];
dest[4] = src[4];
dest[5] = src[7];
dest[6] = src[2];
dest[7] = src[5];
dest[8] = src[8];
dest += 9;
src += 9;
}
}
/// Zero matrix.
static Matrix3 Zero = new Matrix3(0, 0, 0, 0, 0, 0, 0, 0, 0);
/// Identity matrix.
static Matrix3 Identity = new Matrix3(
1, 0, 0,
0, 1, 0,
0, 0, 1);
public override int GetHashCode()
{
unchecked
{
var hashCode = M00.GetHashCode();
hashCode = (hashCode * 397) ^ M01.GetHashCode();
hashCode = (hashCode * 397) ^ M02.GetHashCode();
hashCode = (hashCode * 397) ^ M10.GetHashCode();
hashCode = (hashCode * 397) ^ M11.GetHashCode();
hashCode = (hashCode * 397) ^ M12.GetHashCode();
hashCode = (hashCode * 397) ^ M20.GetHashCode();
hashCode = (hashCode * 397) ^ M21.GetHashCode();
hashCode = (hashCode * 397) ^ M22.GetHashCode();
return hashCode;
}
}
};
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.TeamFoundation.Core.WebApi.Types;
using Microsoft.TeamFoundation.Work.WebApi;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;
using Microsoft.VisualStudio.Services.WebApi.Patch;
using Microsoft.VisualStudio.Services.WebApi.Patch.Json;
using TfsCmdlets.Extensions;
using TfsCmdlets.Util;
namespace TfsCmdlets.Cmdlets.Team
{
/// <summary>
/// Changes the details of a team.
/// </summary>
[Cmdlet(VerbsCommon.Set, "TfsTeam", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType(typeof(WebApiTeam))]
public class SetTeam : SetCmdletBase<Models.Team>
{
/// <summary>
/// HELP_PARAM_TEAM
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[Alias("Name")]
[SupportsWildcards()]
public object Team { get; set; }
/// <summary>
/// Specifies a new description
/// </summary>
[Parameter()]
public string Description { get; set; }
/// <summary>
/// Specifies the team's default area path (or "team field"). The default area path is assigned
/// automatically to all work items created in a team's backlog and/or board.
/// </summary>
[Parameter()]
[Alias("TeamFieldValue")]
public string DefaultAreaPath { get; set; }
/// <summary>
/// Specifies the backlog area paths that are associated with this team. Provide a list
/// of area paths in the form '/path1/path2/[*]'. When the path ends with an asterisk, all
/// child area path will be included recursively. Otherwise, only the area itself (without
/// its children) will be included.
/// </summary>
[Parameter()]
public IEnumerable<string> AreaPaths { get; set; }
/// <summary>
/// Specifies the team's backlog iteration path. When omitted, defaults to the team project's root iteration.
/// </summary>
[Parameter()]
public string BacklogIteration { get; set; } = "\\";
/// <summary>
/// Specifies the backlog iteration paths that are associated with this team. Provide a list
/// of iteration paths in the form '/path1/path2'.
/// </summary>
[Parameter()]
public object IterationPaths { get; set; }
/// <summary>
/// Specifies the default iteration macro. When omitted, defaults to "@CurrentIteration".
/// </summary>
[Parameter()]
public string DefaultIterationMacro { get; set; } = "@CurrentIteration";
/// <summary>
/// Specifies the team's Working Days. When omitted, defaults to Monday thru Friday
/// </summary>
[Parameter()]
public IEnumerable<string> WorkingDays = new[] { "monday", "tuesday", "wednesday", "thursday", "friday" };
/// <summary>
/// Specifies how bugs should behave when added to a board.
/// </summary>
[Parameter()]
[ValidateSet("AsTasks", "AsRequirements", "Off")]
public string BugsBehavior { get; set; }
/// <summary>
/// Specifies which backlog levels (e.g. Epics, Features, Stories) should be visible.
/// </summary>
[Parameter()]
public Hashtable BacklogVisibilities { get; set; }
/// <summary>
/// Sets the supplied team as the default team project team.
/// </summary>
[Parameter()]
public SwitchParameter Default { get; set; }
}
partial class TeamDataService
{
protected override Models.Team DoSetItem()
{
var (tpc, tp, t) = GetCollectionProjectAndTeam();
var description = GetParameter<string>(nameof(SetTeam.Description));
var defaultTeam = GetParameter<bool>(nameof(SetTeam.Default));
var defaultAreaPath = GetParameter<string>(nameof(SetTeam.DefaultAreaPath));
var areaPaths = GetParameter<IEnumerable<string>>(nameof(SetTeam.AreaPaths));
var backlogIteration = GetParameter<string>(nameof(SetTeam.BacklogIteration));
var iterationPaths = GetParameter<IEnumerable<string>>(nameof(SetTeam.IterationPaths));
var defaultIteration = GetParameter<string>(nameof(SetTeam.DefaultIterationMacro));
var teamClient = GetClient<TeamHttpClient>();
var projectClient = GetClient<ProjectHttpClient>();
var workClient = GetClient<WorkHttpClient>();
// Set description
if (HasParameter("Description") && ShouldProcess(t, $"Set team's description to '{description}'"))
{
teamClient.UpdateTeamAsync(new WebApiTeam()
{
Description = description ?? string.Empty
}, tp.Id.ToString(), t.Id.ToString())
.GetResult($"Error setting team '{t.Name}''s description to '{description}'");
}
// Set default team
if (defaultTeam && ShouldProcess(tp, $"Set team '{t.Name} as default'"))
{
throw new NotImplementedException("Set team as default is currently not supported");
}
// Set Team Field / Area Path settings
var ctx = new TeamContext(tp.Name, t.Name);
var teamFieldPatch = new TeamFieldValuesPatch();
if (!string.IsNullOrEmpty(defaultAreaPath) &&
ShouldProcess(t, $"Set team's default area path (team field) to '{defaultAreaPath}'"))
{
if (tpc.IsHosted)
{
this.Log("Conected to Azure DevOps Services. Treating Team Field Value as Area Path");
defaultAreaPath = NodeUtil.NormalizeNodePath(defaultAreaPath, tp.Name, "Areas", includeTeamProject: true);
}
if (areaPaths == null)
{
this.Log("AreaPaths is empty. Adding DefaultAreaPath (TeamFieldValue) to AreaPaths as default value.");
areaPaths = new string[] { defaultAreaPath };
}
var area = new { Node = defaultAreaPath };
if (!TestItem<Models.ClassificationNode>(area))
{
NewItem<Models.ClassificationNode>(area);
}
this.Log($"Setting default area path (team field) to {defaultAreaPath}");
teamFieldPatch.DefaultValue = defaultAreaPath;
}
if (areaPaths != null &&
ShouldProcess(t, $"Set {string.Join(", ", areaPaths)} as team's area paths"))
{
var values = new List<TeamFieldValue>();
foreach (var a in areaPaths)
{
values.Add(new TeamFieldValue()
{
Value = NodeUtil.NormalizeNodePath(a.TrimEnd('\\', '*'), tp.Name, scope: "Areas", includeTeamProject: true),
IncludeChildren = a.EndsWith("*")
});
}
teamFieldPatch.Values = values;
workClient.UpdateTeamFieldValuesAsync(teamFieldPatch, ctx)
.GetResult("Error applying team field value and/or area path settings");
}
// Set backlog and iteration path settings
bool isDirty = false;
var iterationPatch = new TeamSettingsPatch();
if (backlogIteration != null &&
ShouldProcess(t, $"Set the team's backlog iteration to '{backlogIteration}'"))
{
this.Log($"Setting backlog iteration to {backlogIteration}");
var iteration = GetItem<Models.ClassificationNode>(new
{
Node = backlogIteration,
StructureGroup = TreeStructureGroup.Iterations
});
iterationPatch.BacklogIteration =
iterationPatch.DefaultIteration =
iteration.Identifier;
isDirty = true;
}
if (!string.IsNullOrEmpty(defaultIteration) &&
ShouldProcess(t, $"Set the team's default iteration to '{defaultIteration}'"))
{
this.Log($"Setting default iteration to '{defaultIteration}'");
if (!defaultIteration.StartsWith("@"))
{
var iteration = GetItem<Models.ClassificationNode>(new
{
Node = defaultIteration,
StructureGroup = TreeStructureGroup.Iterations
});
iterationPatch.DefaultIteration = iteration.Identifier;
}
else
{
iterationPatch.DefaultIteration = null;
iterationPatch.DefaultIterationMacro = defaultIteration;
}
isDirty = true;
}
if (isDirty) workClient.UpdateTeamSettingsAsync(iterationPatch, ctx)
.GetResult("Error applying iteration and/or board settings");
// TODO: Finish migration
// if (BacklogVisibilities && ShouldProcess(Team, $"Set the team"s backlog visibilities to {_DumpObj {BacklogVisibilities}}"))
// {
// this.Log($"Setting backlog iteration to {BacklogVisibilities}");
// patch.BacklogVisibilities = _NewDictionary @([string], [bool]) BacklogVisibilities
// isDirty = true
// }
// if (DefaultIterationMacro && ShouldProcess(Team, $"Set the team"s default iteration macro to {DefaultIterationMacro}"))
// {
// this.Log($"Setting default iteration macro to {DefaultIterationMacro}");
// patch.DefaultIterationMacro = DefaultIterationMacro
// isDirty = true
// }
// if (WorkingDays && ShouldProcess(Team, $"Set the team"s working days to {_DumpObj {WorkingDays}}"))
// {
// this.Log($"Setting working days to {{WorkingDays}|ConvertTo=-Json -Compress}");
// patch.WorkingDays = WorkingDays
// isDirty = true
// }
// if(BugsBehavior && ShouldProcess(Team, $"Set the team"s bugs behavior to {_DumpObj {BugsBehavior}}"))
// {
// this.Log($"Setting bugs behavior to {_DumpObj {BugsBehavior}}");
// patch.BugsBehavior = BugsBehavior
// isDirty = true
// }
// if(isDirty)
// {
// task = client.UpdateTeamSettingsAsync(patch, ctx)
// result = task.Result; if(task.IsFaulted) { _throw new Exception("Error applying iteration settings" task.Exception.InnerExceptions })
// }
// if(Passthru.IsPresent)
// {
// WriteObject(t); return;
// }
// }
// }
return GetItem<Models.Team>();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// ported from https://github.com/dotnet/roslyn/blob/aaee215045c03c4f4b38a66b56d35261ee7f0ddc/src/Test/Utilities/Portable/Platform/Desktop/CLRHelpers.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using PEVerify;
using Roslyn.Test.Utilities.Desktop.ComTypes;
namespace Roslyn.Test.Utilities.Desktop
{
public static class CLRHelpers
{
private static readonly Guid s_clsIdClrRuntimeHost = new Guid("90F1A06E-7712-4762-86B5-7A5EBA6BDB02");
private static readonly Guid s_clsIdCorMetaDataDispenser = new Guid("E5CB7A31-7512-11d2-89CE-0080C792E5D8");
public static event ResolveEventHandler ReflectionOnlyAssemblyResolve;
static CLRHelpers()
{
// Work around CLR bug:
// PE Verifier adds a handler to ReflectionOnlyAssemblyResolve event in AppDomain.EnableResolveAssembliesForIntrospection
// (called from ValidateWorker in Validator.cpp) in which it directly calls Assembly.ReflectionOnlyLoad.
// If that happens before we get a chance to resolve the assembly the resolution fails.
//
// The handlers are invoked in the order they were added until one of them returns non-null assembly.
// Therefore once we call Validate we can't add any more handlers -- they would all follow the CLR one, which fails.
//
// As A workaround we add a single forwarding handler before any calls to Validate and then subscribe all of our true handlers
// to this event.
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += ReflectionOnlyAssemblyResolveHandler;
}
private static Assembly ReflectionOnlyAssemblyResolveHandler(object sender, ResolveEventArgs args)
{
var handler = ReflectionOnlyAssemblyResolve;
if (handler != null)
{
return handler(sender, args);
}
return null;
}
public static object GetRuntimeInterfaceAsObject(Guid clsid, Guid riid)
{
// This API isn't available on Mono hence we must use reflection to access it.
Debug.Assert(!MonoHelpers.IsRunningOnMono());
var getRuntimeInterfaceAsObject = typeof(RuntimeEnvironment).GetMethod("GetRuntimeInterfaceAsObject", BindingFlags.Public | BindingFlags.Static);
return getRuntimeInterfaceAsObject.Invoke(null, new object[] { clsid, riid });
}
/// <summary>
/// Verifies the specified image. Subscribe to <see cref="ReflectionOnlyAssemblyResolve"/> to provide a loader for dependent assemblies.
/// </summary>
public static string[] PeVerify(byte[] peImage, bool metadataOnly)
{
// fileName must be null, otherwise AssemblyResolve events won't fire
return PeVerify(peImage, AppDomain.CurrentDomain.Id, assemblyPath: null, metadataOnly: metadataOnly);
}
/// <summary>
/// Verifies the specified file. All dependencies must be on disk next to the file.
/// </summary>
public static string[] PeVerify(string filePath, bool metadataOnly)
{
return PeVerify(File.ReadAllBytes(filePath), AppDomain.CurrentDomain.Id, filePath, metadataOnly: metadataOnly);
}
private static readonly object s_guard = new object();
private static string[] PeVerify(byte[] peImage, int domainId, string assemblyPath, bool metadataOnly)
{
if (MonoHelpers.IsRunningOnMono())
{
// PEverify is currently unsupported on Mono hence return an empty
// set of messages
return new string[0];
}
lock (s_guard)
{
GCHandle pinned = GCHandle.Alloc(peImage, GCHandleType.Pinned);
try
{
IntPtr buffer = pinned.AddrOfPinnedObject();
ICLRValidator validator = (ICLRValidator)GetRuntimeInterfaceAsObject(s_clsIdClrRuntimeHost, typeof(ICLRRuntimeHost).GUID);
ValidationErrorHandler errorHandler = new ValidationErrorHandler(validator);
IMetaDataDispenser dispenser = (IMetaDataDispenser)GetRuntimeInterfaceAsObject(s_clsIdCorMetaDataDispenser, typeof(IMetaDataDispenser).GUID);
// the buffer needs to be pinned during validation
Guid riid = typeof(IMetaDataImport).GUID;
object metaDataImport = null;
if (assemblyPath != null)
{
dispenser.OpenScope(assemblyPath, CorOpenFlags.ofRead, ref riid, out metaDataImport);
}
else
{
dispenser.OpenScopeOnMemory(buffer, (uint)peImage.Length, CorOpenFlags.ofRead, ref riid, out metaDataImport);
}
IMetaDataValidate metaDataValidate = (IMetaDataValidate)metaDataImport;
metaDataValidate.ValidatorInit(CorValidatorModuleType.ValidatorModuleTypePE, errorHandler);
metaDataValidate.ValidateMetaData();
if (!metadataOnly)
{
validator.Validate(errorHandler, (uint)domainId, ValidatorFlags.VALIDATOR_EXTRA_VERBOSE,
ulMaxError: 10, token: 0, fileName: assemblyPath, pe: buffer, ulSize: (uint)peImage.Length);
}
return errorHandler.GetOutput();
}
finally
{
pinned.Free();
}
}
}
private class ValidationErrorHandler : IVEHandler
{
private readonly ICLRValidator _validator;
private readonly List<string> _output;
private const int MessageLength = 256;
public ValidationErrorHandler(ICLRValidator validator)
{
_validator = validator;
_output = new List<string>();
}
public void SetReporterFtn(long lFnPtr)
{
throw new NotImplementedException();
}
public void VEHandler(int VECode, tag_VerError Context, Array psa)
{
StringBuilder sb = new StringBuilder(MessageLength);
string message = null;
if (Context.Flags == (uint)ValidatorFlags.VALIDATOR_CHECK_PEFORMAT_ONLY)
{
GetErrorResourceString(VECode, sb);
string formatString = ReplaceFormatItems(sb.ToString(), "%08x", ":x8");
formatString = ReplaceFormatItems(formatString, "%d", "");
if (psa == null)
{
psa = new object[0];
}
message = string.Format(formatString, (object[])psa);
}
else
{
_validator.FormatEventInfo(VECode, Context, sb, (uint)MessageLength - 1, psa);
message = sb.ToString();
}
// retail version of peverify.exe filters out CLS warnings...
if (!message.Contains("[CLS]"))
{
_output.Add(message);
}
}
public string[] GetOutput()
{
return _output.ToArray();
}
private static readonly string s_resourceFilePath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "mscorrc.dll");
private const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
private static readonly IntPtr s_hMod = LoadLibraryEx(s_resourceFilePath, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE);
private static void GetErrorResourceString(int code, StringBuilder message)
{
LoadString(s_hMod, (uint)(code & 0x0000FFFF), message, MessageLength - 1);
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
private static string ReplaceFormatItems(string input, string oldFormat, string newFormat)
{
// not foolproof/efficient, but easy to write/understand...
var parts = input.Replace(oldFormat, "|").Split('|');
var formatString = new StringBuilder();
for (int i = 0; i < parts.Length; i++)
{
formatString.Append(parts[i]);
if (i < (parts.Length - 1))
{
formatString.Append('{');
formatString.Append(i);
formatString.Append(newFormat);
formatString.Append('}');
}
}
return formatString.ToString();
}
}
}
namespace ComTypes
{
[ComImport, CoClass(typeof(object)), Guid("90F1A06C-7712-4762-86B5-7A5EBA6BDB02"), TypeIdentifier]
public interface CLRRuntimeHost : ICLRRuntimeHost
{
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("90F1A06C-7712-4762-86B5-7A5EBA6BDB02"), TypeIdentifier]
public interface ICLRRuntimeHost
{
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("63DF8730-DC81-4062-84A2-1FF943F59FDD"), TypeIdentifier]
public interface ICLRValidator
{
void Validate(
[In, MarshalAs(UnmanagedType.Interface)] IVEHandler veh,
[In] uint ulAppDomainId,
[In] ValidatorFlags ulFlags,
[In] uint ulMaxError,
[In] uint token,
[In, MarshalAs(UnmanagedType.LPWStr)] string fileName,
[In] IntPtr pe,
[In] uint ulSize);
void FormatEventInfo(
[In, MarshalAs(UnmanagedType.Error)] int hVECode,
[In] tag_VerError Context,
[In, Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder msg,
[In] uint ulMaxLength,
[In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array psa);
}
[ComImport, Guid("856CA1B2-7DAB-11D3-ACEC-00C04F86C309"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), TypeIdentifier]
public interface IVEHandler
{
void VEHandler([In, MarshalAs(UnmanagedType.Error)] int VECode, [In] tag_VerError Context, [In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array psa);
void SetReporterFtn([In] long lFnPtr);
}
[ComImport, Guid("809C652E-7396-11D2-9771-00A0C9B4D50C"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), TypeIdentifier]
public interface IMetaDataDispenser
{
void DefineScope(
[In] ref Guid rclsid,
[In] uint dwCreateFlags,
[In] ref Guid riid,
[Out, MarshalAs(UnmanagedType.IUnknown)] out object ppIUnk);
void OpenScope(
[In, MarshalAs(UnmanagedType.LPWStr)] string szScope,
[In] CorOpenFlags dwOpenFlags,
[In] ref Guid riid,
[Out, MarshalAs(UnmanagedType.IUnknown)] out object ppIUnk);
void OpenScopeOnMemory(
[In] IntPtr pData,
[In] uint cbData,
[In] CorOpenFlags dwOpenFlags,
[In] ref Guid riid,
[Out, MarshalAs(UnmanagedType.IUnknown)] out object ppIUnk);
}
[ComImport, Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), TypeIdentifier]
public interface IMetaDataImport
{
}
[ComImport, Guid("4709C9C6-81FF-11D3-9FC7-00C04F79A0A3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), TypeIdentifier]
public interface IMetaDataValidate
{
void ValidatorInit([In] CorValidatorModuleType dwModuleType, [In, MarshalAs(UnmanagedType.IUnknown)] object pUnk);
void ValidateMetaData();
}
[StructLayout(LayoutKind.Sequential, Pack = 4), TypeIdentifier("5477469e-83b1-11d2-8b49-00a0c9b7c9c4", "mscoree.tag_VerError")]
public struct tag_VerError
{
public uint Flags;
public uint opcode;
public uint uOffset;
public uint Token;
public uint item1_flags;
public IntPtr item1_data;
public uint item2_flags;
public IntPtr item2_data;
}
public enum ValidatorFlags : uint
{
VALIDATOR_EXTRA_VERBOSE = 0x00000001,
VALIDATOR_SHOW_SOURCE_LINES = 0x00000002,
VALIDATOR_CHECK_ILONLY = 0x00000004,
VALIDATOR_CHECK_PEFORMAT_ONLY = 0x00000008,
VALIDATOR_NOCHECK_PEFORMAT = 0x00000010
};
public enum CorValidatorModuleType : uint
{
ValidatorModuleTypeInvalid = 0x00000000,
ValidatorModuleTypeMin = 0x00000001,
ValidatorModuleTypePE = 0x00000001,
ValidatorModuleTypeObj = 0x00000002,
ValidatorModuleTypeEnc = 0x00000003,
ValidatorModuleTypeIncr = 0x00000004,
ValidatorModuleTypeMax = 0x00000004
};
public enum CorOpenFlags : uint
{
ofRead = 0x00000000,
ofWrite = 0x00000001,
ofReadWriteMask = 0x00000001,
ofCopyMemory = 0x00000002,
ofCacheImage = 0x00000004,
ofManifestMetadata = 0x00000008,
ofReadOnly = 0x00000010,
ofTakeOwnership = 0x00000020,
ofNoTypeLib = 0x00000080,
ofReserved1 = 0x00000100,
ofReserved2 = 0x00000200,
ofReserved = 0xffffff40,
};
}
}
| |
using System;
namespace Rawr.Elemental.Spells
{
public abstract class Spell
{
protected float baseMinDamage = 0f;
protected float baseMaxDamage = 0f;
protected float baseCastTime = 0f;
protected float castTime = 0f;
protected float periodicTick = 0f;
protected float periodicTicks = 0f;
protected float periodicTickTime = 3f;
protected float manaCost = 0f;
protected float gcd = 1.5f;
protected float crit = 0f;
protected float critModifier = 1f;
protected float cooldown = 0f;
protected float missChance = .17f;
protected float totalCoef = 1f;
protected float directCoefBonus = 0f;
protected float baseCoef = 1f;
protected float spCoef = 0f;
protected float dotBaseCoef = 1f;
protected float dotSpCoef = 0f;
protected float dotCanCrit = 0f;
protected float dotCritModifier = 1f;
protected float spellPower = 0f;
protected float latencyGcd = .15f;
protected float latencyCast = .075f;
/// <summary>
/// This Constructor calls SetBaseValues.
/// </summary>
public Spell()
{
SetBaseValues();
}
protected virtual void SetBaseValues()
{
baseMinDamage = 0f;
baseMaxDamage = 0f;
baseCastTime = 0f;
castTime = 0f;
periodicTick = 0f;
periodicTicks = 0f;
periodicTickTime = 3f;
manaCost = 0f;
gcd = 1.5f;
crit = 0f;
critModifier = 1f;
cooldown = 0f;
missChance = .17f;
totalCoef = 1f;
baseCoef = 1f;
spCoef = 0f;
dotBaseCoef = 1f;
dotSpCoef = 0f;
dotCritModifier = 1f;
directCoefBonus = 0f;
dotCanCrit = 0f;
spellPower = 0f;
}
public void Update(ISpellArgs args)
{
SetBaseValues();
Initialize(args);
}
protected string shortName = "Spell";
protected static void add(Spell sp1, Spell sp2, Spell nS)
{
nS.baseMinDamage = (sp1.baseMinDamage + sp2.baseMaxDamage);
nS.baseMaxDamage = (sp1.baseMaxDamage + sp2.baseMaxDamage);
nS.castTime = (sp1.castTime + sp2.castTime);
nS.periodicTick = (sp1.periodicTick + sp2.periodicTick);
nS.periodicTicks = (sp1.periodicTicks + sp2.periodicTicks);
nS.periodicTickTime = (sp1.periodicTickTime + sp2.periodicTickTime);
nS.manaCost = (sp1.manaCost + sp2.manaCost);
nS.gcd = (sp1.gcd + sp2.gcd);
nS.crit = (sp1.crit + sp2.crit);
nS.critModifier = (sp1.critModifier + sp2.critModifier);
nS.cooldown = (sp1.cooldown + sp2.cooldown);
nS.missChance = (sp1.missChance + sp2.missChance);
nS.totalCoef = (sp1.totalCoef + sp2.totalCoef);
nS.directCoefBonus = (sp1.directCoefBonus + sp2.directCoefBonus);
nS.baseCoef = (sp1.baseCoef + sp2.baseCoef);
nS.spCoef = (sp1.spCoef + sp2.spCoef);
nS.dotBaseCoef = (sp1.dotBaseCoef + sp2.dotBaseCoef);
nS.dotSpCoef = (sp1.dotSpCoef + sp2.dotSpCoef);
nS.dotCritModifier = (sp1.dotCritModifier + sp2.dotCritModifier);
nS.spellPower = (sp1.spellPower + sp2.spellPower);
}
protected static void multiply(Spell sp1, float c, Spell nS)
{
nS.baseMinDamage = sp1.baseMinDamage * c;
nS.baseMaxDamage = sp1.baseMaxDamage * c;
nS.castTime = sp1.castTime * c;
nS.periodicTick = sp1.periodicTick * c;
nS.periodicTicks = sp1.periodicTicks * c;
nS.periodicTickTime = sp1.periodicTickTime * c;
nS.manaCost = sp1.manaCost * c;
nS.gcd = sp1.gcd * c;
nS.crit = sp1.crit * c;
nS.critModifier = sp1.critModifier * c;
nS.cooldown = sp1.cooldown * c;
nS.missChance = sp1.missChance * c;
nS.totalCoef = sp1.totalCoef * c;
nS.baseCoef = sp1.baseCoef * c;
nS.spCoef = sp1.spCoef * c;
nS.dotBaseCoef = sp1.dotBaseCoef * c;
nS.dotSpCoef = sp1.dotSpCoef * c;
nS.directCoefBonus = sp1.directCoefBonus * c;
nS.dotCritModifier = sp1.dotCritModifier * c;
nS.spellPower = sp1.spellPower * c;
}
public virtual float MinHit
{ get { return (totalCoef + directCoefBonus) * (baseMinDamage * baseCoef + spellPower * spCoef); } }
public float MinCrit
{ get { return MinHit * (1 + critModifier); } }
public virtual float MaxHit
{ get { return (totalCoef + directCoefBonus) * (baseMaxDamage * baseCoef + spellPower * spCoef); } }
public float MaxCrit
{ get { return MaxHit * (1 + critModifier); } }
public float AvgHit
{ get { return (MinHit + MaxHit) / 2; } }
public float AvgCrit
{ get { return (MinCrit + MaxCrit) / 2; } }
public float AvgDamage
{ get { return (1f - CritChance) * AvgHit + CritChance * AvgCrit; } }
public float MinDamage
{ get { return (1f - CritChance) * MinHit + CritChance * MinCrit; } }
public float MaxDamage
{ get { return (1f - CritChance) * MaxHit + CritChance * MaxCrit; } }
/// <summary>
/// This is to ensure that the constraints on the GCD are met on abilities that have Gcd
/// </summary>
public float Gcd
{ get { return (gcd >= 1 ? gcd : 1); } }
/// <summary>
/// The effective Cast Time. Taking GCD and latency into account.
/// </summary>
public float CastTime
{
get
{
if (gcd == 0 && castTime == 0)
return 0;
if (castTime > Gcd)
return castTime + Latency;
else
return Gcd + Latency;
}
}
/// <summary>
/// The effective Latency of this spell effecting the start cast time of the next one.
/// </summary>
public float Latency
{
get
{
if (gcd == 0 && castTime == 0)
return 0;
if (castTime >= gcd)
return latencyCast;
else
return latencyGcd;
}
}
public float BaseCastTime
{
get
{
return Math.Max(baseCastTime, 1.5f);
}
}
public float CastTimeWithoutGCD
{ get { return castTime; } }
public float CritChance
{ get { return Math.Min(1f, crit); } }
/// <summary>
/// Crit chance for all kind of proc triggers (e.g. Clearcasting). This exists seperately because of Lightning Overload.
/// </summary>
public virtual float CCCritChance
{ get { return CritChance; } }
public float MissChance
{ get { return missChance; } }
public float HitChance
{ get { return 1f - missChance; } }
public float DamageFromSpellPower
{ get { return spellPower * spCoef * totalCoef; } }
public float PeriodicTick
{ get { return totalCoef * (periodicTick * dotBaseCoef + spellPower * dotSpCoef) * (1 + dotCanCrit * dotCritModifier * CritChance); } }
public float PeriodicTicks
{
get { return periodicTicks; }
set
{
periodicTicks = value;
if (periodicTicks < 0)
periodicTicks = 0;
}
}
public float PeriodicDamage()
{
return PeriodicDamage(Duration);
}
public float PeriodicDamage(float duration)
{
if (PeriodicTickTime <= 0 || duration <= 0)
return 0;
int effectiveTicks = (int)Math.Floor(Math.Min(duration, Duration) / PeriodicTickTime);
return PeriodicTick * effectiveTicks;
}
public virtual float TotalDamage
{ get { return AvgDamage + PeriodicDamage(); } }
public virtual float DirectDpS
{ get { return AvgDamage / CastTime; } }
public float PeriodicDpS
{ get { return PeriodicTick / periodicTickTime; } }
public float PeriodicTickTime
{ get { return periodicTickTime; } }
public float DpM
{ get { return TotalDamage / manaCost; } }
public float DpCT
{ get { return TotalDamage / CastTime; } }
public float DpPR
{ get { return TotalDamage / PeriodicRefreshTime; } }
public float DpCDR
{ get { return TotalDamage / CDRefreshTime; } }
public float CTpDuration
{ get { return Duration > 0 ? CastTime / Duration : 1f; } }
public float Duration
{ get { return periodicTicks * periodicTickTime; } }
public float Cooldown
{ get { return cooldown; } }
public float PeriodicRefreshTime
{ get { return (Duration > CDRefreshTime ? Duration : CDRefreshTime); } }
public float CDRefreshTime
{ get { return cooldown > CastTime ? cooldown + castTime : CastTime; } }
//{ get { return cooldown + CastTime; } }
public float ManaCost
{ get { return manaCost; } }
public virtual void Initialize(ISpellArgs args)
{
float Speed = (1f + args.Stats.SpellHaste) * (1f + StatConversion.GetSpellHasteFromRating(args.Stats.HasteRating));
gcd = (float)Math.Round(gcd / Speed, 4);
castTime = (float)Math.Round(castTime / Speed, 4);
latencyGcd = args.LatencyGCD;
latencyCast = args.LatencyCast;
critModifier += .2f * args.Talents.ElementalFury;
critModifier *= (float)Math.Round(1.5f * (1f + args.Stats.BonusSpellCritMultiplier) - 1f, 6);
dotCritModifier += .2f * args.Talents.ElementalFury;
dotCritModifier *= (float)Math.Round(1.5f * (1f + args.Stats.BonusSpellCritMultiplier) - 1f, 6);
//critModifier += 1f;
spellPower += args.Stats.SpellPower;
crit += args.Stats.SpellCrit;
missChance -= args.Stats.SpellHit;
totalCoef *= 1 + args.Stats.BonusDamageMultiplier; //ret + bm buff
if (missChance < 0) missChance = 0;
manaCost = (float)Math.Floor(manaCost);
//base resistance by level
totalCoef *= 1f - StatConversion.GetAverageResistance(80, 83, 0, 0);
}
public void ApplyDotHaste(ISpellArgs args)
{
float Speed = (1f + args.Stats.SpellHaste) * (1f + StatConversion.GetSpellHasteFromRating(args.Stats.HasteRating));
periodicTickTime = (float)Math.Round(periodicTickTime / Speed, 4);
}
public void ApplyEM(float modifier)
{
throw new NotImplementedException();
}
public virtual Spell Clone()
{
return (Spell)this.MemberwiseClone();
}
public override string ToString()
{
return shortName;
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using log4net;
using NDesk.Options;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
/// <summary>
/// This module loads and saves OpenSimulator inventory archives
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InventoryArchiverModule")]
public class InventoryArchiverModule : ISharedRegionModule, IInventoryArchiverModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <value>
/// Enable or disable checking whether the iar user is actually logged in
/// </value>
// public bool DisablePresenceChecks { get; set; }
public event InventoryArchiveSaved OnInventoryArchiveSaved;
public event InventoryArchiveLoaded OnInventoryArchiveLoaded;
/// <summary>
/// The file to load and save inventory if no filename has been specified
/// </summary>
protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar";
/// <value>
/// Pending save and load completions initiated from the console
/// </value>
protected List<UUID> m_pendingConsoleTasks = new List<UUID>();
/// <value>
/// All scenes that this module knows about
/// </value>
private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
private Scene m_aScene;
private IUserAccountService m_UserAccountService;
protected IUserAccountService UserAccountService
{
get
{
if (m_UserAccountService == null)
// What a strange thing to do...
foreach (Scene s in m_scenes.Values)
{
m_UserAccountService = s.RequestModuleInterface<IUserAccountService>();
break;
}
return m_UserAccountService;
}
}
public InventoryArchiverModule() {}
// public InventoryArchiverModule(bool disablePresenceChecks)
// {
// DisablePresenceChecks = disablePresenceChecks;
// }
#region ISharedRegionModule
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
if (m_scenes.Count == 0)
{
scene.RegisterModuleInterface<IInventoryArchiverModule>(this);
OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted;
OnInventoryArchiveLoaded += LoadInvConsoleCommandCompleted;
scene.AddCommand(
"Archiving", this, "load iar",
"load iar [-m|--merge] <first> <last> <inventory path> <password> [<IAR path>]",
"Load user inventory archive (IAR).",
"-m|--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones"
+ "<first> is user's first name." + Environment.NewLine
+ "<last> is user's last name." + Environment.NewLine
+ "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine
+ "<password> is the user's password." + Environment.NewLine
+ "<IAR path> is the filesystem path or URI from which to load the IAR."
+ string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME),
HandleLoadInvConsoleCommand);
scene.AddCommand(
"Archiving", this, "save iar",
"save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]",
"Save user inventory archive (IAR).",
"<first> is the user's first name.\n"
+ "<last> is the user's last name.\n"
+ "<inventory path> is the path inside the user's inventory for the folder/item to be saved.\n"
+ "<IAR path> is the filesystem path at which to save the IAR."
+ string.Format(" If this is not given then the filename {0} in the current directory is used.\n", DEFAULT_INV_BACKUP_FILENAME)
+ "-h|--home=<url> adds the url of the profile service to the saved user information.\n"
+ "-c|--creators preserves information about foreign creators.\n"
+ "-e|--exclude=<name/uuid> don't save the inventory item in archive" + Environment.NewLine
+ "-f|--excludefolder=<folder/uuid> don't save contents of the folder in archive" + Environment.NewLine
+ "-v|--verbose extra debug messages.\n"
+ "--noassets stops assets being saved to the IAR."
+ "--perm=<permissions> stops items with insufficient permissions from being saved to the IAR.\n"
+ " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer, \"M\" = Modify.\n",
HandleSaveInvConsoleCommand);
m_aScene = scene;
}
m_scenes[scene.RegionInfo.RegionID] = scene;
}
public void RemoveRegion(Scene scene)
{
}
public void Close() {}
public void RegionLoaded(Scene scene)
{
}
public void PostInitialise()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name { get { return "Inventory Archiver Module"; } }
#endregion
/// <summary>
/// Trigger the inventory archive saved event.
/// </summary>
protected internal void TriggerInventoryArchiveSaved(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
Exception reportedException, int SaveCount, int FilterCount)
{
InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved;
if (handlerInventoryArchiveSaved != null)
handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException, SaveCount , FilterCount);
}
/// <summary>
/// Trigger the inventory archive loaded event.
/// </summary>
protected internal void TriggerInventoryArchiveLoaded(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream loadStream,
Exception reportedException, int LoadCount)
{
InventoryArchiveLoaded handlerInventoryArchiveLoaded = OnInventoryArchiveLoaded;
if (handlerInventoryArchiveLoaded != null)
handlerInventoryArchiveLoaded(id, succeeded, userInfo, invPath, loadStream, reportedException, LoadCount);
}
public bool ArchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, Stream saveStream)
{
return ArchiveInventory(id, firstName, lastName, invPath, pass, saveStream, new Dictionary<string, object>());
}
public bool ArchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, Stream saveStream,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
try
{
new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(options, UserAccountService);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
public bool ArchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, string savePath,
Dictionary<string, object> options)
{
// if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, savePath))
// return false;
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
try
{
new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(options, UserAccountService);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
public bool DearchiveInventory(UUID id, string firstName, string lastName, string invPath, string pass, Stream loadStream)
{
return DearchiveInventory(id, firstName, lastName, invPath, pass, loadStream, new Dictionary<string, object>());
}
public bool DearchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, Stream loadStream,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
InventoryArchiveReadRequest request;
bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false);
try
{
request = new InventoryArchiveReadRequest(id, this, m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadStream, merge);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
UpdateClientWithLoadedNodes(userInfo, request.Execute());
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
else
m_log.ErrorFormat("[INVENTORY ARCHIVER]: User {0} {1} not found",
firstName, lastName);
}
return false;
}
public bool DearchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, string loadPath,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
InventoryArchiveReadRequest request;
bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false);
try
{
request = new InventoryArchiveReadRequest(id, this, m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadPath, merge);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
UpdateClientWithLoadedNodes(userInfo, request.Execute());
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
/// <summary>
/// Load inventory from an inventory file archive
/// </summary>
/// <param name="cmdparams"></param>
protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams)
{
try
{
UUID id = UUID.Random();
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet optionSet = new OptionSet().Add("m|merge", delegate (string v) { options["merge"] = v != null; });
List<string> mainParams = optionSet.Parse(cmdparams);
if (mainParams.Count < 6)
{
m_log.Error(
"[INVENTORY ARCHIVER]: usage is load iar [-m|--merge] <first name> <last name> <inventory path> <user password> [<load file path>]");
return;
}
string firstName = mainParams[2];
string lastName = mainParams[3];
string invPath = mainParams[4];
string pass = mainParams[5];
string loadPath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}",
loadPath, invPath, firstName, lastName);
lock (m_pendingConsoleTasks)
m_pendingConsoleTasks.Add(id);
DearchiveInventory(id, firstName, lastName, invPath, pass, loadPath, options);
}
catch (InventoryArchiverException e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
}
}
/// <summary>
/// Save inventory to a file archive
/// </summary>
/// <param name="cmdparams"></param>
protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams)
{
UUID id = UUID.Random();
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet ops = new OptionSet();
//ops.Add("v|version=", delegate(string v) { options["version"] = v; });
ops.Add("h|home=", delegate(string v) { options["home"] = v; });
ops.Add("v|verbose", delegate(string v) { options["verbose"] = v; });
ops.Add("c|creators", delegate(string v) { options["creators"] = v; });
ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; });
ops.Add("e|exclude=", delegate(string v)
{
if (!options.ContainsKey("exclude"))
options["exclude"] = new List<String>();
((List<String>)options["exclude"]).Add(v);
});
ops.Add("f|excludefolder=", delegate(string v)
{
if (!options.ContainsKey("excludefolders"))
options["excludefolders"] = new List<String>();
((List<String>)options["excludefolders"]).Add(v);
});
ops.Add("perm=", delegate(string v) { options["checkPermissions"] = v; });
List<string> mainParams = ops.Parse(cmdparams);
try
{
if (mainParams.Count < 6)
{
m_log.Error(
"[INVENTORY ARCHIVER]: save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]");
return;
}
if (options.ContainsKey("home"))
m_log.WarnFormat("[INVENTORY ARCHIVER]: Please be aware that inventory archives with creator information are not compatible with OpenSim 0.7.0.2 and earlier. Do not use the -home option if you want to produce a compatible IAR");
string firstName = mainParams[2];
string lastName = mainParams[3];
string invPath = mainParams[4];
string pass = mainParams[5];
string savePath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}",
savePath, invPath, firstName, lastName);
lock (m_pendingConsoleTasks)
m_pendingConsoleTasks.Add(id);
ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, options);
}
catch (InventoryArchiverException e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
}
}
private void SaveInvConsoleCommandCompleted(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
Exception reportedException, int SaveCount, int FilterCount)
{
lock (m_pendingConsoleTasks)
{
if (m_pendingConsoleTasks.Contains(id))
m_pendingConsoleTasks.Remove(id);
else
return;
}
if (succeeded)
{
// Report success and include item count and filter count (Skipped items due to --perm or --exclude switches)
if(FilterCount == 0)
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive with {0} items for {1} {2}", SaveCount, userInfo.FirstName, userInfo.LastName);
else
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive with {0} items for {1} {2}. Skipped {3} items due to exclude and/or perm switches", SaveCount, userInfo.FirstName, userInfo.LastName, FilterCount);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}",
userInfo.FirstName, userInfo.LastName, reportedException.Message);
}
}
private void LoadInvConsoleCommandCompleted(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream loadStream,
Exception reportedException, int LoadCount)
{
lock (m_pendingConsoleTasks)
{
if (m_pendingConsoleTasks.Contains(id))
m_pendingConsoleTasks.Remove(id);
else
return;
}
if (succeeded)
{
m_log.InfoFormat("[INVENTORY ARCHIVER]: Loaded {0} items from archive {1} for {2} {3}", LoadCount, invPath, userInfo.FirstName, userInfo.LastName);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Archive load for {0} {1} failed - {2}",
userInfo.FirstName, userInfo.LastName, reportedException.Message);
}
}
/// <summary>
/// Get user information for the given name.
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="pass">User password</param>
/// <returns></returns>
protected UserAccount GetUserInfo(string firstName, string lastName, string pass)
{
UserAccount account
= m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName);
if (null == account)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}",
firstName, lastName);
return null;
}
return account;
/*
try
{
string encpass = Util.Md5Hash(pass);
if (m_aScene.AuthenticationService.Authenticate(account.PrincipalID, encpass, 1) != string.Empty)
{
return account;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.",
firstName, lastName);
return null;
}
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e);
return null;
}
*/
}
/// <summary>
/// Notify the client of loaded nodes if they are logged in
/// </summary>
/// <param name="loadedNodes">Can be empty. In which case, nothing happens</param>
private void UpdateClientWithLoadedNodes(UserAccount userInfo, HashSet<InventoryNodeBase> loadedNodes)
{
if (loadedNodes.Count == 0)
return;
foreach (Scene scene in m_scenes.Values)
{
ScenePresence user = scene.GetScenePresence(userInfo.PrincipalID);
if (user != null && !user.IsChildAgent)
{
foreach (InventoryNodeBase node in loadedNodes)
{
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}",
// user.Name, node.Name);
user.ControllingClient.SendBulkUpdateInventory(node);
}
break;
}
}
}
// /// <summary>
// /// Check if the given user is present in any of the scenes.
// /// </summary>
// /// <param name="userId">The user to check</param>
// /// <returns>true if the user is in any of the scenes, false otherwise</returns>
// protected bool CheckPresence(UUID userId)
// {
// if (DisablePresenceChecks)
// return true;
//
// foreach (Scene scene in m_scenes.Values)
// {
// ScenePresence p;
// if ((p = scene.GetScenePresence(userId)) != null)
// {
// p.ControllingClient.SendAgentAlertMessage("Inventory operation has been started", false);
// return true;
// }
// }
//
// return false;
// }
}
}
| |
// 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 Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.Formatting.Indentation;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.Formatting.Indentation
{
internal partial class CSharpIndentationService
{
internal class Indenter : AbstractIndenter
{
public Indenter(Document document, IEnumerable<IFormattingRule> rules, OptionSet optionSet, ITextSnapshotLine line, CancellationToken cancellationToken) :
base(document, rules, optionSet, line, cancellationToken)
{
}
public override IndentationResult? GetDesiredIndentation()
{
var indentStyle = OptionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp);
if (indentStyle == FormattingOptions.IndentStyle.None)
{
return null;
}
// find previous line that is not blank
var previousLine = GetPreviousNonBlankOrPreprocessorLine();
// it is beginning of the file, there is no previous line exists.
// in that case, indentation 0 is our base indentation.
if (previousLine == null)
{
return IndentFromStartOfLine(0);
}
// okay, now see whether previous line has anything meaningful
var lastNonWhitespacePosition = previousLine.GetLastNonWhitespacePosition();
if (!lastNonWhitespacePosition.HasValue)
{
return null;
}
// there is known parameter list "," parse bug. if previous token is "," from parameter list,
// FindToken will not be able to find them.
var token = Tree.GetRoot(CancellationToken).FindToken(lastNonWhitespacePosition.Value);
if (token.IsKind(SyntaxKind.None) || indentStyle == FormattingOptions.IndentStyle.Block)
{
return GetIndentationOfLine(previousLine);
}
// okay, now check whether the text we found is trivia or actual token.
if (token.Span.Contains(lastNonWhitespacePosition.Value))
{
// okay, it is a token case, do special work based on type of last token on previous line
return GetIndentationBasedOnToken(token);
}
else
{
// there must be trivia that contains or touch this position
Contract.Assert(token.FullSpan.Contains(lastNonWhitespacePosition.Value));
// okay, now check whether the trivia is at the beginning of the line
var firstNonWhitespacePosition = previousLine.GetFirstNonWhitespacePosition();
if (!firstNonWhitespacePosition.HasValue)
{
return IndentFromStartOfLine(0);
}
var trivia = Tree.GetRoot(CancellationToken).FindTrivia(firstNonWhitespacePosition.Value, findInsideTrivia: true);
if (trivia.Kind() == SyntaxKind.None || this.LineToBeIndented.LineNumber > previousLine.LineNumber + 1)
{
// If the token belongs to the next statement and is also the first token of the statement, then it means the user wants
// to start type a new statement. So get indentation from the start of the line but not based on the token.
// Case:
// static void Main(string[] args)
// {
// // A
// // B
//
// $$
// return;
// }
var containingStatement = token.GetAncestor<StatementSyntax>();
if (containingStatement != null && containingStatement.GetFirstToken() == token)
{
var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start);
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken));
}
// If the token previous of the base token happens to be a Comma from a separation list then we need to handle it different
// Case:
// var s = new List<string>
// {
// """",
// """",/*sdfsdfsdfsdf*/
// // dfsdfsdfsdfsdf
//
// $$
// };
var previousToken = token.GetPreviousToken();
if (previousToken.IsKind(SyntaxKind.CommaToken))
{
return GetIndentationFromCommaSeparatedList(previousToken);
}
else if (!previousToken.IsKind(SyntaxKind.None))
{
// okay, beginning of the line is not trivia, use the last token on the line as base token
return GetIndentationBasedOnToken(token);
}
}
// this case we will keep the indentation of this trivia line
// this trivia can't be preprocessor by the way.
return GetIndentationOfLine(previousLine);
}
}
private IndentationResult? GetIndentationBasedOnToken(SyntaxToken token)
{
Contract.ThrowIfNull(LineToBeIndented);
Contract.ThrowIfNull(Tree);
Contract.ThrowIfTrue(token.Kind() == SyntaxKind.None);
// special cases
// case 1: token belongs to verbatim token literal
// case 2: $@"$${0}"
// case 3: $@"Comment$$ inbetween{0}"
// case 4: $@"{0}$$"
if (token.IsVerbatimStringLiteral() ||
token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) ||
token.IsKind(SyntaxKind.InterpolatedStringTextToken) ||
(token.IsKind(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Interpolation)))
{
return IndentFromStartOfLine(0);
}
// if previous statement belong to labeled statement, don't follow label's indentation
// but its previous one.
if (token.Parent is LabeledStatementSyntax || token.IsLastTokenInLabelStatement())
{
token = token.GetAncestor<LabeledStatementSyntax>().GetFirstToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true);
}
var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start);
// first check operation service to see whether we can determine indentation from it
var indentation = Finder.FromIndentBlockOperations(Tree, token, position, CancellationToken);
if (indentation.HasValue)
{
return IndentFromStartOfLine(indentation.Value);
}
var alignmentTokenIndentation = Finder.FromAlignTokensOperations(Tree, token);
if (alignmentTokenIndentation.HasValue)
{
return IndentFromStartOfLine(alignmentTokenIndentation.Value);
}
// if we couldn't determine indentation from the service, use heuristic to find indentation.
var snapshot = LineToBeIndented.Snapshot;
// If this is the last token of an embedded statement, walk up to the top-most parenting embedded
// statement owner and use its indentation.
//
// cases:
// if (true)
// if (false)
// Foo();
//
// if (true)
// { }
if (token.IsSemicolonOfEmbeddedStatement() ||
token.IsCloseBraceOfEmbeddedBlock())
{
Contract.Requires(
token.Parent != null &&
(token.Parent.Parent is StatementSyntax || token.Parent.Parent is ElseClauseSyntax));
var embeddedStatementOwner = token.Parent.Parent;
while (embeddedStatementOwner.IsEmbeddedStatement())
{
embeddedStatementOwner = embeddedStatementOwner.Parent;
}
return GetIndentationOfLine(snapshot.GetLineFromPosition(embeddedStatementOwner.GetFirstToken(includeZeroWidth: true).SpanStart));
}
switch (token.Kind())
{
case SyntaxKind.SemicolonToken:
{
// special cases
if (token.IsSemicolonInForStatement())
{
return GetDefaultIndentationFromToken(token);
}
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken));
}
case SyntaxKind.CloseBraceToken:
{
if (token.Parent.IsKind(SyntaxKind.AccessorList) &&
token.Parent.Parent.IsKind(SyntaxKind.PropertyDeclaration))
{
if (token.GetNextToken().IsEqualsTokenInAutoPropertyInitializers())
{
return GetDefaultIndentationFromToken(token);
}
}
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken));
}
case SyntaxKind.OpenBraceToken:
{
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken));
}
case SyntaxKind.ColonToken:
{
var nonTerminalNode = token.Parent;
Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???");
if (nonTerminalNode is SwitchLabelSyntax)
{
return GetIndentationOfLine(snapshot.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart), OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language));
}
// default case
return GetDefaultIndentationFromToken(token);
}
case SyntaxKind.CloseBracketToken:
{
var nonTerminalNode = token.Parent;
Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???");
// if this is closing an attribute, we shouldn't indent.
if (nonTerminalNode is AttributeListSyntax)
{
return GetIndentationOfLine(snapshot.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart));
}
// default case
return GetDefaultIndentationFromToken(token);
}
case SyntaxKind.XmlTextLiteralToken:
{
return GetIndentationOfLine(snapshot.GetLineFromPosition(token.SpanStart));
}
case SyntaxKind.CommaToken:
{
return GetIndentationFromCommaSeparatedList(token);
}
default:
{
return GetDefaultIndentationFromToken(token);
}
}
}
private IndentationResult? GetIndentationFromCommaSeparatedList(SyntaxToken token)
{
var node = token.Parent;
var argument = node as BaseArgumentListSyntax;
if (argument != null)
{
return GetIndentationFromCommaSeparatedList(argument.Arguments, token);
}
var parameter = node as BaseParameterListSyntax;
if (parameter != null)
{
return GetIndentationFromCommaSeparatedList(parameter.Parameters, token);
}
var typeArgument = node as TypeArgumentListSyntax;
if (typeArgument != null)
{
return GetIndentationFromCommaSeparatedList(typeArgument.Arguments, token);
}
var typeParameter = node as TypeParameterListSyntax;
if (typeParameter != null)
{
return GetIndentationFromCommaSeparatedList(typeParameter.Parameters, token);
}
var enumDeclaration = node as EnumDeclarationSyntax;
if (enumDeclaration != null)
{
return GetIndentationFromCommaSeparatedList(enumDeclaration.Members, token);
}
var initializerSyntax = node as InitializerExpressionSyntax;
if (initializerSyntax != null)
{
return GetIndentationFromCommaSeparatedList(initializerSyntax.Expressions, token);
}
return GetDefaultIndentationFromToken(token);
}
private IndentationResult? GetIndentationFromCommaSeparatedList<T>(SeparatedSyntaxList<T> list, SyntaxToken token) where T : SyntaxNode
{
var index = list.GetWithSeparators().IndexOf(token);
if (index < 0)
{
return GetDefaultIndentationFromToken(token);
}
// find node that starts at the beginning of a line
var snapshot = LineToBeIndented.Snapshot;
for (int i = (index - 1) / 2; i >= 0; i--)
{
var node = list[i];
var firstToken = node.GetFirstToken(includeZeroWidth: true);
if (firstToken.IsFirstTokenOnLine(snapshot))
{
return GetIndentationOfLine(snapshot.GetLineFromPosition(firstToken.SpanStart));
}
}
// smart indenter has a special indent block rule for comma separated list, so don't
// need to add default additional space for multiline expressions
return GetDefaultIndentationFromTokenLine(token, additionalSpace: 0);
}
private IndentationResult? GetDefaultIndentationFromToken(SyntaxToken token)
{
if (IsPartOfQueryExpression(token))
{
return GetIndentationForQueryExpression(token);
}
return GetDefaultIndentationFromTokenLine(token);
}
private IndentationResult? GetIndentationForQueryExpression(SyntaxToken token)
{
// find containing non terminal node
var queryExpressionClause = GetQueryExpressionClause(token);
Contract.ThrowIfNull(queryExpressionClause);
// find line where first token of the node is
var snapshot = LineToBeIndented.Snapshot;
var firstToken = queryExpressionClause.GetFirstToken(includeZeroWidth: true);
var firstTokenLine = snapshot.GetLineFromPosition(firstToken.SpanStart);
// find line where given token is
var givenTokenLine = snapshot.GetLineFromPosition(token.SpanStart);
if (firstTokenLine.LineNumber != givenTokenLine.LineNumber)
{
// do default behavior
return GetDefaultIndentationFromTokenLine(token);
}
// okay, we are right under the query expression.
// align caret to query expression
if (firstToken.IsFirstTokenOnLine(snapshot))
{
return GetIndentationOfToken(firstToken);
}
// find query body that has a token that is a first token on the line
var queryBody = queryExpressionClause.Parent as QueryBodySyntax;
if (queryBody == null)
{
return GetIndentationOfToken(firstToken);
}
// find preceding clause that starts on its own.
var clauses = queryBody.Clauses;
for (int i = clauses.Count - 1; i >= 0; i--)
{
var clause = clauses[i];
if (firstToken.SpanStart <= clause.SpanStart)
{
continue;
}
var clauseToken = clause.GetFirstToken(includeZeroWidth: true);
if (clauseToken.IsFirstTokenOnLine(snapshot))
{
var tokenSpan = clauseToken.Span.ToSnapshotSpan(snapshot);
return GetIndentationOfToken(clauseToken);
}
}
// no query clause start a line. use the first token of the query expression
return GetIndentationOfToken(queryBody.Parent.GetFirstToken(includeZeroWidth: true));
}
private SyntaxNode GetQueryExpressionClause(SyntaxToken token)
{
var clause = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is QueryClauseSyntax || n is SelectOrGroupClauseSyntax);
if (clause != null)
{
return clause;
}
// If this is a query continuation, use the last clause of its parenting query.
var body = token.GetAncestor<QueryBodySyntax>();
if (body != null)
{
if (body.SelectOrGroup.IsMissing)
{
return body.Clauses.LastOrDefault();
}
else
{
return body.SelectOrGroup;
}
}
return null;
}
private bool IsPartOfQueryExpression(SyntaxToken token)
{
var queryExpression = token.GetAncestor<QueryExpressionSyntax>();
return queryExpression != null;
}
private IndentationResult? GetDefaultIndentationFromTokenLine(SyntaxToken token, int? additionalSpace = null)
{
var spaceToAdd = additionalSpace ?? this.OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language);
var snapshot = LineToBeIndented.Snapshot;
// find line where given token is
var givenTokenLine = snapshot.GetLineFromPosition(token.SpanStart);
// find right position
var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start);
// find containing non expression node
var nonExpressionNode = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is StatementSyntax);
if (nonExpressionNode == null)
{
// well, I can't find any non expression node. use default behavior
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, spaceToAdd, CancellationToken));
}
// find line where first token of the node is
var firstTokenLine = snapshot.GetLineFromPosition(nonExpressionNode.GetFirstToken(includeZeroWidth: true).SpanStart);
// single line expression
if (firstTokenLine.LineNumber == givenTokenLine.LineNumber)
{
return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, spaceToAdd, CancellationToken));
}
// okay, looks like containing node is written over multiple lines, in that case, give same indentation as given token
return GetIndentationOfLine(givenTokenLine);
}
protected override bool HasPreprocessorCharacter(ITextSnapshotLine currentLine)
{
if (currentLine == null)
{
throw new ArgumentNullException("currentLine");
}
var text = currentLine.GetText();
Contract.Requires(!string.IsNullOrWhiteSpace(text));
var trimmedText = text.Trim();
Contract.Assert(SyntaxFacts.GetText(SyntaxKind.HashToken).Length == 1);
return trimmedText[0] == SyntaxFacts.GetText(SyntaxKind.HashToken)[0];
}
private int GetCurrentPositionNotBelongToEndOfFileToken(int position)
{
var compilationUnit = Tree.GetRoot(CancellationToken) as CompilationUnitSyntax;
if (compilationUnit == null)
{
return position;
}
return Math.Min(compilationUnit.EndOfFileToken.FullSpan.Start, position);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Spatial.Prefix;
using Lucene.Net.Spatial.Prefix.Tree;
using Lucene.Net.Store;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OrchardCore.Environment.Shell;
using OrchardCore.Indexing;
using OrchardCore.Lucene.Model;
using OrchardCore.Lucene.Services;
using OrchardCore.Modules;
using Spatial4n.Core.Context;
using Directory = System.IO.Directory;
using LDirectory = Lucene.Net.Store.Directory;
namespace OrchardCore.Lucene
{
/// <summary>
/// Provides methods to manage physical Lucene indices.
/// This class is provided as a singleton to that the index searcher can be reused across requests.
/// </summary>
public class LuceneIndexManager : IDisposable
{
private readonly IClock _clock;
private readonly ILogger _logger;
private readonly string _rootPath;
private bool _disposing;
private readonly ConcurrentDictionary<string, IndexReaderPool> _indexPools = new ConcurrentDictionary<string, IndexReaderPool>(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<string, IndexWriterWrapper> _writers = new ConcurrentDictionary<string, IndexWriterWrapper>(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<string, DateTime> _timestamps = new ConcurrentDictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
private readonly LuceneAnalyzerManager _luceneAnalyzerManager;
private readonly LuceneIndexSettingsService _luceneIndexSettingsService;
private readonly SpatialContext _ctx;
private readonly GeohashPrefixTree _grid;
private readonly static object _synLock = new object();
public LuceneIndexManager(
IClock clock,
IOptions<ShellOptions> shellOptions,
ShellSettings shellSettings,
ILogger<LuceneIndexManager> logger,
LuceneAnalyzerManager luceneAnalyzerManager,
LuceneIndexSettingsService luceneIndexSettingsService
)
{
_clock = clock;
_logger = logger;
_rootPath = PathExtensions.Combine(
shellOptions.Value.ShellsApplicationDataPath,
shellOptions.Value.ShellsContainerName,
shellSettings.Name, "Lucene");
Directory.CreateDirectory(_rootPath);
_luceneAnalyzerManager = luceneAnalyzerManager;
_luceneIndexSettingsService = luceneIndexSettingsService;
// Typical geospatial context
// These can also be constructed from SpatialContextFactory
_ctx = SpatialContext.GEO;
var maxLevels = 11; // Results in sub-meter precision for geohash
// TODO demo lookup by detail distance
// This can also be constructed from SpatialPrefixTreeFactory
_grid = new GeohashPrefixTree(_ctx, maxLevels);
}
public async Task CreateIndexAsync(string indexName)
{
await WriteAsync(indexName, _ => { }, true);
}
public async Task DeleteDocumentsAsync(string indexName, IEnumerable<string> contentItemIds)
{
await WriteAsync(indexName, writer =>
{
writer.DeleteDocuments(contentItemIds.Select(x => new Term("ContentItemId", x)).ToArray());
writer.Commit();
if (_indexPools.TryRemove(indexName, out var pool))
{
pool.MakeDirty();
pool.Release();
}
});
}
public void DeleteIndex(string indexName)
{
lock (this)
{
if (_writers.TryGetValue(indexName, out var writer))
{
writer.IsClosing = true;
writer.Dispose();
}
if (_indexPools.TryRemove(indexName, out var reader))
{
reader.Dispose();
}
_timestamps.TryRemove(indexName, out _);
var indexFolder = PathExtensions.Combine(_rootPath, indexName);
if (Directory.Exists(indexFolder))
{
try
{
Directory.Delete(indexFolder, true);
}
catch { }
}
_writers.TryRemove(indexName, out _);
}
}
public bool Exists(string indexName)
{
if (String.IsNullOrWhiteSpace(indexName))
{
return false;
}
return Directory.Exists(PathExtensions.Combine(_rootPath, indexName));
}
public async Task StoreDocumentsAsync(string indexName, IEnumerable<DocumentIndex> indexDocuments)
{
await WriteAsync(indexName, writer =>
{
foreach (var indexDocument in indexDocuments)
{
writer.AddDocument(CreateLuceneDocument(indexDocument));
}
writer.Commit();
if (_indexPools.TryRemove(indexName, out var pool))
{
pool.MakeDirty();
pool.Release();
}
});
}
public async Task SearchAsync(string indexName, Func<IndexSearcher, Task> searcher)
{
if (Exists(indexName))
{
using (var reader = GetReader(indexName))
{
var indexSearcher = new IndexSearcher(reader.IndexReader);
await searcher(indexSearcher);
}
_timestamps[indexName] = _clock.UtcNow;
}
}
public void Read(string indexName, Action<IndexReader> reader)
{
if (Exists(indexName))
{
using (var indexReader = GetReader(indexName))
{
reader(indexReader.IndexReader);
}
_timestamps[indexName] = _clock.UtcNow;
}
}
/// <summary>
/// Returns a list of open indices and the last time they were accessed.
/// </summary>
public IReadOnlyDictionary<string, DateTime> GetTimestamps()
{
return new ReadOnlyDictionary<string, DateTime>(_timestamps);
}
private Document CreateLuceneDocument(DocumentIndex documentIndex)
{
var doc = new Document
{
// Always store the content item id
new StringField("ContentItemId", documentIndex.ContentItemId.ToString(), Field.Store.YES)
};
foreach (var entry in documentIndex.Entries)
{
var store = entry.Options.HasFlag(DocumentIndexOptions.Store)
? Field.Store.YES
: Field.Store.NO;
switch (entry.Type)
{
case DocumentIndex.Types.Boolean:
// Store "true"/"false" for booleans
doc.Add(new StringField(entry.Name, Convert.ToString(entry.Value).ToLowerInvariant(), store));
break;
case DocumentIndex.Types.DateTime:
if (entry.Value != null)
{
if (entry.Value is DateTimeOffset)
{
doc.Add(new StringField(entry.Name, DateTools.DateToString(((DateTimeOffset)entry.Value).UtcDateTime, DateTools.Resolution.SECOND), store));
}
else
{
doc.Add(new StringField(entry.Name, DateTools.DateToString(((DateTime)entry.Value).ToUniversalTime(), DateTools.Resolution.SECOND), store));
}
}
else
{
doc.Add(new StringField(entry.Name, "NULL", store));
}
break;
case DocumentIndex.Types.Integer:
if (entry.Value != null && Int64.TryParse(entry.Value.ToString(), out var value))
{
doc.Add(new Int64Field(entry.Name, value, store));
}
else
{
doc.Add(new StringField(entry.Name, "NULL", store));
}
break;
case DocumentIndex.Types.Number:
if (entry.Value != null)
{
doc.Add(new DoubleField(entry.Name, Convert.ToDouble(entry.Value), store));
}
else
{
doc.Add(new StringField(entry.Name, "NULL", store));
}
break;
case DocumentIndex.Types.Text:
if (entry.Value != null && !String.IsNullOrEmpty(Convert.ToString(entry.Value)))
{
if (entry.Options.HasFlag(DocumentIndexOptions.Analyze))
{
doc.Add(new TextField(entry.Name, Convert.ToString(entry.Value), store));
}
else
{
doc.Add(new StringField(entry.Name, Convert.ToString(entry.Value), store));
}
}
else
{
if (entry.Options.HasFlag(DocumentIndexOptions.Analyze))
{
doc.Add(new TextField(entry.Name, "NULL", store));
}
else
{
doc.Add(new StringField(entry.Name, "NULL", store));
}
}
break;
case DocumentIndex.Types.GeoPoint:
var strategy = new RecursivePrefixTreeStrategy(_grid, entry.Name);
if (entry.Value != null && entry.Value is DocumentIndex.GeoPoint point)
{
var geoPoint = _ctx.MakePoint((double)point.Longitude, (double)point.Latitude);
foreach (var field in strategy.CreateIndexableFields(geoPoint))
{
doc.Add(field);
}
if (entry.Options.HasFlag(DocumentIndexOptions.Store))
{
doc.Add(new StoredField(strategy.FieldName, $"{point.Latitude},{point.Longitude}"));
}
}
else
{
doc.Add(new StringField(strategy.FieldName, "NULL", store));
}
break;
}
}
return doc;
}
private BaseDirectory CreateDirectory(string indexName)
{
lock (this)
{
var path = new DirectoryInfo(PathExtensions.Combine(_rootPath, indexName));
if (!path.Exists)
{
path.Create();
}
// Lucene is not thread safe on this call
lock (_synLock)
{
return FSDirectory.Open(path);
}
}
}
private async Task WriteAsync(string indexName, Action<IndexWriter> action, bool close = false)
{
if (!_writers.TryGetValue(indexName, out var writer))
{
var indexAnalyzer = await _luceneIndexSettingsService.LoadIndexAnalyzerAsync(indexName);
lock (this)
{
if (!_writers.TryGetValue(indexName, out writer))
{
var directory = CreateDirectory(indexName);
var analyzer = _luceneAnalyzerManager.CreateAnalyzer(indexAnalyzer);
var config = new IndexWriterConfig(LuceneSettings.DefaultVersion, analyzer)
{
OpenMode = OpenMode.CREATE_OR_APPEND,
WriteLockTimeout = Lock.LOCK_POLL_INTERVAL * 3
};
writer = new IndexWriterWrapper(directory, config);
if (close)
{
action?.Invoke(writer);
writer.Dispose();
_timestamps[indexName] = _clock.UtcNow;
return;
}
_writers[indexName] = writer;
}
}
}
if (writer.IsClosing)
{
return;
}
action?.Invoke(writer);
_timestamps[indexName] = _clock.UtcNow;
}
private IndexReaderPool.IndexReaderLease GetReader(string indexName)
{
var pool = _indexPools.GetOrAdd(indexName, n =>
{
var path = new DirectoryInfo(PathExtensions.Combine(_rootPath, indexName));
var reader = DirectoryReader.Open(FSDirectory.Open(path));
return new IndexReaderPool(reader);
});
return pool.Acquire();
}
/// <summary>
/// Releases all readers and writers. This can be used after some time of innactivity to free resources.
/// </summary>
public void FreeReaderWriter()
{
lock (this)
{
foreach (var writer in _writers)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Freeing writer for: " + writer.Key);
}
writer.Value.IsClosing = true;
writer.Value.Dispose();
}
foreach (var reader in _indexPools)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Freeing reader for: " + reader.Key);
}
reader.Value.Dispose();
}
_writers.Clear();
_indexPools.Clear();
_timestamps.Clear();
}
}
/// <summary>
/// Releases all readers and writers. This can be used after some time of innactivity to free resources.
/// </summary>
public void FreeReaderWriter(string indexName)
{
lock (this)
{
if (_writers.TryGetValue(indexName, out var writer))
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Freeing writer for: " + indexName);
}
writer.IsClosing = true;
writer.Dispose();
}
if (_indexPools.TryGetValue(indexName, out var reader))
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Freeing reader for: " + indexName);
}
reader.Dispose();
}
_timestamps.TryRemove(indexName, out _);
_writers.TryRemove(indexName, out _);
}
}
public void Dispose()
{
if (_disposing)
{
return;
}
_disposing = true;
FreeReaderWriter();
}
~LuceneIndexManager()
{
Dispose();
}
}
internal class IndexWriterWrapper : IndexWriter
{
public IndexWriterWrapper(LDirectory directory, IndexWriterConfig config) : base(directory, config)
{
IsClosing = false;
}
public bool IsClosing { get; set; }
}
internal class IndexReaderPool : IDisposable
{
private bool _dirty;
private int _count;
private readonly IndexReader _reader;
public IndexReaderPool(IndexReader reader)
{
_reader = reader;
}
public void MakeDirty()
{
_dirty = true;
}
public IndexReaderLease Acquire()
{
return new IndexReaderLease(this, _reader);
}
public void Release()
{
if (_dirty && _count == 0)
{
_reader.Dispose();
}
}
public void Dispose()
{
_reader.Dispose();
}
public struct IndexReaderLease : IDisposable
{
private readonly IndexReaderPool _pool;
public IndexReaderLease(IndexReaderPool pool, IndexReader reader)
{
_pool = pool;
Interlocked.Increment(ref _pool._count);
IndexReader = reader;
}
public IndexReader IndexReader { get; }
public void Dispose()
{
Interlocked.Decrement(ref _pool._count);
_pool.Release();
}
}
}
}
| |
/* ====================================================================
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.Record
{
using System;
using System.IO;
using System.Text;
using NPOI.HSSF.Record;
using NPOI.Util;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula;
using NPOI.SS.UserModel;
using NPOI.HSSF.Record.Cont;
using NPOI.SS.Formula.PTG;
using System.Globalization;
internal class TextObjectRecord : ContinuableRecord
{
NPOI.SS.UserModel.IRichTextString _text;
public const short sid = 0x1B6;
private static int FORMAT_RUN_ENCODED_SIZE = 8; // 2 shorts and 4 bytes reserved
private BitField _HorizontalTextAlignment = BitFieldFactory.GetInstance(0x000E);
private BitField _VerticalTextAlignment = BitFieldFactory.GetInstance(0x0070);
private BitField textLocked = BitFieldFactory.GetInstance(0x200);
public const short TEXT_ORIENTATION_NONE = 0;
public const short TEXT_ORIENTATION_TOP_TO_BOTTOM = 1;
public const short TEXT_ORIENTATION_ROT_RIGHT = 2;
public const short TEXT_ORIENTATION_ROT_LEFT = 3;
public const short HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED = 1;
public const short HORIZONTAL_TEXT_ALIGNMENT_CENTERED = 2;
public const short HORIZONTAL_TEXT_ALIGNMENT_RIGHT_ALIGNED = 3;
public const short HORIZONTAL_TEXT_ALIGNMENT_JUSTIFIED = 4;
public const short VERTICAL_TEXT_ALIGNMENT_TOP = 1;
public const short VERTICAL_TEXT_ALIGNMENT_CENTER = 2;
public const short VERTICAL_TEXT_ALIGNMENT_BOTTOM = 3;
public const short VERTICAL_TEXT_ALIGNMENT_JUSTIFY = 4;
private int field_1_options;
private int field_2_textOrientation;
private int field_3_reserved4;
private int field_4_reserved5;
private int field_5_reserved6;
private int field_8_reserved7;
/*
* Note - the next three fields are very similar to those on
* EmbededObjectRefSubRecord(ftPictFmla 0x0009)
*
* some observed values for the 4 bytes preceding the formula: C0 5E 86 03
* C0 11 AC 02 80 F1 8A 03 D4 F0 8A 03
*/
private int _unknownPreFormulaInt;
/** expect tRef, tRef3D, tArea, tArea3D or tName */
private OperandPtg _linkRefPtg;
/**
* Not clear if needed . Excel seems to be OK if this byte is not present.
* Value is often the same as the earlier firstColumn byte. */
private Byte? _unknownPostFormulaByte;
public TextObjectRecord()
{
}
public TextObjectRecord(RecordInputStream in1)
{
field_1_options = in1.ReadUShort();
field_2_textOrientation = in1.ReadUShort();
field_3_reserved4 = in1.ReadUShort();
field_4_reserved5 = in1.ReadUShort();
field_5_reserved6 = in1.ReadUShort();
int field_6_textLength = in1.ReadUShort();
int field_7_formattingDataLength = in1.ReadUShort();
field_8_reserved7 = in1.ReadInt();
if (in1.Remaining > 0)
{
// Text Objects can have simple reference formulas
// (This bit not mentioned in the MS document)
if (in1.Remaining < 11)
{
throw new RecordFormatException("Not enough remaining data for a link formula");
}
int formulaSize = in1.ReadUShort();
_unknownPreFormulaInt = in1.ReadInt();
Ptg[] ptgs = Ptg.ReadTokens(formulaSize, in1);
if (ptgs.Length != 1)
{
throw new RecordFormatException("Read " + ptgs.Length
+ " tokens but expected exactly 1");
}
_linkRefPtg = (OperandPtg)ptgs[0];
if (in1.Remaining > 0)
{
_unknownPostFormulaByte = (byte)in1.ReadByte();
}
else
{
_unknownPostFormulaByte = null;
}
}
else
{
_linkRefPtg = null;
}
if (in1.Remaining > 0)
{
throw new RecordFormatException("Unused " + in1.Remaining + " bytes at end of record");
}
String text;
if (field_6_textLength > 0)
{
text = ReadRawString(in1, field_6_textLength);
}
else
{
text = "";
}
_text = new HSSFRichTextString(text);
if (field_7_formattingDataLength > 0)
{
ProcessFontRuns(in1, _text, field_7_formattingDataLength);
}
}
private static void ProcessFontRuns(RecordInputStream in1, IRichTextString str,
int formattingRunDataLength)
{
if (formattingRunDataLength % FORMAT_RUN_ENCODED_SIZE != 0)
{
throw new RecordFormatException("Bad format run data length " + formattingRunDataLength
+ ")");
}
int nRuns = formattingRunDataLength / FORMAT_RUN_ENCODED_SIZE;
for (int i = 0; i < nRuns; i++)
{
short index = in1.ReadShort();
short iFont = in1.ReadShort();
in1.ReadInt(); // skip reserved.
str.ApplyFont(index, str.Length, iFont);
}
}
private int TrailingRecordsSize
{
get
{
if (_text.Length < 1)
{
return 0;
}
int encodedTextSize = 0;
int textBytesLength = _text.Length * LittleEndianConsts.SHORT_SIZE;
while (textBytesLength > 0)
{
int chunkSize = Math.Min(RecordInputStream.MAX_RECORD_DATA_SIZE - 2, textBytesLength);
textBytesLength -= chunkSize;
encodedTextSize += 4; // +4 for ContinueRecord sid+size
encodedTextSize += 1 + chunkSize; // +1 for compressed unicode flag,
}
int encodedFormatSize = (_text.NumFormattingRuns + 1) * FORMAT_RUN_ENCODED_SIZE
+ 4; // +4 for ContinueRecord sid+size
return encodedTextSize + encodedFormatSize;
}
}
private static byte[] CreateFormatData(IRichTextString str)
{
int nRuns = str.NumFormattingRuns;
byte[] result = new byte[(nRuns + 1) * FORMAT_RUN_ENCODED_SIZE];
int pos = 0;
for (int i = 0; i < nRuns; i++)
{
LittleEndian.PutUShort(result, pos, str.GetIndexOfFormattingRun(i));
pos += 2;
int fontIndex = ((HSSFRichTextString)str).GetFontOfFormattingRun(i);
LittleEndian.PutUShort(result, pos, fontIndex == HSSFRichTextString.NO_FONT ? 0 : fontIndex);
pos += 2;
pos += 4; // skip reserved
}
LittleEndian.PutUShort(result, pos, str.Length);
pos += 2;
LittleEndian.PutUShort(result, pos, 0);
pos += 2;
pos += 4; // skip reserved
return result;
}
private void SerializeTrailingRecords(ContinuableRecordOutput out1)
{
out1.WriteContinue();
out1.WriteStringData(_text.String);
out1.WriteContinue();
WriteFormatData(out1,_text);
}
private void WriteFormatData(ContinuableRecordOutput out1, IRichTextString str)
{
int nRuns = str.NumFormattingRuns;
for (int i = 0; i < nRuns; i++)
{
out1.WriteShort(str.GetIndexOfFormattingRun(i));
int fontIndex = ((HSSFRichTextString)str).GetFontOfFormattingRun(i);
out1.WriteShort(fontIndex == HSSFRichTextString.NO_FONT ? 0 : fontIndex);
out1.WriteInt(0); // skip reserved
}
out1.WriteShort(str.Length);
out1.WriteShort(0);
out1.WriteInt(0); // skip reserved
}
private int FormattingDataLength
{
get
{
if (_text.Length < 1)
{
// important - no formatting data if text is empty
return 0;
}
return (_text.NumFormattingRuns + 1) * FORMAT_RUN_ENCODED_SIZE;
}
}
private void SerializeTXORecord(ContinuableRecordOutput out1)
{
out1.WriteShort(field_1_options);
out1.WriteShort(field_2_textOrientation);
out1.WriteShort(field_3_reserved4);
out1.WriteShort(field_4_reserved5);
out1.WriteShort(field_5_reserved6);
out1.WriteShort(_text.Length);
out1.WriteShort(FormattingDataLength);
out1.WriteInt(field_8_reserved7);
if (_linkRefPtg != null)
{
int formulaSize = _linkRefPtg.Size;
out1.WriteShort(formulaSize);
out1.WriteInt(_unknownPreFormulaInt);
_linkRefPtg.Write(out1);
if (_unknownPostFormulaByte != null)
{
out1.WriteByte(Convert.ToByte(_unknownPostFormulaByte, CultureInfo.InvariantCulture));
}
}
}
protected override void Serialize(ContinuableRecordOutput out1)
{
SerializeTXORecord(out1);
if (_text.String.Length > 0)
{
SerializeTrailingRecords(out1);
}
}
private void ProcessFontRuns(RecordInputStream in1)
{
while (in1.Remaining > 0)
{
short index = in1.ReadShort();
short iFont = in1.ReadShort();
in1.ReadInt(); // skip reserved.
_text.ApplyFont(index, _text.Length, iFont);
}
}
private static String ReadRawString(RecordInputStream in1, int textLength)
{
byte compressByte = (byte)in1.ReadByte();
bool isCompressed = (compressByte & 0x01) == 0;
if (isCompressed)
{
return in1.ReadCompressedUnicode(textLength);
}
return in1.ReadUnicodeLEString(textLength);
}
public IRichTextString Str
{
get { return _text; }
set { this._text = value; }
}
public override short Sid
{
get
{
return sid;
}
}
/**
* Get the text orientation field for the TextObjectBase record.
*
* @return One of
* TEXT_ORIENTATION_NONE
* TEXT_ORIENTATION_TOP_TO_BOTTOM
* TEXT_ORIENTATION_ROT_RIGHT
* TEXT_ORIENTATION_ROT_LEFT
*/
public int TextOrientation
{
get { return field_2_textOrientation; }
set { this.field_2_textOrientation = value; }
}
/**
* @return the Horizontal text alignment field value.
*/
public int HorizontalTextAlignment
{
get
{
return _HorizontalTextAlignment.GetValue(field_1_options);
}
set { field_1_options = _HorizontalTextAlignment.SetValue(field_1_options, value); }
}
/**
* @return the Vertical text alignment field value.
*/
public int VerticalTextAlignment
{
get
{
return _VerticalTextAlignment.GetValue(field_1_options);
}
set { field_1_options = _VerticalTextAlignment.SetValue(field_1_options, value); }
}
/**
* Text has been locked
* @return the text locked field value.
*/
public bool IsTextLocked
{
get { return textLocked.IsSet(field_1_options); }
set { field_1_options = textLocked.SetBoolean(field_1_options, value); }
}
public Ptg LinkRefPtg
{
get
{
return _linkRefPtg;
}
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("[TXO]\n");
sb.Append(" .options = ").Append(HexDump.ShortToHex(field_1_options)).Append("\n");
sb.Append(" .IsHorizontal = ").Append(HorizontalTextAlignment).Append('\n');
sb.Append(" .IsVertical = ").Append(VerticalTextAlignment).Append('\n');
sb.Append(" .textLocked = ").Append(IsTextLocked).Append('\n');
sb.Append(" .textOrientation= ").Append(HexDump.ShortToHex(TextOrientation)).Append("\n");
sb.Append(" .reserved4 = ").Append(HexDump.ShortToHex(field_3_reserved4)).Append("\n");
sb.Append(" .reserved5 = ").Append(HexDump.ShortToHex(field_4_reserved5)).Append("\n");
sb.Append(" .reserved6 = ").Append(HexDump.ShortToHex(field_5_reserved6)).Append("\n");
sb.Append(" .textLength = ").Append(HexDump.ShortToHex(_text.Length)).Append("\n");
sb.Append(" .reserved7 = ").Append(HexDump.IntToHex(field_8_reserved7)).Append("\n");
sb.Append(" .string = ").Append(_text).Append('\n');
for (int i = 0; i < _text.NumFormattingRuns; i++)
{
sb.Append(" .textrun = ").Append(((HSSFRichTextString)_text).GetFontOfFormattingRun(i)).Append('\n');
}
sb.Append("[/TXO]\n");
return sb.ToString();
}
public override Object Clone()
{
TextObjectRecord rec = new TextObjectRecord();
rec._text = _text;
rec.field_1_options = field_1_options;
rec.field_2_textOrientation = field_2_textOrientation;
rec.field_3_reserved4 = field_3_reserved4;
rec.field_4_reserved5 = field_4_reserved5;
rec.field_5_reserved6 = field_5_reserved6;
rec.field_8_reserved7 = field_8_reserved7;
rec._text = _text; // clone needed?
if (_linkRefPtg != null)
{
rec._unknownPreFormulaInt = _unknownPreFormulaInt;
rec._linkRefPtg = _linkRefPtg.Copy();
rec._unknownPostFormulaByte = _unknownPostFormulaByte;
}
return rec;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using Rynchodon.Autopilot.Instruction.Command;
using Rynchodon.Utility;
using Sandbox.Game.Entities;
using Sandbox.Game.Gui;
using Sandbox.ModAPI;
using Sandbox.ModAPI.Interfaces.Terminal;
using VRage.Game.ModAPI;
using VRage.ModAPI;
using VRage.Utils;
namespace Rynchodon.Autopilot.Instruction
{
/// <summary>
/// GUI programming and command interpretation.
/// </summary>
public class AutopilotCommands
{
private class StaticVariables
{
public readonly Regex GPS_tag = new Regex(@"[^c]\s*GPS:.*?:(-?\d+\.?\d*):(-?\d+\.?\d*):(-?\d+\.?\d*):");
public readonly string GPS_replaceWith = @"cg $1, $2, $3";
public Dictionary<char, List<ACommand>> dummyCommands = new Dictionary<char, List<ACommand>>();
public AddCommandInternalNode addCommandRoot;
}
private static StaticVariables Static = new StaticVariables();
static AutopilotCommands()
{
List<AddCommandInternalNode> rootCommands = new List<AddCommandInternalNode>();
// fly somewhere
List<AddCommandLeafNode> commands = new List<AddCommandLeafNode>();
AddDummy(new GolisCoordinate(), commands);
AddDummy(new GolisGps(), commands);
AddDummy(new FlyRelative(), commands);
AddDummy(new Character(), commands);
rootCommands.Add(new AddCommandInternalNode("Fly Somewhere", commands.ToArray()));
// friendly grid
commands.Clear();
AddDummy(new TargetBlockSearch(), commands);
AddDummy(new LandingBlock(), commands);
AddDummy(new Offset(), commands);
AddDummy(new Form(), commands);
AddDummy(new GridDestination(), commands);
AddDummy(new Unland(), commands);
AddDummy(new UnlandBlock(), commands);
rootCommands.Add(new AddCommandInternalNode("Fly to a Ship", commands.ToArray()));
// complex task
commands.Clear();
AddDummy(new Enemy(), commands);
AddDummy(new HarvestVoxel(), commands);
AddDummy(new Grind(), commands);
AddDummy(new Weld(), commands);
AddDummy(new LandVoxel(), commands);
AddDummy(new Orbit(), commands);
AddDummy(new NavigationBlock(), commands);
AddDummy(new FaceMove(), commands);
rootCommands.Add(new AddCommandInternalNode("Tasks", commands.ToArray()));
// variables
commands.Clear();
AddDummy(new Proximity(), commands);
AddDummy(new SpeedLimit(), commands);
AddDummy(new Jump(), commands);
AddDummy(new StraightLine(), commands);
AddDummy(new Asteroid(), commands);
rootCommands.Add(new AddCommandInternalNode("Variables", commands.ToArray()));
// flow control
commands.Clear();
AddDummy(new TextPanel(), commands);
AddDummy(new Wait(), commands);
AddDummy(new Exit(), commands);
AddDummy(new Stop(), commands);
AddDummy(new Disable(), commands);
AddDummy(new WaitForBatteryRecharge(), commands);
rootCommands.Add(new AddCommandInternalNode("Flow Control", commands.ToArray()));
// terminal action/property
commands.Clear();
AddDummy(new TerminalAction(), commands);
AddDummy(new TerminalPropertyBool(), commands);
AddDummy(new TerminalPropertyFloat(), commands);
AddDummy(new TerminalPropertyColour(), commands);
rootCommands.Add(new AddCommandInternalNode("Terminal", commands.ToArray()));
Static.addCommandRoot = new AddCommandInternalNode("root", rootCommands.ToArray());
}
private static void AddDummy(ACommand command, string idOrAlias)
{
List<ACommand> list;
if (!Static.dummyCommands.TryGetValue(idOrAlias[0], out list))
{
list = new List<ACommand>();
Static.dummyCommands.Add(idOrAlias[0], list);
}
if (!list.Contains(command))
list.Add(command);
}
private static void AddDummy(ACommand command, List<AddCommandLeafNode> children = null)
{
foreach (string idOrAlias in command.IdAndAliases())
AddDummy(command, idOrAlias);
if (children != null)
children.Add(new AddCommandLeafNode(command));
}
public static AutopilotCommands GetOrCreate(IMyTerminalBlock block)
{
if (Globals.WorldClosed || block.Closed)
return null;
AutopilotCommands result;
if (!Registrar.TryGetValue(block, out result))
result = new AutopilotCommands(block);
return result;
}
/// <summary>
/// Get the best command associated with a string.
/// </summary>
/// <param name="parse">The complete command string, including Identifier.</param>
/// <returns>The best command associated with parse.</returns>
private static ACommand GetCommand(string parse)
{
parse = parse.TrimStart().ToLower();
List<ACommand> list;
if (!Static.dummyCommands.TryGetValue(parse[0], out list))
return null;
ACommand bestMatch = null;
int bestMatchLength = 0;
foreach (ACommand cmd in list)
foreach (string idOrAlias in cmd.IdAndAliases())
if (idOrAlias.Length > bestMatchLength && parse.StartsWith(idOrAlias))
{
bestMatchLength = idOrAlias.Length;
bestMatch = cmd;
}
if (bestMatch == null)
return null;
return bestMatch.Clone();
}
private readonly IMyTerminalBlock m_block;
/// <summary>Command list for GUI programming, not to be used by others</summary>
private readonly List<ACommand> m_commandList = new List<ACommand>();
/// <summary>Shared from any command source</summary>
private readonly StringBuilder m_syntaxErrors = new StringBuilder();
/// <summary>Action list for GUI programming and commands text box, not to be used for messaged commands.</summary>
private readonly AutopilotActionList m_actionList = new AutopilotActionList();
private IMyTerminalControlListbox m_termCommandList;
private bool m_listCommands = true, m_replace;
private int m_insertIndex;
private ACommand m_currentCommand;
private Stack<AddCommandInternalNode> m_currentAddNode = new Stack<AddCommandInternalNode>();
private string m_infoMessage, m_commands;
private Logable Log { get { return new Logable(m_block); } }
/// <summary>
/// The most recent commands from either terminal or a message.
/// </summary>
public string Commands
{
get { return m_commands; }
private set
{
m_commands = value;
Log.AlwaysLog("Commands: " + m_commands); // for bug reports
}
}
public bool HasSyntaxErrors { get { return m_syntaxErrors.Length != 0; } }
private AutopilotCommands(IMyTerminalBlock block)
{
this.m_block = block;
m_block.AppendingCustomInfo += m_block_AppendSyntaxErrors;
Registrar.Add(block, this);
}
/// <summary>
/// Invoke when commands textbox changed.
/// </summary>
public void OnCommandsChanged()
{
Log.DebugLog("entered");
m_actionList.Clear();
}
public void StartGooeyProgramming()
{
Log.DebugLog("entered");
using (MainLock.AcquireSharedUsing())
{
m_currentCommand = null;
m_listCommands = true;
m_commandList.Clear();
m_syntaxErrors.Clear();
MyTerminalControls.Static.CustomControlGetter += CustomControlGetter;
m_block.AppendingCustomInfo += m_block_AppendingCustomInfo;
Commands = AutopilotTerminal.GetAutopilotCommands(m_block).ToString();
foreach (ACommand comm in ParseCommands(Commands))
m_commandList.Add(comm);
if (m_syntaxErrors.Length != 0)
m_block.UpdateCustomInfo();
m_block.RebuildControls();
}
}
public AutopilotActionList GetActions()
{
using (MainLock.AcquireSharedUsing())
{
if (!m_actionList.IsEmpty)
{
m_actionList.Reset();
return m_actionList;
}
m_syntaxErrors.Clear();
Commands = AutopilotTerminal.GetAutopilotCommands(m_block).ToString();
List<ACommand> commands = new List<ACommand>();
GetActions(Commands, m_actionList);
if (m_syntaxErrors.Length != 0)
m_block.UpdateCustomInfo();
return m_actionList;
}
}
public AutopilotActionList GetActions(string allCommands)
{
using (MainLock.AcquireSharedUsing())
{
Commands = allCommands;
m_syntaxErrors.Clear();
AutopilotActionList actList = new AutopilotActionList();
GetActions(Commands, actList);
if (m_syntaxErrors.Length != 0)
m_block.UpdateCustomInfo();
return actList;
}
}
public void GetActions(string allCommands, AutopilotActionList actionList)
{
GetActions(ParseCommands(allCommands), actionList);
}
private IEnumerable<ACommand> ParseCommands(string allCommands)
{
if (string.IsNullOrWhiteSpace(allCommands))
{
Logger.DebugLog("no commands");
yield break;
}
allCommands = Static.GPS_tag.Replace(allCommands, Static.GPS_replaceWith);
string[] commands = allCommands.Split(new char[] { ';', ':' });
foreach (string cmd in commands)
{
if (string.IsNullOrWhiteSpace(cmd))
{
Logger.DebugLog("empty command");
continue;
}
ACommand apCmd = GetCommand(cmd);
if (apCmd == null)
{
m_syntaxErrors.AppendLine("No command: \"" + cmd + '"');
Logger.DebugLog("No command: \"" + cmd + '"');
continue;
}
string msg;
if (!apCmd.SetDisplayString((IMyCubeBlock)m_block, cmd, out msg))
{
m_syntaxErrors.Append("Error with command: \"");
m_syntaxErrors.Append(cmd);
m_syntaxErrors.Append("\":\n ");
m_syntaxErrors.AppendLine(msg);
Logger.DebugLog("Error with command: \"" + cmd + "\":\n " + msg, Logger.severity.INFO);
continue;
}
yield return apCmd;
}
}
private void GetActions(IEnumerable<ACommand> commandList, AutopilotActionList actionList)
{
int count = 0;
const int limit = 1000;
foreach (ACommand cmd in commandList)
{
TextPanel tp = cmd as TextPanel;
if (tp == null)
{
if (cmd.Action == null)
{
Logger.AlwaysLog("Command is missing action: " + cmd.DisplayString, Logger.severity.ERROR);
continue;
}
if (++count > limit)
{
Logger.DebugLog("Reached command limit");
m_syntaxErrors.AppendLine("Reached command limit");
return;
}
Logger.DebugLog("yield: " + cmd.DisplayString);
actionList.Add(cmd.Action);
continue;
}
TextPanelMonitor textPanelMonitor = tp.GetTextPanelMonitor(m_block, this);
if (textPanelMonitor == null)
{
Logger.DebugLog("Text panel not found: " + tp.SearchPanelName);
m_syntaxErrors.Append("Text panel not found: ");
m_syntaxErrors.AppendLine(tp.SearchPanelName);
continue;
}
if (textPanelMonitor.AutopilotActions.IsEmpty)
{
Logger.DebugLog(textPanelMonitor.TextPanel.DisplayNameText + " has no commands");
m_syntaxErrors.Append(textPanelMonitor.TextPanel.DisplayNameText);
m_syntaxErrors.AppendLine(" has no commands");
continue;
}
actionList.Add(textPanelMonitor);
}
actionList.Reset();
}
private void CustomControlGetter(IMyTerminalBlock block, List<IMyTerminalControl> controls)
{
//Log.DebugLog("entered");
if (block != m_block)
return;
controls.Clear();
if (m_listCommands)
{
Log.DebugLog("showing command list");
if (m_termCommandList == null)
{
m_termCommandList = new MyTerminalControlListbox<MyShipController>("CommandList", MyStringId.GetOrCompute("Commands"), MyStringId.NullOrEmpty, false, 10);
m_termCommandList.ListContent = ListCommands;
m_termCommandList.ItemSelected = CommandSelected;
}
controls.Add(m_termCommandList);
controls.Add(new MyTerminalControlButton<MyShipController>("AddCommand", MyStringId.GetOrCompute("Add Command"), MyStringId.NullOrEmpty, AddCommand));
controls.Add(new MyTerminalControlButton<MyShipController>("InsertCommand", MyStringId.GetOrCompute("Insert Command"), MyStringId.NullOrEmpty, InsertCommand));
controls.Add(new MyTerminalControlButton<MyShipController>("RemoveCommand", MyStringId.GetOrCompute("Remove Command"), MyStringId.NullOrEmpty, RemoveCommand));
controls.Add(new MyTerminalControlButton<MyShipController>("EditCommand", MyStringId.GetOrCompute("Edit Command"), MyStringId.NullOrEmpty, EditCommand));
controls.Add(new MyTerminalControlButton<MyShipController>("MoveCommandUp", MyStringId.GetOrCompute("Move Command Up"), MyStringId.NullOrEmpty, MoveCommandUp));
controls.Add(new MyTerminalControlButton<MyShipController>("MoveCommandDown", MyStringId.GetOrCompute("Move Command Down"), MyStringId.NullOrEmpty, MoveCommandDown));
controls.Add(new MyTerminalControlSeparator<MyShipController>());
controls.Add(new MyTerminalControlButton<MyShipController>("Finished", MyStringId.GetOrCompute("Save & Exit"), MyStringId.GetOrCompute("Save all commands and exit"), b => Finished(true)));
controls.Add(new MyTerminalControlButton<MyShipController>("DiscardAll", MyStringId.GetOrCompute("Discard & Exit"), MyStringId.GetOrCompute("Discard all commands and exit"), b => Finished(false)));
return;
}
if (m_currentCommand == null)
{
// add/insert new command
if (m_currentAddNode.Count == 0)
m_currentAddNode.Push(Static.addCommandRoot);
foreach (AddCommandTreeNode child in m_currentAddNode.Peek().Children)
controls.Add(new MyTerminalControlButton<MyShipController>(child.Name.RemoveWhitespace(), MyStringId.GetOrCompute(child.Name), MyStringId.GetOrCompute(child.Tooltip), shipController => {
AddCommandLeafNode leaf = child as AddCommandLeafNode;
if (leaf != null)
{
m_currentCommand = leaf.Command.Clone();
if (!m_currentCommand.HasControls)
CheckAndSave(block);
m_currentAddNode.Clear();
}
else
m_currentAddNode.Push((AddCommandInternalNode)child);
ClearMessage();
}));
controls.Add(new MyTerminalControlButton<MyShipController>("UpOneLevel", MyStringId.GetOrCompute("Up one level"), MyStringId.GetOrCompute("Return to previous list"), shipController => {
m_currentAddNode.Pop();
if (m_currentAddNode.Count == 0)
m_listCommands = true;
shipController.RebuildControls();
}));
return;
}
Log.DebugLog("showing single command: " + m_currentCommand.Identifier);
m_currentCommand.AddControls(controls);
controls.Add(new MyTerminalControlSeparator<MyShipController>());
controls.Add(new MyTerminalControlButton<MyShipController>("SaveGooeyCommand", MyStringId.GetOrCompute("Check & Save"), MyStringId.GetOrCompute("Check the current command for syntax errors and save it"), CheckAndSave));
controls.Add(new MyTerminalControlButton<MyShipController>("DiscardGooeyCommand", MyStringId.GetOrCompute("Discard"), MyStringId.GetOrCompute("Discard the current command"), Discard));
}
private void ListCommands(IMyTerminalBlock block, List<MyTerminalControlListBoxItem> allItems, List<MyTerminalControlListBoxItem> selected)
{
Log.DebugLog("block != m_block", Logger.severity.FATAL, condition: block != m_block);
foreach (ACommand command in m_commandList)
{
// this will leak memory, as MyTerminalControlListBoxItem uses MyStringId for some stupid reason
MyTerminalControlListBoxItem item = new MyTerminalControlListBoxItem(MyStringId.GetOrCompute(command.DisplayString), MyStringId.GetOrCompute(command.Description), command);
allItems.Add(item);
if (command == m_currentCommand && selected.Count == 0)
selected.Add(item);
}
}
private void CommandSelected(IMyTerminalBlock block, List<MyTerminalControlListBoxItem> selected)
{
Log.DebugLog("block != m_block", Logger.severity.FATAL, condition: block != m_block);
Log.DebugLog("selected.Count: " + selected.Count, Logger.severity.ERROR, condition: selected.Count > 1);
if (selected.Count == 0)
{
m_currentCommand = null;
Log.DebugLog("selection cleared");
}
else
{
m_currentCommand = (ACommand)selected[0].UserData;
Log.DebugLog("selected: " + m_currentCommand.DisplayString);
}
}
#region Button Action
private void Discard(IMyTerminalBlock block)
{
Log.DebugLog("entered");
Log.DebugLog("block != m_block", Logger.severity.FATAL, condition: block != m_block);
Log.DebugLog("m_currentCommand == null", Logger.severity.FATAL, condition: m_currentCommand == null);
m_currentCommand = null;
m_listCommands = true;
ClearMessage();
}
private void CheckAndSave(IMyTerminalBlock block)
{
Log.DebugLog("block != m_block", Logger.severity.FATAL, condition: block != m_block);
Log.DebugLog("m_currentCommand == null", Logger.severity.FATAL, condition: m_currentCommand == null);
string msg;
if (m_currentCommand.ValidateControls((IMyCubeBlock)m_block, out msg))
{
if (m_commandList.Contains(m_currentCommand))
{
Log.DebugLog("edited command: " + m_currentCommand.DisplayString);
}
else
{
if (m_insertIndex == -1)
{
Log.DebugLog("new command: " + m_currentCommand.DisplayString);
m_commandList.Add(m_currentCommand);
}
else
{
if (m_replace)
{
m_commandList.RemoveAt(m_insertIndex);
Log.DebugLog("replace at " + m_insertIndex + ": " + m_currentCommand.DisplayString);
}
else
Log.DebugLog("new command at " + m_insertIndex + ": " + m_currentCommand.DisplayString);
m_commandList.Insert(m_insertIndex, m_currentCommand);
}
}
m_currentCommand = null;
m_listCommands = true;
ClearMessage();
}
else
{
Log.DebugLog("failed to save command: " + m_currentCommand.DisplayString + ", reason: " + msg);
LogAndInfo(msg);
}
}
private void AddCommand(IMyTerminalBlock block)
{
Log.DebugLog("block != m_block", Logger.severity.FATAL, condition: block != m_block);
m_insertIndex = -1;
m_replace = false;
m_currentCommand = null;
m_listCommands = false;
ClearMessage();
Log.DebugLog("adding new command at end");
}
private void InsertCommand(IMyTerminalBlock block)
{
Log.DebugLog("block != m_block", Logger.severity.FATAL, condition: block != m_block);
if (m_currentCommand == null)
{
LogAndInfo("nothing selected");
return;
}
m_insertIndex = m_commandList.IndexOf(m_currentCommand);
m_replace = false;
m_currentCommand = null;
m_listCommands = false;
ClearMessage();
Log.DebugLog("inserting new command at " + m_insertIndex);
}
private void RemoveCommand(IMyTerminalBlock block)
{
Log.DebugLog("entered");
Log.DebugLog("block != m_block", Logger.severity.FATAL, condition: block != m_block);
if (m_currentCommand == null)
{
LogAndInfo("nothing selected");
return;
}
m_commandList.Remove(m_currentCommand);
m_currentCommand = null;
ClearMessage();
}
private void EditCommand(IMyTerminalBlock block)
{
Log.DebugLog("block != m_block", Logger.severity.FATAL, condition: block != m_block);
if (m_currentCommand == null)
{
LogAndInfo("nothing selected");
return;
}
if (!m_currentCommand.HasControls)
{
LogAndInfo("This command cannot be edited");
return;
}
Log.DebugLog("editing: " + m_currentCommand.DisplayString);
m_insertIndex = m_commandList.IndexOf(m_currentCommand);
m_replace = true;
m_currentCommand = m_currentCommand.Clone();
m_listCommands = false;
ClearMessage();
}
private void MoveCommandUp(IMyTerminalBlock block)
{
Log.DebugLog("block != m_block", Logger.severity.FATAL, condition: block != m_block);
if (m_currentCommand == null)
{
LogAndInfo("nothing selected");
return;
}
int index = m_commandList.IndexOf(m_currentCommand);
if (index == 0)
{
LogAndInfo("already first element: " + m_currentCommand.DisplayString);
return;
}
Log.DebugLog("moved up: " + m_currentCommand.DisplayString);
m_commandList.Swap(index, index - 1);
ClearMessage();
}
private void MoveCommandDown(IMyTerminalBlock block)
{
Log.DebugLog("block != m_block", Logger.severity.FATAL, condition: block != m_block);
if (m_currentCommand == null)
{
LogAndInfo("nothing selected");
return;
}
int index = m_commandList.IndexOf(m_currentCommand);
if (index == m_commandList.Count - 1)
{
LogAndInfo("already last element: " + m_currentCommand.DisplayString);
return;
}
Log.DebugLog("moved down: " + m_currentCommand.DisplayString);
m_commandList.Swap(index, index + 1);
ClearMessage();
}
private void Finished(bool save)
{
Log.DebugLog("entered");
if (save)
{
Commands = string.Join(" ; ", m_commandList.Select(cmd => cmd.DisplayString));
AutopilotTerminal.SetAutopilotCommands(m_block, new StringBuilder(Commands));
m_actionList.Clear();
GetActions(Commands, m_actionList);
}
MyTerminalControls.Static.CustomControlGetter -= CustomControlGetter;
m_block.AppendingCustomInfo -= m_block_AppendingCustomInfo;
m_block.UpdateCustomInfo();
m_block.RebuildControls();
Cleanup();
}
#endregion Button Action
private void LogAndInfo(string message, [CallerMemberName] string member = null, [CallerLineNumber] int lineNumber = 0)
{
Log.DebugLog(message, member: member, lineNumber: lineNumber);
m_infoMessage = message;
m_block.UpdateCustomInfo();
m_block.RebuildControls();
}
private void ClearMessage()
{
m_infoMessage = null;
m_block.UpdateCustomInfo();
m_block.RebuildControls();
}
private void m_block_AppendingCustomInfo(IMyTerminalBlock arg1, StringBuilder arg2)
{
Log.DebugLog("entered");
if (!string.IsNullOrWhiteSpace(m_infoMessage))
{
Log.DebugLog("appending info message: " + m_infoMessage);
arg2.AppendLine();
arg2.AppendLine(m_infoMessage);
}
if (!m_listCommands && m_currentCommand != null)
{
Log.DebugLog("appending command info");
arg2.AppendLine();
m_currentCommand.AppendCustomInfo(arg2);
arg2.AppendLine();
}
}
private void m_block_AppendSyntaxErrors(IMyTerminalBlock arg1, StringBuilder arg2)
{
if (m_syntaxErrors.Length != 0)
{
Log.DebugLog("appending syntax errors");
arg2.AppendLine();
arg2.Append("Syntax Errors:\n");
arg2.Append(m_syntaxErrors);
}
}
private void Cleanup()
{
m_commandList.Clear();
m_infoMessage = null;
m_termCommandList = null;
m_currentCommand = null;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Insights;
using Microsoft.Azure.Insights.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Insights
{
/// <summary>
/// Microsoft Azure event logs and summaries can be retrieved using these
/// operations
/// </summary>
internal partial class EventOperations : IServiceOperations<InsightsClient>, IEventOperations
{
/// <summary>
/// Initializes a new instance of the EventOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal EventOperations(InsightsClient client)
{
this._client = client;
}
private InsightsClient _client;
/// <summary>
/// Gets a reference to the Microsoft.Azure.Insights.InsightsClient.
/// </summary>
public InsightsClient Client
{
get { return this._client; }
}
/// <summary>
/// The count of events in a subscription.
/// </summary>
/// <param name='filterString'>
/// Required. The filter string should be generated using
/// Microsoft.WindowsAzure.Common.OData.FilterStringHere is an
/// example:var filterString =
/// FilterString.Generate<GetCountSummaryParameters> (p =>
/// (p.StartTime == startTime) && p.EndTime == endTime);
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The event count summary response.
/// </returns>
public async Task<EventCountSummaryResponse> GetCountSummaryAsync(string filterString, CancellationToken cancellationToken)
{
// Validate
if (filterString == null)
{
throw new ArgumentNullException("filterString");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("filterString", filterString);
Tracing.Enter(invocationId, this, "GetCountSummaryAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/providers/microsoft.insights/eventtypes/management/summaries/count?";
url = url + "api-version=2014-04-01";
url = url + "&$filter=" + Uri.EscapeDataString(filterString.Trim());
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
EventCountSummaryResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EventCountSummaryResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken eventPropertyNameValue = responseDoc["eventPropertyName"];
if (eventPropertyNameValue != null && eventPropertyNameValue.Type != JTokenType.Null)
{
string eventPropertyNameInstance = ((string)eventPropertyNameValue);
result.EventPropertyName = eventPropertyNameInstance;
}
JToken eventPropertyValueValue = responseDoc["eventPropertyValue"];
if (eventPropertyValueValue != null && eventPropertyValueValue.Type != JTokenType.Null)
{
string eventPropertyValueInstance = ((string)eventPropertyValueValue);
result.EventPropertyValue = eventPropertyValueInstance;
}
JToken startTimeValue = responseDoc["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
result.StartTime = startTimeInstance;
}
JToken endTimeValue = responseDoc["endTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTime endTimeInstance = ((DateTime)endTimeValue);
result.EndTime = endTimeInstance;
}
JToken timeGrainValue = responseDoc["timeGrain"];
if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
{
TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan(((string)timeGrainValue));
result.TimeGrain = timeGrainInstance;
}
JToken summaryItemsArray = responseDoc["summaryItems"];
if (summaryItemsArray != null && summaryItemsArray.Type != JTokenType.Null)
{
foreach (JToken summaryItemsValue in ((JArray)summaryItemsArray))
{
CountSummaryItem countSummaryItemInstance = new CountSummaryItem();
result.SummaryItems.Add(countSummaryItemInstance);
JToken eventTimeValue = summaryItemsValue["eventTime"];
if (eventTimeValue != null && eventTimeValue.Type != JTokenType.Null)
{
DateTime eventTimeInstance = ((DateTime)eventTimeValue);
countSummaryItemInstance.EventTime = eventTimeInstance;
}
JToken totalEventsCountValue = summaryItemsValue["totalEventsCount"];
if (totalEventsCountValue != null && totalEventsCountValue.Type != JTokenType.Null)
{
int totalEventsCountInstance = ((int)totalEventsCountValue);
countSummaryItemInstance.TotalEventsCount = totalEventsCountInstance;
}
JToken failedEventsCountValue = summaryItemsValue["failedEventsCount"];
if (failedEventsCountValue != null && failedEventsCountValue.Type != JTokenType.Null)
{
int failedEventsCountInstance = ((int)failedEventsCountValue);
countSummaryItemInstance.FailedEventsCount = failedEventsCountInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Event Values operation lists the events.
/// </summary>
/// <param name='filterString'>
/// Required. The filter string should be generated using
/// Microsoft.WindowsAzure.Common.OData.FilterStringHere is an
/// example:var filterString =
/// FilterString.Generate<GetCountSummaryParameters> (p =>
/// (p.StartTime == startTime) && p.EndTime == endTime);
/// </param>
/// <param name='selectedProperties'>
/// Optional. The list of property names to be returned. You can save
/// bandwidth by selecting only the properties you need.Here is an
/// example:string selectedProperties = "EventDataId, EventTimestamp,
/// ResourceUri"
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Events operation response.
/// </returns>
public async Task<EventDataListResponse> ListEventsAsync(string filterString, string selectedProperties, CancellationToken cancellationToken)
{
// Validate
if (filterString == null)
{
throw new ArgumentNullException("filterString");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("filterString", filterString);
tracingParameters.Add("selectedProperties", selectedProperties);
Tracing.Enter(invocationId, this, "ListEventsAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/providers/microsoft.insights/eventtypes/management/values?";
url = url + "api-version=2014-04-01";
url = url + "&$filter=" + Uri.EscapeDataString(filterString.Trim());
if (selectedProperties != null)
{
url = url + "&$select=" + Uri.EscapeDataString(selectedProperties != null ? selectedProperties.Trim() : "");
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
EventDataListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EventDataListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
EventDataCollection eventDataCollectionInstance = new EventDataCollection();
result.EventDataCollection = eventDataCollectionInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
EventData eventDataInstance = new EventData();
eventDataCollectionInstance.Value.Add(eventDataInstance);
JToken authorizationValue = valueValue["authorization"];
if (authorizationValue != null && authorizationValue.Type != JTokenType.Null)
{
SenderAuthorization authorizationInstance = new SenderAuthorization();
eventDataInstance.Authorization = authorizationInstance;
JToken actionValue = authorizationValue["action"];
if (actionValue != null && actionValue.Type != JTokenType.Null)
{
string actionInstance = ((string)actionValue);
authorizationInstance.Action = actionInstance;
}
JToken conditionValue = authorizationValue["condition"];
if (conditionValue != null && conditionValue.Type != JTokenType.Null)
{
string conditionInstance = ((string)conditionValue);
authorizationInstance.Condition = conditionInstance;
}
JToken roleValue = authorizationValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
authorizationInstance.Role = roleInstance;
}
JToken scopeValue = authorizationValue["scope"];
if (scopeValue != null && scopeValue.Type != JTokenType.Null)
{
string scopeInstance = ((string)scopeValue);
authorizationInstance.Scope = scopeInstance;
}
}
JToken channelsValue = valueValue["channels"];
if (channelsValue != null && channelsValue.Type != JTokenType.Null)
{
EventChannels channelsInstance = ((EventChannels)Enum.Parse(typeof(EventChannels), ((string)channelsValue), true));
eventDataInstance.EventChannels = channelsInstance;
}
JToken claimsSequenceElement = ((JToken)valueValue["claims"]);
if (claimsSequenceElement != null && claimsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in claimsSequenceElement)
{
string claimsKey = ((string)property.Name);
string claimsValue = ((string)property.Value);
eventDataInstance.Claims.Add(claimsKey, claimsValue);
}
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
eventDataInstance.Description = descriptionInstance;
}
JToken eventDataIdValue = valueValue["eventDataId"];
if (eventDataIdValue != null && eventDataIdValue.Type != JTokenType.Null)
{
string eventDataIdInstance = ((string)eventDataIdValue);
eventDataInstance.EventDataId = eventDataIdInstance;
}
JToken correlationIdValue = valueValue["correlationId"];
if (correlationIdValue != null && correlationIdValue.Type != JTokenType.Null)
{
string correlationIdInstance = ((string)correlationIdValue);
eventDataInstance.CorrelationId = correlationIdInstance;
}
JToken eventNameValue = valueValue["eventName"];
if (eventNameValue != null && eventNameValue.Type != JTokenType.Null)
{
LocalizableString eventNameInstance = new LocalizableString();
eventDataInstance.EventName = eventNameInstance;
JToken valueValue2 = eventNameValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
eventNameInstance.Value = valueInstance;
}
JToken localizedValueValue = eventNameValue["localizedValue"];
if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null)
{
string localizedValueInstance = ((string)localizedValueValue);
eventNameInstance.LocalizedValue = localizedValueInstance;
}
}
JToken eventSourceValue = valueValue["eventSource"];
if (eventSourceValue != null && eventSourceValue.Type != JTokenType.Null)
{
LocalizableString eventSourceInstance = new LocalizableString();
eventDataInstance.EventSource = eventSourceInstance;
JToken valueValue3 = eventSourceValue["value"];
if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue3);
eventSourceInstance.Value = valueInstance2;
}
JToken localizedValueValue2 = eventSourceValue["localizedValue"];
if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null)
{
string localizedValueInstance2 = ((string)localizedValueValue2);
eventSourceInstance.LocalizedValue = localizedValueInstance2;
}
}
JToken httpRequestValue = valueValue["httpRequest"];
if (httpRequestValue != null && httpRequestValue.Type != JTokenType.Null)
{
HttpRequestInfo httpRequestInstance = new HttpRequestInfo();
eventDataInstance.HttpRequest = httpRequestInstance;
JToken clientRequestIdValue = httpRequestValue["clientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
httpRequestInstance.ClientRequestId = clientRequestIdInstance;
}
JToken clientIpAddressValue = httpRequestValue["clientIpAddress"];
if (clientIpAddressValue != null && clientIpAddressValue.Type != JTokenType.Null)
{
string clientIpAddressInstance = ((string)clientIpAddressValue);
httpRequestInstance.ClientIpAddress = clientIpAddressInstance;
}
JToken methodValue = httpRequestValue["method"];
if (methodValue != null && methodValue.Type != JTokenType.Null)
{
string methodInstance = ((string)methodValue);
httpRequestInstance.Method = methodInstance;
}
JToken uriValue = httpRequestValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
httpRequestInstance.Uri = uriInstance;
}
}
JToken levelValue = valueValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
EventLevel levelInstance = ((EventLevel)Enum.Parse(typeof(EventLevel), ((string)levelValue), true));
eventDataInstance.Level = levelInstance;
}
JToken resourceGroupNameValue = valueValue["resourceGroupName"];
if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null)
{
string resourceGroupNameInstance = ((string)resourceGroupNameValue);
eventDataInstance.ResourceGroupName = resourceGroupNameInstance;
}
JToken resourceProviderNameValue = valueValue["resourceProviderName"];
if (resourceProviderNameValue != null && resourceProviderNameValue.Type != JTokenType.Null)
{
LocalizableString resourceProviderNameInstance = new LocalizableString();
eventDataInstance.ResourceProviderName = resourceProviderNameInstance;
JToken valueValue4 = resourceProviderNameValue["value"];
if (valueValue4 != null && valueValue4.Type != JTokenType.Null)
{
string valueInstance3 = ((string)valueValue4);
resourceProviderNameInstance.Value = valueInstance3;
}
JToken localizedValueValue3 = resourceProviderNameValue["localizedValue"];
if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null)
{
string localizedValueInstance3 = ((string)localizedValueValue3);
resourceProviderNameInstance.LocalizedValue = localizedValueInstance3;
}
}
JToken resourceUriValue = valueValue["resourceUri"];
if (resourceUriValue != null && resourceUriValue.Type != JTokenType.Null)
{
string resourceUriInstance = ((string)resourceUriValue);
eventDataInstance.ResourceUri = resourceUriInstance;
}
JToken operationIdValue = valueValue["operationId"];
if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
{
string operationIdInstance = ((string)operationIdValue);
eventDataInstance.OperationId = operationIdInstance;
}
JToken operationNameValue = valueValue["operationName"];
if (operationNameValue != null && operationNameValue.Type != JTokenType.Null)
{
LocalizableString operationNameInstance = new LocalizableString();
eventDataInstance.OperationName = operationNameInstance;
JToken valueValue5 = operationNameValue["value"];
if (valueValue5 != null && valueValue5.Type != JTokenType.Null)
{
string valueInstance4 = ((string)valueValue5);
operationNameInstance.Value = valueInstance4;
}
JToken localizedValueValue4 = operationNameValue["localizedValue"];
if (localizedValueValue4 != null && localizedValueValue4.Type != JTokenType.Null)
{
string localizedValueInstance4 = ((string)localizedValueValue4);
operationNameInstance.LocalizedValue = localizedValueInstance4;
}
}
JToken propertiesSequenceElement = ((JToken)valueValue["properties"]);
if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property2 in propertiesSequenceElement)
{
string propertiesKey = ((string)property2.Name);
string propertiesValue = ((string)property2.Value);
eventDataInstance.Properties.Add(propertiesKey, propertiesValue);
}
}
JToken statusValue = valueValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
LocalizableString statusInstance = new LocalizableString();
eventDataInstance.Status = statusInstance;
JToken valueValue6 = statusValue["value"];
if (valueValue6 != null && valueValue6.Type != JTokenType.Null)
{
string valueInstance5 = ((string)valueValue6);
statusInstance.Value = valueInstance5;
}
JToken localizedValueValue5 = statusValue["localizedValue"];
if (localizedValueValue5 != null && localizedValueValue5.Type != JTokenType.Null)
{
string localizedValueInstance5 = ((string)localizedValueValue5);
statusInstance.LocalizedValue = localizedValueInstance5;
}
}
JToken subStatusValue = valueValue["subStatus"];
if (subStatusValue != null && subStatusValue.Type != JTokenType.Null)
{
LocalizableString subStatusInstance = new LocalizableString();
eventDataInstance.SubStatus = subStatusInstance;
JToken valueValue7 = subStatusValue["value"];
if (valueValue7 != null && valueValue7.Type != JTokenType.Null)
{
string valueInstance6 = ((string)valueValue7);
subStatusInstance.Value = valueInstance6;
}
JToken localizedValueValue6 = subStatusValue["localizedValue"];
if (localizedValueValue6 != null && localizedValueValue6.Type != JTokenType.Null)
{
string localizedValueInstance6 = ((string)localizedValueValue6);
subStatusInstance.LocalizedValue = localizedValueInstance6;
}
}
JToken eventTimestampValue = valueValue["eventTimestamp"];
if (eventTimestampValue != null && eventTimestampValue.Type != JTokenType.Null)
{
DateTime eventTimestampInstance = ((DateTime)eventTimestampValue);
eventDataInstance.EventTimestamp = eventTimestampInstance;
}
JToken submissionTimestampValue = valueValue["submissionTimestamp"];
if (submissionTimestampValue != null && submissionTimestampValue.Type != JTokenType.Null)
{
DateTime submissionTimestampInstance = ((DateTime)submissionTimestampValue);
eventDataInstance.SubmissionTimestamp = submissionTimestampInstance;
}
JToken subscriptionIdValue = valueValue["subscriptionId"];
if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
{
string subscriptionIdInstance = ((string)subscriptionIdValue);
eventDataInstance.SubscriptionId = subscriptionIdInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
eventDataCollectionInstance.NextLink = nextLinkInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Event Next operation lists the next set of events.
/// </summary>
/// <param name='nextLink'>
/// Required. The next link works as a continuation token when all of
/// the events are not returned in the response and a second call is
/// required
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Events operation response.
/// </returns>
public async Task<EventDataListResponse> ListEventsNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
Tracing.Enter(invocationId, this, "ListEventsNextAsync", tracingParameters);
}
// Construct URL
string url = nextLink.Trim();
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
EventDataListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EventDataListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
EventDataCollection eventDataCollectionInstance = new EventDataCollection();
result.EventDataCollection = eventDataCollectionInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
EventData eventDataInstance = new EventData();
eventDataCollectionInstance.Value.Add(eventDataInstance);
JToken authorizationValue = valueValue["authorization"];
if (authorizationValue != null && authorizationValue.Type != JTokenType.Null)
{
SenderAuthorization authorizationInstance = new SenderAuthorization();
eventDataInstance.Authorization = authorizationInstance;
JToken actionValue = authorizationValue["action"];
if (actionValue != null && actionValue.Type != JTokenType.Null)
{
string actionInstance = ((string)actionValue);
authorizationInstance.Action = actionInstance;
}
JToken conditionValue = authorizationValue["condition"];
if (conditionValue != null && conditionValue.Type != JTokenType.Null)
{
string conditionInstance = ((string)conditionValue);
authorizationInstance.Condition = conditionInstance;
}
JToken roleValue = authorizationValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
authorizationInstance.Role = roleInstance;
}
JToken scopeValue = authorizationValue["scope"];
if (scopeValue != null && scopeValue.Type != JTokenType.Null)
{
string scopeInstance = ((string)scopeValue);
authorizationInstance.Scope = scopeInstance;
}
}
JToken channelsValue = valueValue["channels"];
if (channelsValue != null && channelsValue.Type != JTokenType.Null)
{
EventChannels channelsInstance = ((EventChannels)Enum.Parse(typeof(EventChannels), ((string)channelsValue), true));
eventDataInstance.EventChannels = channelsInstance;
}
JToken claimsSequenceElement = ((JToken)valueValue["claims"]);
if (claimsSequenceElement != null && claimsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in claimsSequenceElement)
{
string claimsKey = ((string)property.Name);
string claimsValue = ((string)property.Value);
eventDataInstance.Claims.Add(claimsKey, claimsValue);
}
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
eventDataInstance.Description = descriptionInstance;
}
JToken eventDataIdValue = valueValue["eventDataId"];
if (eventDataIdValue != null && eventDataIdValue.Type != JTokenType.Null)
{
string eventDataIdInstance = ((string)eventDataIdValue);
eventDataInstance.EventDataId = eventDataIdInstance;
}
JToken correlationIdValue = valueValue["correlationId"];
if (correlationIdValue != null && correlationIdValue.Type != JTokenType.Null)
{
string correlationIdInstance = ((string)correlationIdValue);
eventDataInstance.CorrelationId = correlationIdInstance;
}
JToken eventNameValue = valueValue["eventName"];
if (eventNameValue != null && eventNameValue.Type != JTokenType.Null)
{
LocalizableString eventNameInstance = new LocalizableString();
eventDataInstance.EventName = eventNameInstance;
JToken valueValue2 = eventNameValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
eventNameInstance.Value = valueInstance;
}
JToken localizedValueValue = eventNameValue["localizedValue"];
if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null)
{
string localizedValueInstance = ((string)localizedValueValue);
eventNameInstance.LocalizedValue = localizedValueInstance;
}
}
JToken eventSourceValue = valueValue["eventSource"];
if (eventSourceValue != null && eventSourceValue.Type != JTokenType.Null)
{
LocalizableString eventSourceInstance = new LocalizableString();
eventDataInstance.EventSource = eventSourceInstance;
JToken valueValue3 = eventSourceValue["value"];
if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue3);
eventSourceInstance.Value = valueInstance2;
}
JToken localizedValueValue2 = eventSourceValue["localizedValue"];
if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null)
{
string localizedValueInstance2 = ((string)localizedValueValue2);
eventSourceInstance.LocalizedValue = localizedValueInstance2;
}
}
JToken httpRequestValue = valueValue["httpRequest"];
if (httpRequestValue != null && httpRequestValue.Type != JTokenType.Null)
{
HttpRequestInfo httpRequestInstance = new HttpRequestInfo();
eventDataInstance.HttpRequest = httpRequestInstance;
JToken clientRequestIdValue = httpRequestValue["clientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
httpRequestInstance.ClientRequestId = clientRequestIdInstance;
}
JToken clientIpAddressValue = httpRequestValue["clientIpAddress"];
if (clientIpAddressValue != null && clientIpAddressValue.Type != JTokenType.Null)
{
string clientIpAddressInstance = ((string)clientIpAddressValue);
httpRequestInstance.ClientIpAddress = clientIpAddressInstance;
}
JToken methodValue = httpRequestValue["method"];
if (methodValue != null && methodValue.Type != JTokenType.Null)
{
string methodInstance = ((string)methodValue);
httpRequestInstance.Method = methodInstance;
}
JToken uriValue = httpRequestValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
httpRequestInstance.Uri = uriInstance;
}
}
JToken levelValue = valueValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
EventLevel levelInstance = ((EventLevel)Enum.Parse(typeof(EventLevel), ((string)levelValue), true));
eventDataInstance.Level = levelInstance;
}
JToken resourceGroupNameValue = valueValue["resourceGroupName"];
if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null)
{
string resourceGroupNameInstance = ((string)resourceGroupNameValue);
eventDataInstance.ResourceGroupName = resourceGroupNameInstance;
}
JToken resourceProviderNameValue = valueValue["resourceProviderName"];
if (resourceProviderNameValue != null && resourceProviderNameValue.Type != JTokenType.Null)
{
LocalizableString resourceProviderNameInstance = new LocalizableString();
eventDataInstance.ResourceProviderName = resourceProviderNameInstance;
JToken valueValue4 = resourceProviderNameValue["value"];
if (valueValue4 != null && valueValue4.Type != JTokenType.Null)
{
string valueInstance3 = ((string)valueValue4);
resourceProviderNameInstance.Value = valueInstance3;
}
JToken localizedValueValue3 = resourceProviderNameValue["localizedValue"];
if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null)
{
string localizedValueInstance3 = ((string)localizedValueValue3);
resourceProviderNameInstance.LocalizedValue = localizedValueInstance3;
}
}
JToken resourceUriValue = valueValue["resourceUri"];
if (resourceUriValue != null && resourceUriValue.Type != JTokenType.Null)
{
string resourceUriInstance = ((string)resourceUriValue);
eventDataInstance.ResourceUri = resourceUriInstance;
}
JToken operationIdValue = valueValue["operationId"];
if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
{
string operationIdInstance = ((string)operationIdValue);
eventDataInstance.OperationId = operationIdInstance;
}
JToken operationNameValue = valueValue["operationName"];
if (operationNameValue != null && operationNameValue.Type != JTokenType.Null)
{
LocalizableString operationNameInstance = new LocalizableString();
eventDataInstance.OperationName = operationNameInstance;
JToken valueValue5 = operationNameValue["value"];
if (valueValue5 != null && valueValue5.Type != JTokenType.Null)
{
string valueInstance4 = ((string)valueValue5);
operationNameInstance.Value = valueInstance4;
}
JToken localizedValueValue4 = operationNameValue["localizedValue"];
if (localizedValueValue4 != null && localizedValueValue4.Type != JTokenType.Null)
{
string localizedValueInstance4 = ((string)localizedValueValue4);
operationNameInstance.LocalizedValue = localizedValueInstance4;
}
}
JToken propertiesSequenceElement = ((JToken)valueValue["properties"]);
if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property2 in propertiesSequenceElement)
{
string propertiesKey = ((string)property2.Name);
string propertiesValue = ((string)property2.Value);
eventDataInstance.Properties.Add(propertiesKey, propertiesValue);
}
}
JToken statusValue = valueValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
LocalizableString statusInstance = new LocalizableString();
eventDataInstance.Status = statusInstance;
JToken valueValue6 = statusValue["value"];
if (valueValue6 != null && valueValue6.Type != JTokenType.Null)
{
string valueInstance5 = ((string)valueValue6);
statusInstance.Value = valueInstance5;
}
JToken localizedValueValue5 = statusValue["localizedValue"];
if (localizedValueValue5 != null && localizedValueValue5.Type != JTokenType.Null)
{
string localizedValueInstance5 = ((string)localizedValueValue5);
statusInstance.LocalizedValue = localizedValueInstance5;
}
}
JToken subStatusValue = valueValue["subStatus"];
if (subStatusValue != null && subStatusValue.Type != JTokenType.Null)
{
LocalizableString subStatusInstance = new LocalizableString();
eventDataInstance.SubStatus = subStatusInstance;
JToken valueValue7 = subStatusValue["value"];
if (valueValue7 != null && valueValue7.Type != JTokenType.Null)
{
string valueInstance6 = ((string)valueValue7);
subStatusInstance.Value = valueInstance6;
}
JToken localizedValueValue6 = subStatusValue["localizedValue"];
if (localizedValueValue6 != null && localizedValueValue6.Type != JTokenType.Null)
{
string localizedValueInstance6 = ((string)localizedValueValue6);
subStatusInstance.LocalizedValue = localizedValueInstance6;
}
}
JToken eventTimestampValue = valueValue["eventTimestamp"];
if (eventTimestampValue != null && eventTimestampValue.Type != JTokenType.Null)
{
DateTime eventTimestampInstance = ((DateTime)eventTimestampValue);
eventDataInstance.EventTimestamp = eventTimestampInstance;
}
JToken submissionTimestampValue = valueValue["submissionTimestamp"];
if (submissionTimestampValue != null && submissionTimestampValue.Type != JTokenType.Null)
{
DateTime submissionTimestampInstance = ((DateTime)submissionTimestampValue);
eventDataInstance.SubmissionTimestamp = submissionTimestampInstance;
}
JToken subscriptionIdValue = valueValue["subscriptionId"];
if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
{
string subscriptionIdInstance = ((string)subscriptionIdValue);
eventDataInstance.SubscriptionId = subscriptionIdInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
eventDataCollectionInstance.NextLink = nextLinkInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Lucene.Net.Analysis;
using Version = Lucene.Net.Util.Version;
namespace Lucene.Net.Analysis.Standard
{
/// <summary> Filters {@link StandardTokenizer} with {@link StandardFilter},
/// {@link LowerCaseFilter} and {@link StopFilter}, using a list of English stop
/// words.
///
/// <a name="version"/>
/// <p/>
/// You must specify the required {@link Version} compatibility when creating
/// StandardAnalyzer:
/// <ul>
/// <li>As of 2.9, StopFilter preserves position increments</li>
/// <li>As of 2.4, Tokens incorrectly identified as acronyms are corrected (see
/// <a href="https://issues.apache.org/jira/browse/LUCENE-1068">LUCENE-1608</a></li>
/// </ul>
///
/// </summary>
/// <version> $Id: StandardAnalyzer.java 829134 2009-10-23 17:18:53Z mikemccand $
/// </version>
public class StandardAnalyzer : Analyzer
{
private System.Collections.Hashtable stopSet;
/// <summary> Specifies whether deprecated acronyms should be replaced with HOST type.
/// This is false by default to support backward compatibility.
///
/// </summary>
/// <deprecated> this should be removed in the next release (3.0).
///
/// See https://issues.apache.org/jira/browse/LUCENE-1068
/// </deprecated>
[Obsolete("this should be removed in the next release (3.0).")]
private bool replaceInvalidAcronym = defaultReplaceInvalidAcronym;
private static bool defaultReplaceInvalidAcronym;
private bool enableStopPositionIncrements;
// @deprecated
[Obsolete]
private bool useDefaultStopPositionIncrements;
/// <summary> </summary>
/// <returns> true if new instances of StandardTokenizer will
/// replace mischaracterized acronyms
///
/// See https://issues.apache.org/jira/browse/LUCENE-1068
/// </returns>
/// <deprecated> This will be removed (hardwired to true) in 3.0
/// </deprecated>
[Obsolete("This will be removed (hardwired to true) in 3.0")]
public static bool GetDefaultReplaceInvalidAcronym()
{
return defaultReplaceInvalidAcronym;
}
/// <summary> </summary>
/// <param name="replaceInvalidAcronym">Set to true to have new
/// instances of StandardTokenizer replace mischaracterized
/// acronyms by default. Set to false to preserve the
/// previous (before 2.4) buggy behavior. Alternatively,
/// set the system property
/// Lucene.Net.Analysis.Standard.StandardAnalyzer.replaceInvalidAcronym
/// to false.
///
/// See https://issues.apache.org/jira/browse/LUCENE-1068
/// </param>
/// <deprecated> This will be removed (hardwired to true) in 3.0
/// </deprecated>
[Obsolete("This will be removed (hardwired to true) in 3.0")]
public static void SetDefaultReplaceInvalidAcronym(bool replaceInvalidAcronym)
{
defaultReplaceInvalidAcronym = replaceInvalidAcronym;
}
/// <summary>An array containing some common English words that are usually not
/// useful for searching.
/// </summary>
/// <deprecated> Use {@link #STOP_WORDS_SET} instead
/// </deprecated>
[Obsolete("Use STOP_WORDS_SET instead ")]
public static readonly System.String[] STOP_WORDS;
/// <summary>An unmodifiable set containing some common English words that are usually not
/// useful for searching.
/// </summary>
public static readonly System.Collections.Hashtable STOP_WORDS_SET;
/// <summary>Builds an analyzer with the default stop words ({@link
/// #STOP_WORDS_SET}).
/// </summary>
/// <deprecated> Use {@link #StandardAnalyzer(Version)} instead.
/// </deprecated>
[Obsolete("Use StandardAnalyzer(Version) instead")]
public StandardAnalyzer():this(Version.LUCENE_24, STOP_WORDS_SET)
{
}
/// <summary>Builds an analyzer with the default stop words ({@link
/// #STOP_WORDS}).
/// </summary>
/// <param name="matchVersion">Lucene version to match See {@link
/// <a href="#version">above</a>}
/// </param>
public StandardAnalyzer(Version matchVersion):this(matchVersion, STOP_WORDS_SET)
{
}
/// <summary>Builds an analyzer with the given stop words.</summary>
/// <deprecated> Use {@link #StandardAnalyzer(Version, Set)}
/// instead
/// </deprecated>
[Obsolete("Use StandardAnalyzer(Version, Set) instead")]
public StandardAnalyzer(System.Collections.Hashtable stopWords):this(Version.LUCENE_24, stopWords)
{
}
/// <summary>Builds an analyzer with the given stop words.</summary>
/// <param name="matchVersion">Lucene version to match See {@link
/// <a href="#version">above</a>}
/// </param>
/// <param name="stopWords">stop words
/// </param>
public StandardAnalyzer(Version matchVersion, System.Collections.Hashtable stopWords)
{
stopSet = stopWords;
Init(matchVersion);
}
/// <summary>Builds an analyzer with the given stop words.</summary>
/// <deprecated> Use {@link #StandardAnalyzer(Version, Set)} instead
/// </deprecated>
[Obsolete("Use StandardAnalyzer(Version, Set) instead")]
public StandardAnalyzer(System.String[] stopWords):this(Version.LUCENE_24, StopFilter.MakeStopSet(stopWords))
{
}
/// <summary>Builds an analyzer with the stop words from the given file.</summary>
/// <seealso cref="WordlistLoader.GetWordSet(File)">
/// </seealso>
/// <deprecated> Use {@link #StandardAnalyzer(Version, File)}
/// instead
/// </deprecated>
[Obsolete("Use StandardAnalyzer(Version, File) instead")]
public StandardAnalyzer(System.IO.FileInfo stopwords):this(Version.LUCENE_24, stopwords)
{
}
/// <summary>Builds an analyzer with the stop words from the given file.</summary>
/// <seealso cref="WordlistLoader.GetWordSet(File)">
/// </seealso>
/// <param name="matchVersion">Lucene version to match See {@link
/// <a href="#version">above</a>}
/// </param>
/// <param name="stopwords">File to read stop words from
/// </param>
public StandardAnalyzer(Version matchVersion, System.IO.FileInfo stopwords)
{
stopSet = WordlistLoader.GetWordSet(stopwords);
Init(matchVersion);
}
/// <summary>Builds an analyzer with the stop words from the given reader.</summary>
/// <seealso cref="WordlistLoader.GetWordSet(Reader)">
/// </seealso>
/// <deprecated> Use {@link #StandardAnalyzer(Version, Reader)}
/// instead
/// </deprecated>
[Obsolete("Use StandardAnalyzer(Version, Reader) instead")]
public StandardAnalyzer(System.IO.TextReader stopwords):this(Version.LUCENE_24, stopwords)
{
}
/// <summary>Builds an analyzer with the stop words from the given reader.</summary>
/// <seealso cref="WordlistLoader.GetWordSet(Reader)">
/// </seealso>
/// <param name="matchVersion">Lucene version to match See {@link
/// <a href="#version">above</a>}
/// </param>
/// <param name="stopwords">Reader to read stop words from
/// </param>
public StandardAnalyzer(Version matchVersion, System.IO.TextReader stopwords)
{
stopSet = WordlistLoader.GetWordSet(stopwords);
Init(matchVersion);
}
/// <summary> </summary>
/// <param name="replaceInvalidAcronym">Set to true if this analyzer should replace mischaracterized acronyms in the StandardTokenizer
///
/// See https://issues.apache.org/jira/browse/LUCENE-1068
///
/// </param>
/// <deprecated> Remove in 3.X and make true the only valid value
/// </deprecated>
[Obsolete("Remove in 3.X and make true the only valid value")]
public StandardAnalyzer(bool replaceInvalidAcronym):this(Version.LUCENE_24, STOP_WORDS_SET)
{
this.replaceInvalidAcronym = replaceInvalidAcronym;
useDefaultStopPositionIncrements = true;
}
/// <param name="stopwords">The stopwords to use
/// </param>
/// <param name="replaceInvalidAcronym">Set to true if this analyzer should replace mischaracterized acronyms in the StandardTokenizer
///
/// See https://issues.apache.org/jira/browse/LUCENE-1068
///
/// </param>
/// <deprecated> Remove in 3.X and make true the only valid value
/// </deprecated>
[Obsolete("Remove in 3.X and make true the only valid value")]
public StandardAnalyzer(System.IO.TextReader stopwords, bool replaceInvalidAcronym):this(Version.LUCENE_24, stopwords)
{
this.replaceInvalidAcronym = replaceInvalidAcronym;
}
/// <param name="stopwords">The stopwords to use
/// </param>
/// <param name="replaceInvalidAcronym">Set to true if this analyzer should replace mischaracterized acronyms in the StandardTokenizer
///
/// See https://issues.apache.org/jira/browse/LUCENE-1068
///
/// </param>
/// <deprecated> Remove in 3.X and make true the only valid value
/// </deprecated>
[Obsolete("Remove in 3.X and make true the only valid value")]
public StandardAnalyzer(System.IO.FileInfo stopwords, bool replaceInvalidAcronym):this(Version.LUCENE_24, stopwords)
{
this.replaceInvalidAcronym = replaceInvalidAcronym;
}
/// <summary> </summary>
/// <param name="stopwords">The stopwords to use
/// </param>
/// <param name="replaceInvalidAcronym">Set to true if this analyzer should replace mischaracterized acronyms in the StandardTokenizer
///
/// See https://issues.apache.org/jira/browse/LUCENE-1068
///
/// </param>
/// <deprecated> Remove in 3.X and make true the only valid value
/// </deprecated>
[Obsolete("Remove in 3.X and make true the only valid value")]
public StandardAnalyzer(System.String[] stopwords, bool replaceInvalidAcronym):this(Version.LUCENE_24, StopFilter.MakeStopSet(stopwords))
{
this.replaceInvalidAcronym = replaceInvalidAcronym;
}
/// <param name="stopwords">The stopwords to use
/// </param>
/// <param name="replaceInvalidAcronym">Set to true if this analyzer should replace mischaracterized acronyms in the StandardTokenizer
///
/// See https://issues.apache.org/jira/browse/LUCENE-1068
///
/// </param>
/// <deprecated> Remove in 3.X and make true the only valid value
/// </deprecated>
[Obsolete("Remove in 3.X and make true the only valid value")]
public StandardAnalyzer(System.Collections.Hashtable stopwords, bool replaceInvalidAcronym):this(Version.LUCENE_24, stopwords)
{
this.replaceInvalidAcronym = replaceInvalidAcronym;
}
private void Init(Version matchVersion)
{
SetOverridesTokenStreamMethod(typeof(StandardAnalyzer));
if (matchVersion.OnOrAfter(Version.LUCENE_29))
{
enableStopPositionIncrements = true;
}
else
{
useDefaultStopPositionIncrements = true;
}
if (matchVersion.OnOrAfter(Version.LUCENE_24))
{
replaceInvalidAcronym = defaultReplaceInvalidAcronym;
}
else
{
replaceInvalidAcronym = false;
}
}
/// <summary>Constructs a {@link StandardTokenizer} filtered by a {@link
/// StandardFilter}, a {@link LowerCaseFilter} and a {@link StopFilter}.
/// </summary>
public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader)
{
StandardTokenizer tokenStream = new StandardTokenizer(reader, replaceInvalidAcronym);
tokenStream.SetMaxTokenLength(maxTokenLength);
TokenStream result = new StandardFilter(tokenStream);
result = new LowerCaseFilter(result);
if (useDefaultStopPositionIncrements)
{
result = new StopFilter(result, stopSet);
}
else
{
result = new StopFilter(enableStopPositionIncrements, result, stopSet);
}
return result;
}
private sealed class SavedStreams
{
internal StandardTokenizer tokenStream;
internal TokenStream filteredTokenStream;
}
/// <summary>Default maximum allowed token length </summary>
public const int DEFAULT_MAX_TOKEN_LENGTH = 255;
private int maxTokenLength = DEFAULT_MAX_TOKEN_LENGTH;
/// <summary> Set maximum allowed token length. If a token is seen
/// that exceeds this length then it is discarded. This
/// setting only takes effect the next time tokenStream or
/// reusableTokenStream is called.
/// </summary>
public virtual void SetMaxTokenLength(int length)
{
maxTokenLength = length;
}
/// <seealso cref="setMaxTokenLength">
/// </seealso>
public virtual int GetMaxTokenLength()
{
return maxTokenLength;
}
/// <deprecated> Use {@link #tokenStream} instead
/// </deprecated>
[Obsolete("Use TokenStream instead")]
public override TokenStream ReusableTokenStream(System.String fieldName, System.IO.TextReader reader)
{
if (overridesTokenStreamMethod)
{
// LUCENE-1678: force fallback to tokenStream() if we
// have been subclassed and that subclass overrides
// tokenStream but not reusableTokenStream
return TokenStream(fieldName, reader);
}
SavedStreams streams = (SavedStreams) GetPreviousTokenStream();
if (streams == null)
{
streams = new SavedStreams();
SetPreviousTokenStream(streams);
streams.tokenStream = new StandardTokenizer(reader);
streams.filteredTokenStream = new StandardFilter(streams.tokenStream);
streams.filteredTokenStream = new LowerCaseFilter(streams.filteredTokenStream);
if (useDefaultStopPositionIncrements)
{
streams.filteredTokenStream = new StopFilter(streams.filteredTokenStream, stopSet);
}
else
{
streams.filteredTokenStream = new StopFilter(enableStopPositionIncrements, streams.filteredTokenStream, stopSet);
}
}
else
{
streams.tokenStream.Reset(reader);
}
streams.tokenStream.SetMaxTokenLength(maxTokenLength);
streams.tokenStream.SetReplaceInvalidAcronym(replaceInvalidAcronym);
return streams.filteredTokenStream;
}
/// <summary> </summary>
/// <returns> true if this Analyzer is replacing mischaracterized acronyms in the StandardTokenizer
///
/// See https://issues.apache.org/jira/browse/LUCENE-1068
/// </returns>
/// <deprecated> This will be removed (hardwired to true) in 3.0
/// </deprecated>
[Obsolete("This will be removed (hardwired to true) in 3.0")]
public virtual bool IsReplaceInvalidAcronym()
{
return replaceInvalidAcronym;
}
/// <summary> </summary>
/// <param name="replaceInvalidAcronym">Set to true if this Analyzer is replacing mischaracterized acronyms in the StandardTokenizer
///
/// See https://issues.apache.org/jira/browse/LUCENE-1068
/// </param>
/// <deprecated> This will be removed (hardwired to true) in 3.0
/// </deprecated>
[Obsolete("This will be removed (hardwired to true) in 3.0")]
public virtual void SetReplaceInvalidAcronym(bool replaceInvalidAcronym)
{
this.replaceInvalidAcronym = replaceInvalidAcronym;
}
static StandardAnalyzer()
{
// Default to true (fixed the bug), unless the system prop is set
{
System.String v = SupportClass.AppSettings.Get("Lucene.Net.Analysis.Standard.StandardAnalyzer.replaceInvalidAcronym", "true");
if (v == null || v.Equals("true"))
defaultReplaceInvalidAcronym = true;
else
defaultReplaceInvalidAcronym = false;
}
STOP_WORDS = StopAnalyzer.ENGLISH_STOP_WORDS;
STOP_WORDS_SET = StopAnalyzer.ENGLISH_STOP_WORDS_SET;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using DAL;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using System.Text;
using System.Web.Script.Services;
using System.Net.Mail;
using System.Configuration;
using VolmaxLauncherLibrary;
//using OpenBeast.TradeCaptureService;
using VCM.Common.Log;
/// <summary>
/// Summary description for Service
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
[ScriptService]
public class Service : System.Web.Services.WebService
{
public Service()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
#region SwaptionVolPrem
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetCurrentMarketDataVol(string UserID, string ProductID)
{
if ((AppsInfo.Instance._dirImgSID.ContainsKey("vcm_calc_swaptionVolPremStrike")) == true)
{
string ProductIDStr = Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_swaptionVolPremStrike"]);
//SwaptionVolPrem bi = (SwaptionVolPrem)BeastConn.Instance.getBeastImage(ProductIDStr, "0", "0", "0", "sp1", "vcm_calc_swaptionVolPremStrike");
DataTable dt = new DataTable();// = bi.dtVolGrid;
//return dt.SerializeTableToString();
//dt.TableName = "Table";
return UtilComman.GetJSONString(dt);
}
else
return "";
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetCurrentMarketDataPrem()
{
string ProductIDStr = Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_swaptionVolPremStrike"]);
//SwaptionVolPrem bi = (SwaptionVolPrem)BeastConn.Instance.getBeastImage(ProductIDStr, "0", "0", "0", "sp1", "vcm_calc_swaptionVolPremStrike");
DataTable dt = new DataTable();// = bi.dtPremGrid;
//return dt.SerializeTableToString();
//dt.TableName = "Table";
return UtilComman.GetJSONString(dt);
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetCurrentMarketDataStrike()
{
string ProductIDStr = Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_swaptionVolPremStrike"]);
//SwaptionVolPrem bi = (SwaptionVolPrem)BeastConn.Instance.getBeastImage(ProductIDStr, "0", "0", "0", "sp1", "vcm_calc_swaptionVolPremStrike");
DataTable dt = new DataTable();// = bi.dtStrikeGrid;
//return dt.SerializeTableToString();
//dt.TableName = "Table";
return UtilComman.GetJSONString(dt);
}
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetGridNodeIDs()
{
string ProductIDStr = Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_swaptionVolPremStrike"]);
// SwaptionVolPrem bi = (SwaptionVolPrem)BeastConn.Instance.getBeastImage(ProductIDStr, "0", "0", "0", "sp1", "vcm_calc_swaptionVolPremStrike");
DataTable dtVoldNodeIDs = new DataTable();// = bi.dtVolGridNodeIDs;
return UtilComman.GetJSONString(dtVoldNodeIDs);
}
#endregion
#region Share Calc
[WebMethod(EnableSession = true)]
public string SubmitBeastCalcAutoUrlShare(long pUserId, string pInstanceId, string pInstanceInfo, string pIpAddress, string pEmailIdList, string SenderEmail, string SenderMessage, string ClientType, string GUID, int expMinutes, bool isBulkShare)
{
string[] ValidToken = null;
string strReturnMsg = "Failed to Share. Please try again.";
string defaultLandingPage = ConfigurationManager.AppSettings["defaultLandingPage"].ToString();
string moveToPage = "SharedBeastApps.aspx";
try
{
ValidToken = ValidateAuthToken(Convert.ToString(pUserId), ClientType, GUID);
if (ValidToken[0] == "False")
{
strReturnMsg = "AuthInvalid#" + ValidToken[1];
return strReturnMsg;
}
char pSeparator = '#';
string vGuid = "";
DataTable dtTableParam = new DataTable();
DataColumn dcTmp = new DataColumn("AutoURLId");
dtTableParam.Columns.Add(dcTmp);
dcTmp = new DataColumn("AutoURL");
dtTableParam.Columns.Add(dcTmp);
dcTmp = new DataColumn("EmailId");
dtTableParam.Columns.Add(dcTmp);
DataRow _dr;
if (isBulkShare)
{
BulkShare oBulkShare = new BulkShare();
pEmailIdList = oBulkShare.GetSharedUsersList(pSeparator);
if (pEmailIdList == "-1")
{
pEmailIdList = pEmailIdList + "#No emails found to send share url";
return strReturnMsg;
}
}
else
{
pEmailIdList = pEmailIdList.Replace("\r\n", "").Replace("\n", "");
}
string[] ArrEmailIds = pEmailIdList.Split(pSeparator);
if (ArrEmailIds.Length > 0)
{
for (int i = 0; i < ArrEmailIds.Length; i++)
{
if (!string.IsNullOrEmpty(ArrEmailIds[i].Trim()))
{
vGuid = Convert.ToString(Guid.NewGuid());
_dr = dtTableParam.NewRow();
_dr["AutoURLId"] = vGuid;
_dr["AutoURL"] = defaultLandingPage + "?id=" + vGuid;
_dr["EmailId"] = ArrEmailIds[i].Trim();
dtTableParam.Rows.Add(_dr);
}
}
}
DateTime defaultStart = DateTime.UtcNow;
DateTime defaultEnd = DateTime.UtcNow.AddMinutes(expMinutes);
int defaultMinutes = expMinutes;
//Submit to DB
clsDAL oClsDAL = new clsDAL(false);
int iResult = oClsDAL.SubmitBeastCalcSharing(pUserId, dtTableParam, defaultStart, defaultEnd, moveToPage, pIpAddress, defaultMinutes, "", pInstanceId, pInstanceInfo);
//strReturnMsg = iResult == 1 ? "[{'IsSave': 'TRUE'}]" : "[{'IsSave': 'FALSE'}]";
strReturnMsg = iResult == 1 ? "Calculator shared successfully." : "Failed to Share. Please try again.";
if (iResult == 1)
{
//string vUserName = oClsDAL.GetUserNameFromUserId(pUserId);
//vUserName = vUserName.Split('#')[0];
//SendAutoUrlMail(dtTableParam, vUserName, defaultStart.ToString(), defaultEnd.ToString(), SenderEmail, pUserId, SenderMessage);
}
}
catch (Exception ex)
{
}
return strReturnMsg;
}
#endregion
#region Last Calc Open
[WebMethod(EnableSession = true)]
public void SubmitLastOpenCalc(long pUserId, string pInstanceId, string pInstanceInfo)
{
try
{
//Submit to DB
clsDAL oClsDAL = new clsDAL(false);
int iResult = oClsDAL.SubmitLastCalcDetail(pUserId, pInstanceId, pInstanceInfo);
//strReturnMsg = iResult == 1 ? "[{'IsSave': 'TRUE'}]" : "[{'IsSave': 'FALSE'}]";
//strReturnMsg = iResult == 1 ? "Calculator shared successfully." : "Failed to Share. Please try again.";
}
catch (Exception ex)
{
}
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetLastOpenCalc(string UserId, string ClientType, string GUID)
{
string calcDetails = "";
DataSet ds = null;
ds = new DataSet();
DataTable dt = new DataTable();
try
{
string[] ValidToken = null;
//ValidToken = ValidateAuthToken(Convert.ToString(UserId.Replace('\"', ' ').Trim()), ClientType.Replace('\"', ' ').Trim(), GUID.Replace('\"', ' ').Trim());
//if (ValidToken[0] == "False")
//{
// dt.Columns.Add("InstanceId");
// dt.Columns.Add("InstanceInfo");
// dt.Rows.Add("False", ValidToken[1]);
// dt.TableName = "d";
//}
//else
//{
DataSet dsnew = null;
dsnew = new DataSet();
clsDAL oClsDAL = new clsDAL(false);
ds = oClsDAL.GetLastCalcDetail(Convert.ToInt64(UserId.Replace('\"', ' ').Trim()));
dt = ds.Tables[0];
// }
return UtilComman.GetJSONString(dt);
}
catch (Exception ex)
{
ds = null;
dt = null;
}
finally
{
ds = null;
dt = null;
}
return calcDetails;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetMainMenuCategory(string UserId, string ClientType, string GUID)
{
string calcDetails = "";
DataSet ds = new DataSet();
try
{
string[] ValidToken = null;
ValidToken = ValidateAuthToken(Convert.ToString(UserId.Replace('\"', ' ').Trim()), ClientType.Replace('\"', ' ').Trim(), GUID.Replace('\"', ' ').Trim());
if (ValidToken[0] == "False")
{
DataTable dt = new DataTable();
dt.Columns.Add("CategoryId");
dt.Columns.Add("CategoryName");
dt.Rows.Add("False", ValidToken[1]);
dt.TableName = "d";
ds.Tables.Add(dt);
}
else
{
clsDAL oClsDAL = new clsDAL(false);
ds = oClsDAL.GetMenuCategoryDetail(1, 0, Convert.ToInt64(UserId.Replace('\"', ' ').Trim()));
}
return UtilComman.GetJSONString(ds.Tables[0]);
}
catch (Exception ex)
{
}
return calcDetails;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetSubMenuCategory(string CategoryId, string UserId, string ClientType, string GUID)
{
string calcDetails = "";
DataSet ds = new DataSet();
try
{
string[] ValidToken = null;
ValidToken = ValidateAuthToken(Convert.ToString(UserId.Replace('\"', ' ').Trim()), ClientType.Replace('\"', ' ').Trim(), GUID.Replace('\"', ' ').Trim());
if (ValidToken[0] == "False")
{
DataTable dt = new DataTable();
dt.Columns.Add("AppName");
dt.Columns.Add("AppTitle");
dt.Rows.Add("False", ValidToken[1]);
dt.TableName = "d";
ds.Tables.Add(dt);
}
else
{
clsDAL oClsDAL = new clsDAL(false);
if (CategoryId != "null")
// ds = oClsDAL.GetSubMenCategoryDetail(null, Convert.ToInt64(UserId.Replace('\"', ' ').Trim()));
ds = oClsDAL.GetSubMenCategoryDetail(Convert.ToInt32(CategoryId.Replace('\"', ' ').Trim()), Convert.ToInt64(UserId.Replace('\"', ' ').Trim()));
else
ds = oClsDAL.GetSubMenCategoryDetail(null, Convert.ToInt64(UserId.Replace('\"', ' ').Trim()));
}
return UtilComman.GetJSONString(ds.Tables[0]);
}
catch (Exception ex)
{
}
return calcDetails;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetSubMenuCategoryVendorWise(string VendorId, string UserId, string ClientType, string GUID)
{
string calcDetails = "";
DataSet ds = new DataSet();
try
{
string[] ValidToken = null;
ValidToken = ValidateAuthToken(Convert.ToString(UserId.Replace('\"', ' ').Trim()), ClientType.Replace('\"', ' ').Trim(), GUID.Replace('\"', ' ').Trim());
if (ValidToken[0] == "False")
{
DataTable dt = new DataTable();
dt.Columns.Add("AppName");
dt.Columns.Add("AppTitle");
dt.Rows.Add("False", ValidToken[1]);
dt.TableName = "d";
ds.Tables.Add(dt);
}
else
{
clsDAL oClsDAL = new clsDAL(false);
if (VendorId != "null")
// ds = oClsDAL.GetSubMenCategoryDetail(null, Convert.ToInt64(UserId.Replace('\"', ' ').Trim()));
ds = oClsDAL.GetSubMenCategoryDetailVendorWise(Convert.ToInt32(VendorId.Replace('\"', ' ').Trim()), Convert.ToInt64(UserId.Replace('\"', ' ').Trim()));
else
ds = oClsDAL.GetSubMenCategoryDetailVendorWise(null, Convert.ToInt64(UserId.Replace('\"', ' ').Trim()));
}
return UtilComman.GetJSONString(ds.Tables[0]);
}
catch (Exception ex)
{
}
return calcDetails;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetLastOpenAppName(string InstanceId, string ClientType, string GUID, string UserId)
{
string calcDetails = "";
DataSet ds = new DataSet();
try
{
string[] ValidToken = null;
ValidToken = ValidateAuthToken(Convert.ToString(UserId.Replace('\"', ' ').Trim()), ClientType.Replace('\"', ' ').Trim(), GUID.Replace('\"', ' ').Trim());
if (ValidToken[0] == "False")
{
DataTable dt = new DataTable();
dt.Columns.Add("CategoryId");
dt.Columns.Add("Message");
dt.Rows.Add("False", ValidToken[1]);
dt.TableName = "d";
ds.Tables.Add(dt);
}
else
{
clsDAL oClsDAL = new clsDAL(false);
ds = oClsDAL.GetLastOpenAppNameDetail(InstanceId.Replace('\"', ' ').Trim());
}
return UtilComman.GetJSONString(ds.Tables[0]);
}
catch (Exception ex)
{
}
return calcDetails;
}
//Excel
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public DataSet Excel_GetMainMenuCategory(string UserId, string ClientType, string GUID)
{
DataSet ds = null;
try
{
string[] ValidToken = null;
ValidToken = ValidateAuthToken(Convert.ToString(UserId.Replace('\"', ' ').Trim()), ClientType.Replace('\"', ' ').Trim(), GUID.Replace('\"', ' ').Trim());
if (ValidToken[0] == "False")
{
DataTable dt = new DataTable();
dt.Columns.Add("CategoryId");
dt.Columns.Add("CategoryName");
dt.Rows.Add("False", ValidToken[1]);
dt.TableName = "d";
ds.Tables.Add(dt);
}
else
{
clsDAL oClsDAL = new clsDAL(false);
ds = oClsDAL.GetMenuCategoryDetail(1, 0, Convert.ToInt64(UserId.Replace('\"', ' ').Trim()));
}
}
catch (Exception ex)
{
}
return ds;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public DataSet Excel_GetSubMenuCategory(string CategoryId, string UserId, string ClientType, string GUID)
{
DataSet ds = null;
try
{
string[] ValidToken = null;
ValidToken = ValidateAuthToken(Convert.ToString(UserId.Replace('\"', ' ').Trim()), ClientType.Replace('\"', ' ').Trim(), GUID.Replace('\"', ' ').Trim());
if (ValidToken[0] != "False")
{
clsDAL oClsDAL = new clsDAL(false);
ds = oClsDAL.GetSubMenCategoryDetail(Convert.ToInt32(CategoryId.Replace('\"', ' ').Trim()), Convert.ToInt64(UserId.Replace('\"', ' ').Trim()));
}
}
catch (Exception ex)
{
string str = "CategoryId=" + CategoryId + ";UserId" + UserId + ";GUID" + GUID;
LogUtility.Error("Service.asmx.cs", "Excel_GetSubMenuCategory", "Inner excp:" + ex.InnerException.ToString() + ";Parameter Value:" + str, ex);
}
return ds;
}
#endregion
private void SendAutoUrlMail(DataTable tblUserList, string pUserName, string fromTm, string toDtTm, string SenderEmail, long pUserId, string SenderMessage)
{
try
{
string strSubject = "The BEAST Financial Framework - Shared AutoURL";
string _customMessage = string.IsNullOrEmpty(SenderMessage.Trim()) ? "" : "<p><div style=\"border-top:1px dashed Gray;border-bottom:1px dashed Gray;padding:3px 0px;\">Note from " + pUserName + " : <br/> " + SenderMessage + " </div></p>";
//_customMessage +
string strMailBody = "<div style=\"color:navy;font:normal 12px verdana\"><p>Dear User,</p><p>A BEAST Calculator has been shared with you by our customer " + pUserName + ".</p>" +
"<p>You may access <strong>The BEAST Apps</strong> by clicking on the following URL. You may copy and paste this URL in your browser as well.</p>" +
"<p><a href=\"[AUTOURL]\">[AUTOURL]</a></p>" +
"<p>This URL is valid as follows:</p> " +
"<p>User: " + pUserName + "<br/>" +
"URL Valid for: " + Convert.ToDateTime(fromTm).ToString("dd-MMM-yyyy hh:mm:ss tt") + " GMT To " + Convert.ToDateTime(toDtTm).ToString("dd-MMM-yyyy hh:mm:ss tt") + " GMT</p>" +
"<p> <b>NOTE:</b><b><i> Please treat this URL confidential as this URL will give the recipient an access to your account.</i></b></p>" +
"<p>If you do not wish to receive these URLs, please let us know.</p>" +
"<p>Please contact us if you have any questions.<br/><br/></p>" +
UtilityHandler.VCM_MailAddress_In_Html +
"</div>";
string tmplateBody = "";
for (int i = 0; i < tblUserList.Rows.Count; i++)
{
tmplateBody = strMailBody.Replace("[AUTOURL]", Convert.ToString(tblUserList.Rows[i]["AutoURL"]));
UtilityHandler.SendMail(Convert.ToString(tblUserList.Rows[i]["EmailId"]), "", "", strSubject, tmplateBody, false);
}
/*Summary mail to initiator*/
bool _isImp = false;
strSubject = "The BEAST Financial Framework - Calculator Shared";
_customMessage = string.IsNullOrEmpty(SenderMessage.Trim()) ? "" : "<p><div style=\"border-top:1px dashed Gray;border-bottom:1px dashed Gray;padding:3px 0px;\">Your message : <br/> " + SenderMessage + " </div></p>";
strMailBody = "<div style=\"color:navy;font:normal 12px verdana\"><p>Dear " + pUserName + ",</p>"
+ "<p>You have shared TheBeast calculator to your following " + (tblUserList.Rows.Count == 1 ? "contact" : "contacts") + ":</p>"
+ "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"5px\">";
for (int i = 0; i < tblUserList.Rows.Count; i++)
{
if (!_isImp)
_isImp = UtilityHandler.bIsImportantMail(Convert.ToString(tblUserList.Rows[i]["EmailId"]));
strMailBody += "<tr><td>" + tblUserList.Rows[i]["EmailId"] + "</td><td> - </td><td><a href=\"" + tblUserList.Rows[i]["AutoURL"] + "\">" + tblUserList.Rows[i]["AutoURL"] + "</a> " + "</td></tr>";
}
//_customMessage +
strMailBody += "</table>"
+ "<p>URL Valid for: " + Convert.ToDateTime(fromTm).ToString("dd-MMM-yyyy hh:mm:ss tt") + " GMT To " + Convert.ToDateTime(toDtTm).ToString("dd-MMM-yyyy hh:mm:ss tt") + " GMT</p>"
+ "<p>Please contact us if you have any questions.</p><br/>"
+ UtilityHandler.VCM_MailAddress_In_Html
+ "</div>";
//clsDAL oClsDAL = new clsDAL(false);
//string eMailID_User = oClsDAL.GetEmailIDFromUserId(pUserId);
/*Commented below call as the sender email id repeates in CC parameter*/
//UtilityHandler.SendMail(SenderEmail, System.Configuration.ConfigurationManager.AppSettings["FromEmail"].ToString() + "," + eMailID_User, "", strSubject, strMailBody);
//Mail separation internaluser@thebeastapps.com
if (UtilityHandler.bIsImportantMail(SenderEmail) || _isImp)
UtilityHandler.SendMail(SenderEmail, System.Configuration.ConfigurationManager.AppSettings["FromEmail"].ToString(), "", strSubject, strMailBody, false);
else
UtilityHandler.SendMail(SenderEmail, System.Configuration.ConfigurationManager.AppSettings["InternalEmail"].ToString(), "", strSubject, strMailBody, true);
}
catch (Exception ex)
{
LogUtility.Error("Service.asmx,cs", "SendAutoUrlMail()", ex.Message, ex);
}
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string SetDirImgSIDNull()
{
AppsInfo.Instance._dirImgSID = null;
return "";
}
#region Token
//[WebMethod]
//[ScriptMethod(UseHttpGet = true)]
public string getAuthToken(string UserID, string ClientType)
{
string AuthToken = "";
try
{
AuthToken = AddTokenInDir(UserID, ClientType);
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: getAuthToken() :: " + ex.Message.ToString());
LogUtility.Error("Service.asmx.cs", "getAuthToken()" + ex.Message.ToString());
}
return AuthToken;
}
public string AddTokenInDir(string UserID, string ClientTypeWithVersion)
{
string AuthToken = "";
try
{
string Excelversion = "";
string ClientType = ClientTypeWithVersion;
if (ClientTypeWithVersion.Contains("~"))
{
ClientType = Convert.ToString(ClientTypeWithVersion.Split('~')[0]);
Excelversion = Convert.ToString(ClientTypeWithVersion.Split('~')[1]);
}
AuthToken = Guid.NewGuid().ToString();
//openf2 ws = new openf2();
//clsDAL objDAL = new clsDAL(false);
//string UserName = "";
//string groupid = "";
//if (!string.IsNullOrEmpty(UserID.Trim()))
//{
// if (UserID.Trim().Contains("@"))
// {
// UserName = UserID;
// }
// else
// {
// DataSet ds = GetUserGroups(Convert.ToInt32(UserID));
// if (ds != null && ds.Tables[0].Rows.Count > 0)
// {
// groupid = Convert.ToString(ds.Tables[0].Rows[0]["GroupID"]);
// }
// UserName = objDAL.GetEmailIDFromUserId(Convert.ToInt32(UserID));
// }
//}
//if (UserName.Contains("#"))
//{
// UserName = UserName.Split('#')[0];
//}
//if (OpenBeast.Utilities.AuthenticationToken.Instance == null)
//{
// OpenBeast.Utilities.AuthenticationToken.Instance._dirAuthToken = new Dictionary<string, OpenBeast.Utilities.dirAuthToken>();
//}
//DateTime dateTimeSevenPM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 19, 0, 0);
//DateTime currentTime = DateTime.Now;
//OpenBeast.Utilities.UserDetail objUserDetail = new OpenBeast.Utilities.UserDetail();
//System.TimeSpan timeDiff = dateTimeSevenPM.Subtract(currentTime);
//if (timeDiff.Hours >= 0 && timeDiff.Minutes >= 0)
//{
// objUserDetail.LastAuthTime = dateTimeSevenPM;
//}
//else
//{
// DateTime authTokenNextExpiryTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 19, 0, 0);
// authTokenNextExpiryTime = authTokenNextExpiryTime.AddDays(1);
// objUserDetail.LastAuthTime = authTokenNextExpiryTime;
//}
//string Ipaddress = "";
//objUserDetail.ClientType = ClientType;
//objUserDetail.GUid = AuthToken;
//objUserDetail.Login = System.DateTime.Now;
//objUserDetail.IPAddres = UtilityHandler.Get_IPAddress(HttpContext.Current.Request.UserHostAddress);
//Ipaddress = objUserDetail.IPAddres;
//objUserDetail.UserName = UserName;
//DataSet dsGeoIP = new DataSet();
//dsGeoIP = ws.GetAutoURLGeoIPInfo(objUserDetail.IPAddres);
//string city = "";
//string org = "";
//string Country = "";
//if (dsGeoIP != null && dsGeoIP.Tables[0].Rows.Count > 0)
//{
// city = dsGeoIP.Tables[0].Rows[0][4].ToString();
// org = dsGeoIP.Tables[0].Rows[0][2].ToString();
// Country = dsGeoIP.Tables[0].Rows[0][3].ToString();
// objUserDetail.City = dsGeoIP.Tables[0].Rows[0][4].ToString();
// objUserDetail.Org = dsGeoIP.Tables[0].Rows[0][2].ToString();
// objUserDetail.Country = dsGeoIP.Tables[0].Rows[0][3].ToString();
//}
//OpenBeast.Utilities.dirAuthToken objdirAuthToken = new OpenBeast.Utilities.dirAuthToken();
//List<OpenBeast.Utilities.UserDetail> ListUserDetail = new List<OpenBeast.Utilities.UserDetail>();
//objdirAuthToken.UserDetails = ListUserDetail;
//objdirAuthToken.UserDetails.Add(objUserDetail);
//objdirAuthToken.UserID = UserID;
//if (OpenBeast.Utilities.AuthenticationToken.Instance._dirAuthToken.ContainsKey(UserID))
//{
// OpenBeast.Utilities.dirAuthToken ExistGUid = OpenBeast.Utilities.AuthenticationToken.Instance._dirAuthToken[UserID];
// ExistGUid.UserDetails.Add(objUserDetail);
//}
//else
//{
// OpenBeast.Utilities.AuthenticationToken.Instance._dirAuthToken.Add(UserID, objdirAuthToken);
//}
//if (!UserID.Contains("@"))
//{
// LogUtility.Info("Service.asmx.cs", "AddTokenInDir()", "$$UserID:" + UserID + ":" + (int)OpenBeast.Utilities.SysLogEnum.ADDAUTHENTICATIONTOKEN + " $$Token:" + AuthToken + "$$ClientType:" + ClientType + "$$Log-InTime:" + System.DateTime.Now + " $$UserName:" + UserName + " $$VendorId=" + groupid + " $$ExcelVersion:" + Excelversion + " $$");
//}
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: AddTokenInDir() :: " + ex.Message.ToString());
LogUtility.Error("Service.asmx.cs", "AddTokenInDir()" + ex.Message.ToString());
}
return AuthToken;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string[] ValidateAuthToken(string UserID, string ClientType, string GUID)
{
string[] TokenMessage = { "True", "" };
//try
//{
// if (OpenBeast.Utilities.AuthenticationToken.Instance._dirAuthToken != null)
// {
// LogUtility.Info("Service.asmx.cs", "ValidateAuthToken()", "$$UserID:" + UserID + "$$ClientType:" + ClientType + "$$Time:" + System.DateTime.Now + "dirAuthToken is not null" + " GUID:" + GUID);
// if (OpenBeast.Utilities.AuthenticationToken.Instance._dirAuthToken.ContainsKey(UserID) == true)
// {
// LogUtility.Info("Service.asmx.cs", "ValidateAuthToken()", "$$UserID:" + UserID + "$$ClientType:" + ClientType + "$$Time:" + System.DateTime.Now + "UserID exist" + " GUID:" + GUID);
// OpenBeast.Utilities.dirAuthToken ExistGUid = OpenBeast.Utilities.AuthenticationToken.Instance._dirAuthToken[UserID];
// if (ExistGUid != null)
// {
// LogUtility.Info("Service.asmx.cs", "ValidateAuthToken()", "$$UserID:" + UserID + "$$ClientType:" + ClientType + "$$Time:" + System.DateTime.Now + "Token exist" + " GUID:" + GUID);
// var ExistToken = ExistGUid.UserDetails.Where(x => x.GUid == GUID).FirstOrDefault();
// if (ExistToken != null)
// {
// DateTime currentTime = DateTime.Now;
// System.TimeSpan timeDiff = ExistToken.LastAuthTime.Subtract(currentTime);
// if (timeDiff.Hours >= 0 && timeDiff.Minutes >= 0)
// {
// LogUtility.Info("Service.asmx.cs", "ValidateAuthToken()", "$$UserID:" + UserID + "$$ClientType:" + ClientType + "$$Time:" + System.DateTime.Now + "Validate True" + " GUID:" + GUID);
// TokenMessage[0] = "True";
// }
// else
// {
// LogUtility.Info("Service.asmx.cs", "ValidateAuthToken()", "$$UserID:" + UserID + "$$ClientType:" + ClientType + "$$Time:" + System.DateTime.Now + "LastAuthenticationTime expired" + " GUID:" + GUID);
// TokenMessage[1] = "Your session has expired. Please relogin, LastAuthenticationTime:" + ExistToken.LastAuthTime.ToString();
// VCM_Mail objVCM_Mail = new VCM_Mail();
// objVCM_Mail.SendMailForSessionExpired(UserID, ClientType, GUID, "Session Expired due to daily pool recycle at 7.00 p.m.");
// LogUtility.Info("Service.asmx.cs", "ValidateAuthToken()", "$$UserID:" + UserID + ":" + (int)OpenBeast.Utilities.SysLogEnum.REMOVEAUTHENTICATIONTOKEN + " $$Token:" + GUID + "$$ClientType:" + ClientType + "$$Log-OutTime:" + System.DateTime.Now);
// }
// }
// else
// {
// LogUtility.Info("Service.asmx.cs", "ValidateAuthToken()", "$$UserID:" + UserID + "$$ClientType:" + ClientType + "$$Time:" + System.DateTime.Now + "session has expired" + " GUID:" + GUID);
// TokenMessage[1] = "Your session has expired. Please relogin";
// VCM_Mail objVCM_Mail = new VCM_Mail();
// objVCM_Mail.SendMailForSessionExpired(UserID, ClientType, GUID, "Token does not exist.");
// }
// }
// }
// else
// {
// LogUtility.Info("Service.asmx.cs", "ValidateAuthToken()", "$$UserID:" + UserID + "$$ClientType:" + ClientType + "$$Time:" + System.DateTime.Now + "Userid Does not exist" + " GUID:" + GUID);
// TokenMessage[1] = "Your session has expired. Please relogin";
// VCM_Mail objVCM_Mail = new VCM_Mail();
// objVCM_Mail.SendMailForSessionExpired(UserID, ClientType, GUID, "UserId not found in Token directory.");
// }
// }
// else
// {
// LogUtility.Info("Service.asmx.cs", "ValidateAuthToken()", "$$UserID:" + UserID + "$$ClientType:" + ClientType + "$$Time:" + System.DateTime.Now + "dirAuthToken is null" + " GUID:" + GUID);
// TokenMessage[1] = "Authentication list is empty";
// }
//}
//catch (Exception ex)
//{
// UtilityHandler.SendEmailForError("service.asmx :: ValidateAuthToken() :: " + ex.Message.ToString() + "UserID:" + UserID + "ClientType:" + ClientType + "GUID:" + GUID);
// TokenMessage[1] = ex.Message != null ? ex.Message : "Error" + "Authentication list is empty";
// LogUtility.Error("Service.asmx.cs", "ValidateAuthToken()" + ex.Message.ToString());
//}
return TokenMessage;
}
#endregion
#region UrlAdminNew calls
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public DataSet SharedAutoURL_Validate(string RefID, string ClientType)
{
DataSet dst = new DataSet();
string AuthToken = "";
try
{
//clsDAL objDAL = new clsDAL(false);
//openf2 ws = new openf2();
//dst = ws.BeastApps_SharedAutoURL_Validate(RefID);
if (dst.Tables.Count > 0 && dst.Tables[0].Rows.Count > 0)
{
AuthToken = AddTokenInDir(Convert.ToString(dst.Tables[0].Rows[0]["EmailId"]), ClientType);
dst.Tables[0].Columns.Add("AuthToken");
dst.Tables[0].Rows[0]["AuthToken"] = AuthToken;
// objDAL.SubmitUserTokenSetail(0, Convert.ToString(dst.Tables[0].Rows[0]["EmailId"]), AuthToken, "N", "N");
LogUtility.Info("Service.asmx.cs", "SharedAutoURL_Validate()", "$$UserID:" + Convert.ToString(dst.Tables[0].Rows[0]["InitiatorUserId"]) + " :" + (int)OpenBeast.Utilities.SysLogEnum.SHAREDTOUSERAUTHENTICATED + " $$Token:" + AuthToken + " $$SharedToUser:" + Convert.ToString(dst.Tables[0].Rows[0]["EmailId"]) + " $$ClientType:" + ClientType + " $$Log-InTime:" + System.DateTime.Now + " $$");
}
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: SharedAutoURL_Validate() :: " + ex.Message.ToString());
LogUtility.Error("Service.asmx.cs", "SharedAutoURL_Validate()" + ex.Message.ToString());
}
return dst;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public void BeastApps_SharedAutoURL_UpdateClickCount(string pRefId)
{
try
{
//openf2 wsObj = new openf2();
//wsObj.BeastApps_SharedAutoURL_UpdateClickCount(pRefId);
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: BeastApps_SharedAutoURL_UpdateClickCount() :: " + ex.Message.ToString());
LogUtility.Error("Service.asmx.cs", "BeastApps_SharedAutoURL_UpdateClickCount()" + ex.Message.ToString());
}
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string[] ValidateUser(string strUserName, string strPass, string ClientType)
{
string[] userInfo = null;
//openf2 objadmin = new openf2();
bool isValid = false;
string AuthToken = "";
string AuthTicket = "";
string userdtl = "";
try
{
//userInfo = objadmin.AuthenticateUser(strUserName.Trim(), strPass.Trim());
isValid = Convert.ToBoolean(userInfo[0]);
if (isValid == true)
{
AuthToken = getAuthToken(userInfo[1].ToString().Split('#')[0], ClientType);
int actLength = 12;
string[] _tempElements = new string[actLength];
string[] _tempUserdtl = userInfo[1].Split('#');
int iLength = userInfo[1].Split('#').Length;
for (int i = 0; i < iLength; i++)
{
_tempElements[i] = _tempUserdtl[i];
}
_tempElements[9] = AuthToken;
_tempElements[10] = "";
_tempElements[11] = "";
//Save if client is launcher
if (ClientType.ToLower() == "launcher")
{
clsDAL objCls = new clsDAL(true);
//Generate new token and save to db
AuthTicket = Guid.NewGuid().ToString();
objCls.Launcher_SubmitAuthTicket(_tempElements[0], AuthTicket, DateTime.Now, DateTime.Now.AddDays(5));
_tempElements[10] = AuthTicket;
}
for (int i = 0; i < actLength; i++)
{
userdtl += _tempElements[i] + "#";
}
//Remove last #. Important! Affects all clients : web/excel/launcher
userdtl = userdtl.Substring(0, userdtl.LastIndexOf('#') - 1);
//userdtl = userInfo[1] + "#" + AuthToken;
userInfo[1] = userdtl;
}
if (ClientType.Contains("~"))
{
ClientType = Convert.ToString(ClientType.Split('~')[0]);
}
if (ClientType.Trim().ToLower() != "web")
{
VCM_Mail objVCM_Mail = new VCM_Mail();
objVCM_Mail.SendMailForLoginNotification(userInfo, strUserName, ClientType);
objVCM_Mail = null;
}
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: ValidateUser() :: " + ex.Message.ToString());
LogUtility.Error("Service.asmx.cs", "ValidateUser()" + ex.Message.ToString());
}
return userInfo;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string[] ValidateUser_New_UM(string strUserName, string strPass, string ClientType, string strAspSesionId, Int32 ssId)
{
string[] userInfo = null;
//openf2 objadmin = new openf2();
bool isValid = false;
string AuthToken = "";
string userdtl = "";
string sessionid = "";
try
{
sessionid = Guid.NewGuid().ToString();
//userInfo = objadmin.ValidateUser_New_UM(strUserName.Trim(), strPass.Trim(), sessionid, ssId);
isValid = Convert.ToBoolean(userInfo[0]);
if (isValid == true)
{
AuthToken = getAuthToken(userInfo[1].ToString().Split('#')[0], ClientType);
userdtl = userInfo[1] + "#" + AuthToken;
userInfo[1] = userdtl;
}
if (ClientType.Trim().ToLower() != "web")
{
VCM_Mail objVCM_Mail = new VCM_Mail();
objVCM_Mail.SendMailForLoginNotification(userInfo, strUserName, ClientType);
objVCM_Mail = null;
}
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: ValidateUser() :: " + ex.Message.ToString());
LogUtility.Error("Service.asmx.cs", "ValidateUser()" + ex.Message.ToString());
}
return userInfo;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public DataSet AutoURL_Validate_User_Info(string refNo, string UserHostAddress, int ApplicationCode, string ClientType)
{
DataSet dst = new DataSet();
string AuthToken = "";
try
{
// clsDAL objDAL = new clsDAL(false);
//openf2 ws = new openf2();
//dst = ws.VCM_AutoURL_Validate_User_Info(refNo, UserHostAddress, ApplicationCode);
if (dst.Tables.Count > 0 && dst.Tables[0].Rows.Count > 0)
{
AuthToken = AddTokenInDir(Convert.ToString(dst.Tables[0].Rows[0]["UserId"]), ClientType);
dst.Tables[0].Columns.Add("AuthToken");
dst.Tables[0].Rows[0]["AuthToken"] = AuthToken;
}
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: SharedAutoURL_Validate() :: " + ex.Message.ToString());
LogUtility.Error("Service.asmx.cs", "SharedAutoURL_Validate()" + ex.Message.ToString());
}
return dst;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public bool ChangePassword(Int64 lUserId, string oldPassword, string newPassword)
{
bool retVal = false;
try
{
//openf2 ws = new openf2();
//retVal = ws.ChangePassword(lUserId, oldPassword, newPassword);
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: ChangePassword() :: " + ex.Message.ToString());
LogUtility.Error("Service.asmx.cs", "ChangePassword()" + ex.Message.ToString());
}
return retVal;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public bool LogoutUserForcefully(string UserId)
{
bool retVal = false;
try
{
DAL.clsDAL objDAl = new clsDAL(false);
DataSet ds = new DataSet();
ds = objDAl.GeWeActiveLoginsDtl(UserId);
for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
{
objDAl.SubmitWebActiveLogins(UserId, Convert.ToString(ds.Tables[0].Rows[index]["SessionID"]), "", "", "");
// retVal= DisableToken(Convert.ToString(ds.Tables[0].Rows[index]["SessionID"]), UserId, Convert.ToString(ds.Tables[0].Rows[index]["ClientType"]));
VCMComet.Instance.Send_Message_To_Client_Connection_Generic(Convert.ToString(ds.Tables[0].Rows[index]["ConnectionId"]), "alrt", "m", "eleID", "Logout", "ForceLogout");
}
}
catch (Exception ex)
{
LogUtility.Error("Service.asmx.cs", "LogoutUserForcefully()" + ex.Message.ToString());
}
return retVal;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string CheckLoginPolicy(string UserId, string ClientType)
{
string AuthToken = "";
try
{
DAL.clsDAL objDAl = new clsDAL(false);
DataSet ds = new DataSet();
ds = objDAl.GetVALIDATEUSERLOGIN(UserId);
//if (Convert.ToString(ds.Tables[0].Rows[0][0]) == "-7")
//{
LogoutUserForcefully(UserId);
AuthToken = Guid.NewGuid().ToString();
objDAl.SubmitValidateLogin(UserId, AuthToken);
AuthToken = AddTokenInDir(UserId, ClientType);
//}
}
catch (Exception ex)
{
LogUtility.Error("Service.asmx.cs", "CheckLoginPolicy()" + ex.Message.ToString());
}
return AuthToken;
}
#endregion
#region Excel
[WebMethod]
public DataSet Excel_GetXml(string CalcID, string LastUpdatedDate)
{
DataSet dsxml = new DataSet();
DAL.clsDAL OBJdal = new DAL.clsDAL(false);
dsxml = OBJdal.GetXML(CalcID, LastUpdatedDate);
return dsxml;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public ExeChunk GetLatestVersionID(string UserID, string ObjectID)
{
try
{
clsDAL oClsDAL = new clsDAL(false);
return oClsDAL.GetLatestVersionID(ObjectID);
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: GetLatestVersionID() :: " + ex.Message.ToString());
ExeChunk volEntityObj = new ExeChunk();
return volEntityObj;
}
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public List<ExeChunk> GetLatestVersionSetup(string UserID, string ObjectID)
{
try
{
clsDAL oClsDAL = new clsDAL(false);
return oClsDAL.GetLatestVersionSetup(ObjectID);
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: GetLatestVersionSetup() :: " + ex.Message.ToString());
List<ExeChunk> volEntityObj = new List<ExeChunk>();
return volEntityObj;
}
}
[WebMethod]
public void NotifyDownload(string pExcelVersion, string pClientIp, string pInstallationInfoHtml)
{
try
{
clsDAL _obj = new clsDAL(true);
_obj.SendExcelDownloadNotification(pExcelVersion, pClientIp, pInstallationInfoHtml);
_obj = null;
}
catch (Exception ex)
{
LogUtility.Error("Service.asmx.cs", "NotifyDownload()", ex.Message, ex);
}
}
#endregion
//Added by cpkabra
[WebMethod(EnableSession = true)]
public DataSet GetUserGroups(long UserId)
{
DataSet ds = new DataSet();
try
{
clsDAL oClsDAL = new clsDAL(false);
return ds = oClsDAL.GetUserGroups(UserId);
}
catch (Exception ex)
{
return ds;
}
}
//Ended
//TruMid AutoUrl
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string AutoURL_Validate(string userid, string ClientType)
{
string AuthToken = "";
try
{
return AuthToken = AddTokenInDir(userid, ClientType);
}
catch (Exception ex)
{
LogUtility.Error("Service.asmx.cs", "SharedAutoURL_Validate()" + ex.Message.ToString());
}
return AuthToken;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public int AutoLoginByAuthTicket(string strUserId, string strAuthToken, string ClientType)
{
int iRetVal = 0; // 1 = Valid, Load respective swarm directly | 0 = Invalid, Show login page
// ClientType : Not used now. Kept for future scope
try
{
clsDAL objDAL = new clsDAL(true);
string _result = objDAL.Launcher_GetAuthTicket(strUserId, strAuthToken);
switch (_result.Split('#')[0])
{
case "1":
iRetVal = 1;
break;
case "0":
// Token Expired
break;
case "-1":
// User not found
break;
case "-2":
// Invalid token/ Token not found
break;
}
}
catch (Exception ex)
{
UtilityHandler.SendEmailForError("service.asmx :: AutoLoginByAuthToken() :: " + ex.Message.ToString());
LogUtility.Error("Service.asmx.cs", "AutoLoginByAuthToken()" + ex.Message.ToString());
}
return iRetVal;
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using DotNetCore.Localization.Web.Data;
namespace DotNetCore.Localization.Web.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc2-20901");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("DotNetCore.Localization.Web.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("DotNetCore.Localization.Web.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("DotNetCore.Localization.Web.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("DotNetCore.Localization.Web.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Java.Beans.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.
#pragma warning disable 1717
namespace Java.Beans
{
/// <summary>
/// <para>A PropertyChangeListener can subscribe with a event source. Whenever that source raises a PropertyChangeEvent this listener will get notified. </para>
/// </summary>
/// <java-name>
/// java/beans/PropertyChangeListener
/// </java-name>
[Dot42.DexImport("java/beans/PropertyChangeListener", AccessFlags = 1537)]
public partial interface IPropertyChangeListener : global::Java.Util.IEventListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>The source bean calls this method when an event is raised.</para><para></para>
/// </summary>
/// <java-name>
/// propertyChange
/// </java-name>
[Dot42.DexImport("propertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1025)]
void PropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>An event that indicates that a constraint or a boundary of a property has changed. </para>
/// </summary>
/// <java-name>
/// java/beans/PropertyChangeEvent
/// </java-name>
[Dot42.DexImport("java/beans/PropertyChangeEvent", AccessFlags = 33)]
public partial class PropertyChangeEvent : global::Java.Util.EventObject
/* scope: __dot42__ */
{
/// <summary>
/// <para>The constructor used to create a new <c> PropertyChangeEvent </c> .</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)]
public PropertyChangeEvent(object source, string propertyName, object oldValue, object newValue) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the name of the property that has changed. If an unspecified set of properties has changed it returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the property that has changed, or null. </para>
/// </returns>
/// <java-name>
/// getPropertyName
/// </java-name>
[Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetPropertyName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the propagationId object.</para><para><para>getPropagationId() </para></para>
/// </summary>
/// <java-name>
/// setPropagationId
/// </java-name>
[Dot42.DexImport("setPropagationId", "(Ljava/lang/Object;)V", AccessFlags = 1)]
public virtual void SetPropagationId(object propagationId) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the propagationId object. This is reserved for future use. Beans 1.0 demands that a listener receiving this property and then sending its own PropertyChangeEvent sets the received propagationId on the new PropertyChangeEvent's propagationId field.</para><para></para>
/// </summary>
/// <returns>
/// <para>the propagationId object. </para>
/// </returns>
/// <java-name>
/// getPropagationId
/// </java-name>
[Dot42.DexImport("getPropagationId", "()Ljava/lang/Object;", AccessFlags = 1)]
public virtual object GetPropagationId() /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Returns the old value that the property had. If the old value is unknown this method returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the old property value or null. </para>
/// </returns>
/// <java-name>
/// getOldValue
/// </java-name>
[Dot42.DexImport("getOldValue", "()Ljava/lang/Object;", AccessFlags = 1)]
public virtual object GetOldValue() /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Returns the new value that the property now has. If the new value is unknown this method returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the old property value or null. </para>
/// </returns>
/// <java-name>
/// getNewValue
/// </java-name>
[Dot42.DexImport("getNewValue", "()Ljava/lang/Object;", AccessFlags = 1)]
public virtual object GetNewValue() /* MethodBuilder.Create */
{
return default(object);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PropertyChangeEvent() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns the name of the property that has changed. If an unspecified set of properties has changed it returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the property that has changed, or null. </para>
/// </returns>
/// <java-name>
/// getPropertyName
/// </java-name>
public string PropertyName
{
[Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPropertyName(); }
}
/// <summary>
/// <para>Returns the propagationId object. This is reserved for future use. Beans 1.0 demands that a listener receiving this property and then sending its own PropertyChangeEvent sets the received propagationId on the new PropertyChangeEvent's propagationId field.</para><para></para>
/// </summary>
/// <returns>
/// <para>the propagationId object. </para>
/// </returns>
/// <java-name>
/// getPropagationId
/// </java-name>
public object PropagationId
{
[Dot42.DexImport("getPropagationId", "()Ljava/lang/Object;", AccessFlags = 1)]
get{ return GetPropagationId(); }
[Dot42.DexImport("setPropagationId", "(Ljava/lang/Object;)V", AccessFlags = 1)]
set{ SetPropagationId(value); }
}
/// <summary>
/// <para>Returns the old value that the property had. If the old value is unknown this method returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the old property value or null. </para>
/// </returns>
/// <java-name>
/// getOldValue
/// </java-name>
public object OldValue
{
[Dot42.DexImport("getOldValue", "()Ljava/lang/Object;", AccessFlags = 1)]
get{ return GetOldValue(); }
}
/// <summary>
/// <para>Returns the new value that the property now has. If the new value is unknown this method returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the old property value or null. </para>
/// </returns>
/// <java-name>
/// getNewValue
/// </java-name>
public object NewValue
{
[Dot42.DexImport("getNewValue", "()Ljava/lang/Object;", AccessFlags = 1)]
get{ return GetNewValue(); }
}
}
/// <summary>
/// <para>A type of PropertyChangeEvent that indicates that an indexed property has changed. </para>
/// </summary>
/// <java-name>
/// java/beans/IndexedPropertyChangeEvent
/// </java-name>
[Dot42.DexImport("java/beans/IndexedPropertyChangeEvent", AccessFlags = 33)]
public partial class IndexedPropertyChangeEvent : global::Java.Beans.PropertyChangeEvent
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new property changed event with an indication of the property index.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;I)V", AccessFlags = 1)]
public IndexedPropertyChangeEvent(object source, string propertyName, object oldValue, object newValue, int index) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the index of the property that was changed in this event. </para>
/// </summary>
/// <java-name>
/// getIndex
/// </java-name>
[Dot42.DexImport("getIndex", "()I", AccessFlags = 1)]
public virtual int GetIndex() /* MethodBuilder.Create */
{
return default(int);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal IndexedPropertyChangeEvent() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns the index of the property that was changed in this event. </para>
/// </summary>
/// <java-name>
/// getIndex
/// </java-name>
public int Index
{
[Dot42.DexImport("getIndex", "()I", AccessFlags = 1)]
get{ return GetIndex(); }
}
}
/// <summary>
/// <para>Manages a list of listeners to be notified when a property changes. Listeners subscribe to be notified of all property changes, or of changes to a single named property.</para><para>This class is thread safe. No locking is necessary when subscribing or unsubscribing listeners, or when publishing events. Callers should be careful when publishing events because listeners may not be thread safe. </para>
/// </summary>
/// <java-name>
/// java/beans/PropertyChangeSupport
/// </java-name>
[Dot42.DexImport("java/beans/PropertyChangeSupport", AccessFlags = 33)]
public partial class PropertyChangeSupport : global::Java.Io.ISerializable
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new instance that uses the source bean as source for any event.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Object;)V", AccessFlags = 1)]
public PropertyChangeSupport(object sourceBean) /* MethodBuilder.Create */
{
}
/// <java-name>
/// firePropertyChange
/// </java-name>
[Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)]
public virtual void FirePropertyChange(string @string, object @object, object object1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// fireIndexedPropertyChange
/// </java-name>
[Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;ILjava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)]
public virtual void FireIndexedPropertyChange(string @string, int int32, object @object, object object1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Unsubscribes <c> listener </c> from change notifications for the property named <c> propertyName </c> . If multiple subscriptions exist for <c> listener </c> , it will receive one fewer notifications when the property changes. If the property name or listener is null or not subscribed, this method silently does nothing. </para>
/// </summary>
/// <java-name>
/// removePropertyChangeListener
/// </java-name>
[Dot42.DexImport("removePropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)]
public virtual void RemovePropertyChangeListener(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Subscribes <c> listener </c> to change notifications for the property named <c> propertyName </c> . If the listener is already subscribed, it will receive an additional notification when the property changes. If the property name or listener is null, this method silently does nothing. </para>
/// </summary>
/// <java-name>
/// addPropertyChangeListener
/// </java-name>
[Dot42.DexImport("addPropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)]
public virtual void AddPropertyChangeListener(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the subscribers to be notified when <c> propertyName </c> changes. This includes both listeners subscribed to all property changes and listeners subscribed to the named property only. </para>
/// </summary>
/// <java-name>
/// getPropertyChangeListeners
/// </java-name>
[Dot42.DexImport("getPropertyChangeListeners", "(Ljava/lang/String;)[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)]
public virtual global::Java.Beans.IPropertyChangeListener[] GetPropertyChangeListeners(string propertyName) /* MethodBuilder.Create */
{
return default(global::Java.Beans.IPropertyChangeListener[]);
}
/// <java-name>
/// firePropertyChange
/// </java-name>
[Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;ZZ)V", AccessFlags = 1)]
public virtual void FirePropertyChange(string @string, bool boolean, bool boolean1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// fireIndexedPropertyChange
/// </java-name>
[Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;IZZ)V", AccessFlags = 1)]
public virtual void FireIndexedPropertyChange(string @string, int int32, bool boolean, bool boolean1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// firePropertyChange
/// </java-name>
[Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;II)V", AccessFlags = 1)]
public virtual void FirePropertyChange(string @string, int int32, int int321) /* MethodBuilder.Create */
{
}
/// <java-name>
/// fireIndexedPropertyChange
/// </java-name>
[Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;III)V", AccessFlags = 1)]
public virtual void FireIndexedPropertyChange(string @string, int int32, int int321, int int322) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns true if there are listeners registered to the property with the given name.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if there are listeners registered to that property, false otherwise. </para>
/// </returns>
/// <java-name>
/// hasListeners
/// </java-name>
[Dot42.DexImport("hasListeners", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public virtual bool HasListeners(string propertyName) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Unsubscribes <c> listener </c> from change notifications for all properties. If the listener has multiple subscriptions, it will receive one fewer notification when properties change. If the property name or listener is null or not subscribed, this method silently does nothing. </para>
/// </summary>
/// <java-name>
/// removePropertyChangeListener
/// </java-name>
[Dot42.DexImport("removePropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)]
public virtual void RemovePropertyChangeListener(global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Subscribes <c> listener </c> to change notifications for all properties. If the listener is already subscribed, it will receive an additional notification. If the listener is null, this method silently does nothing. </para>
/// </summary>
/// <java-name>
/// addPropertyChangeListener
/// </java-name>
[Dot42.DexImport("addPropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)]
public virtual void AddPropertyChangeListener(global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns all subscribers. This includes both listeners subscribed to all property changes and listeners subscribed to a single property. </para>
/// </summary>
/// <java-name>
/// getPropertyChangeListeners
/// </java-name>
[Dot42.DexImport("getPropertyChangeListeners", "()[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)]
public virtual global::Java.Beans.IPropertyChangeListener[] GetPropertyChangeListeners() /* MethodBuilder.Create */
{
return default(global::Java.Beans.IPropertyChangeListener[]);
}
/// <summary>
/// <para>Publishes a property change event to all listeners of that property. If the event's old and new values are equal (but non-null), no event will be published. </para>
/// </summary>
/// <java-name>
/// firePropertyChange
/// </java-name>
[Dot42.DexImport("firePropertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1)]
public virtual void FirePropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PropertyChangeSupport() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns all subscribers. This includes both listeners subscribed to all property changes and listeners subscribed to a single property. </para>
/// </summary>
/// <java-name>
/// getPropertyChangeListeners
/// </java-name>
public global::Java.Beans.IPropertyChangeListener[] PropertyChangeListeners
{
[Dot42.DexImport("getPropertyChangeListeners", "()[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)]
get{ return GetPropertyChangeListeners(); }
}
}
/// <summary>
/// <para>The implementation of this listener proxy just delegates the received events to its listener. </para>
/// </summary>
/// <java-name>
/// java/beans/PropertyChangeListenerProxy
/// </java-name>
[Dot42.DexImport("java/beans/PropertyChangeListenerProxy", AccessFlags = 33)]
public partial class PropertyChangeListenerProxy : global::Java.Util.EventListenerProxy, global::Java.Beans.IPropertyChangeListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new listener proxy that associates a listener with a property name.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)]
public PropertyChangeListenerProxy(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the name of the property associated with this listener proxy.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the associated property. </para>
/// </returns>
/// <java-name>
/// getPropertyName
/// </java-name>
[Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetPropertyName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>The source bean calls this method when an event is raised.</para><para></para>
/// </summary>
/// <java-name>
/// propertyChange
/// </java-name>
[Dot42.DexImport("propertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1)]
public virtual void PropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PropertyChangeListenerProxy() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns the name of the property associated with this listener proxy.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the associated property. </para>
/// </returns>
/// <java-name>
/// getPropertyName
/// </java-name>
public string PropertyName
{
[Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPropertyName(); }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.DataStructures
{
#if false && DEBUG
/// <summary>
/// This type causes errors where the ordinay Dictionary<> is used;
/// use CDictionary<> instead.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public class Dictionary<T, U> { }
#endif
/// <summary>
/// A dictionary.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
[DebuggerDisplay("Count = {Count}")]
[System.Runtime.InteropServices.ComVisible(false)]
[ContractVerification(false)]
public sealed class CDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
[Serializable]
[StructLayout(LayoutKind.Auto)]
private struct Entry
{
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[] buckets;
private Entry[] entries;
private int count;
#if DEBUG
private int version;
#endif
private int freeList;
private int freeCount;
private readonly IEqualityComparer<TKey> comparer;
private KeyCollection keys;
private ValueCollection values;
// constants for serialization
private const String VersionName = "Version";
private const String HashSizeName = "HashSize"; // Must save buckets.Length
private const String KeyValuePairsName = "KeyValuePairs";
private const String ComparerName = "Comparer";
/// <summary>
///
/// </summary>
/// <param name="comparer"></param>
public CDictionary(IEqualityComparer<TKey> comparer)
: this(0, comparer)
{
Contract.Requires(comparer != null);
}
/// <summary>
///
/// </summary>
/// <param name="capacity"></param>
/// <param name="comparer"></param>
public CDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
Contract.Requires(capacity >= 0);
Contract.Requires(comparer != null);
if (capacity > 0)
Initialize(capacity);
this.comparer = comparer;
Contract.Assert(this.comparer != null);
}
/// <summary>
///
/// </summary>
public IEqualityComparer<TKey> Comparer
{
get
{
return comparer;
}
}
/// <summary>
///
/// </summary>
public int Count
{
get { return count - freeCount; }
}
/// <summary>
///
/// </summary>
public KeyCollection Keys
{
get
{
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
/// <summary>
///
/// </summary>
public ValueCollection Values
{
get
{
if (values == null) values = new ValueCollection(this);
return values;
}
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public TValue this[TKey key]
{
get
{
Contract.Requires(key != null);
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
return entries[i].value;
}
}
Contract.Assert(false, "key not found");
return default(TValue);
}
set
{
Contract.Requires(key != null);
Insert(key, value, false);
}
}
/// <summary>
/// Value creator delegate.
/// </summary>
public delegate TValue ValueCreator<TContext>(TKey key, TContext context);
/// <summary>
/// Gets or creates the value.
/// </summary>
/// <remarks>
/// The purpose of the context argument is to enable statically allocated delegates.
/// To this end, non-trivial delegates passed to this method should always be declared as
/// a static method, to prevent accidental closures.
/// </remarks>
/// <typeparam name="TContext">The type of the context.</typeparam>
/// <param name="key">The key.</param>
/// <param name="context">The context.</param>
/// <param name="valueCreator">The value creator.</param>
/// <returns></returns>
public TValue GetOrCreateValue<TContext>(TKey key, TContext context, ValueCreator<TContext> valueCreator)
{
Contract.Requires(key != null);
TValue res;
if (!this.TryGetValue(key, out res))
{
res = valueCreator(key, context);
this.Insert(key, res, true);
}
return res;
}
/// <summary>
/// Gets or creates the value.
/// </summary>
/// <remarks>
/// The purpose of the context argument is to enable statically allocated delegates.
/// To this end, non-trivial delegates passed to this method should always be declared as
/// a static method, to prevent accidental closures.
/// </remarks>
/// <typeparam name="TContext">The type of the context.</typeparam>
/// <param name="key">The key.</param>
/// <param name="context">The context.</param>
/// <param name="valueCreator">The value creator.</param>
/// <returns></returns>
public TValue SynchronizedGetOrCreateValue<TContext>(TKey key, TContext context, ValueCreator<TContext> valueCreator)
{
Contract.Requires(key != null);
lock (this)
{
return this.GetOrCreateValue<TContext>(key, context, valueCreator);
}
}
/// <summary>
/// Value creator delegate.
/// </summary>
public delegate TValue ValueCreator(TKey key);
/// <summary>
/// Gets or creates the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="valueCreator">The value creator.</param>
/// <returns></returns>
/// <remarks>
/// This method should be used with statically allocated delegates.
/// To this end, non-trivial delegates passed to this method should always be declared as
/// a static method, to prevent accidental closures.
/// </remarks>
public TValue GetOrCreateValue(TKey key, ValueCreator valueCreator)
{
Contract.Requires(key != null);
// TODO: Profile and consider merging TryGetValue and Insert
TValue res;
if (!this.TryGetValue(key, out res))
{
res = valueCreator(key);
this.Insert(key, res, true);
}
return res;
}
/// <summary>
/// Gets or creates the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="valueCreator">The value creator.</param>
/// <returns></returns>
/// <remarks>
/// This method should be used with statically allocated delegates.
/// To this end, non-trivial delegates passed to this method should always be declared as
/// a static method, to prevent accidental closures.
/// </remarks>
public TValue SynchronizedGetOrCreateValue(TKey key, ValueCreator valueCreator)
{
lock (this)
{
return this.GetOrCreateValue(key, valueCreator);
}
}
/// <summary>
/// This method expect the key to be new.
/// In other words, there should not be a mapping for this key already in the dictionary.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Add(TKey key, TValue value)
{
Contract.Requires(key != null);
this.Insert(key, value, true);
}
/// <summary>
/// Adds the range.
/// </summary>
/// <param name="entries">The entries.</param>
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> entries)
{
Contract.Requires(entries != null);
KeyValuePair<TKey, TValue>[] array = entries as KeyValuePair<TKey, TValue>[];
if (array != null)
this.AddRange(array);
else
foreach (var kvp in entries)
{
Contract.Assume(kvp.Key != null);
this.Insert(kvp.Key, kvp.Value, true);
}
}
/// <summary>
/// Adds the range.
/// </summary>
/// <param name="entries">The entries.</param>
public void AddRange(KeyValuePair<TKey, TValue>[] entries)
{
Contract.Requires(entries != null);
foreach (var kvp in entries)
{
Contract.Assume(kvp.Key != null);
this.Insert(kvp.Key, kvp.Value, true);
}
}
/// <summary>
/// Overrides the range.
/// </summary>
/// <param name="entries">The entries.</param>
public void OverrideRange(IEnumerable<KeyValuePair<TKey, TValue>> entries)
{
Contract.Requires(entries != null);
KeyValuePair<TKey, TValue>[] array = entries as KeyValuePair<TKey, TValue>[];
if (array != null)
this.OverrideRange(array);
else
foreach (var kvp in entries)
{
Contract.Assume(kvp.Key != null);
this.Insert(kvp.Key, kvp.Value, false);
}
}
/// <summary>
/// Overrides the range.
/// </summary>
/// <param name="entries">The entries.</param>
public void OverrideRange(KeyValuePair<TKey, TValue>[] entries)
{
Contract.Requires(entries != null);
foreach (var kvp in entries)
{
Contract.Assume(kvp.Key != null);
this.Insert(kvp.Key, kvp.Value, false);
}
}
/// <summary>
///
/// </summary>
public void Clear()
{
if (count > 0)
{
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
Array.Clear(entries, 0, count);
freeList = -1;
count = 0;
freeCount = 0;
#if DEBUG
version++;
#endif
}
}
/// <summary>
/// Removes all elements, and trims the size of the dictionary.
/// </summary>
public void ClearAndTrim()
{
if (count > 0)
{
buckets = null;
entries = null;
freeList = 0;
count = 0;
freeCount = 0;
keys = null;
values = null;
#if DEBUG
version++;
#endif
}
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
[Pure]
public bool ContainsKey(TKey key)
{
Contract.Requires(key != null);
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
return true;
}
}
return false;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public KeyValuePair<TKey, TValue>[] ToArray()
{
if (this.Count == 0)
return CArray.Empty<KeyValuePair<TKey, TValue>>();
else
{
KeyValuePair<TKey, TValue>[] res = new KeyValuePair<TKey, TValue>[this.Count];
CopyTo(res, 0);
return res;
}
}
/// <summary>
/// Copies to.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="index">The index.</param>
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
Contract.Requires(array != null);
Contract.Requires((uint)index <= (uint)array.Length);
Contract.Requires(array.Length - index >= Count);
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns></returns>
public CDictionary<TKey, TValue> Clone()
{
int count = this.count;
CDictionary<TKey, TValue> res = new CDictionary<TKey, TValue>(this.Count, comparer);
Entry[] entries = this.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
res.Add(entries[i].key, entries[i].value);
}
return res;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Enumerator GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
private void Initialize(int capacity)
{
Contract.Requires(capacity >= 0);
int size = HashHelpers.GetPrime(capacity);
buckets = new int[size];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[size];
freeList = -1;
}
private void Insert(TKey key, TValue value, bool add)
{
Contract.Requires(key != null);
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
if (buckets == null)
Initialize(0);
else
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
{
Contract.Assert(!add);
entries[i].value = value;
#if DEBUG
version++;
#endif
return;
}
}
int index;
if (freeCount > 0)
{
index = freeList;
freeList = entries[index].next;
freeCount--;
}
else
{
if (count == entries.Length) Grow();
index = count;
count++;
}
int bucket = hashCode % buckets.Length;
entries[index].hashCode = hashCode;
entries[index].next = buckets[bucket];
entries[index].key = key;
entries[index].value = value;
buckets[bucket] = index;
#if DEBUG
version++;
#endif
}
private void Shrink()
{
int newSize = HashHelpers.GetPrime(this.count / 2);
int[] newBuckets = new int[newSize];
for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
Entry[] newEntries = new Entry[newSize];
int count = this.count;
int newCount = 0;
for (int i = 0; i < count; i++)
{
int hashCode = entries[i].hashCode;
if (hashCode >= 0)
{
newEntries[newCount].key = entries[i].key;
newEntries[newCount].hashCode = hashCode;
int bucket = hashCode % newSize;
newEntries[newCount].value = entries[i].value;
newEntries[newCount].next = newBuckets[bucket];
newBuckets[bucket] = newCount++;
}
}
this.count = newCount;
buckets = newBuckets;
entries = newEntries;
freeList = -1;
freeCount = 0;
}
private void Grow()
{
int newSize = HashHelpers.GetPrime(this.count * 2);
int[] newBuckets = new int[newSize];
for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
int count = this.count;
Entry[] newEntries = new Entry[newSize];
Array.Copy(entries, 0, newEntries, 0, count);
for (int i = 0; i < count; i++)
{
int bucket = newEntries[i].hashCode % newSize;
newEntries[i].next = newBuckets[bucket];
newBuckets[bucket] = i;
}
buckets = newBuckets;
entries = newEntries;
}
/// <summary>
/// Removes the range.
/// </summary>
/// <param name="keys">The keys.</param>
public void RemoveRange(IEnumerable<TKey> keys)
{
Contract.Requires(keys != null);
TKey[] array = keys as TKey[];
if (array != null)
this.RemoveRange(array);
else
foreach (var key in keys)
{
Contract.Assume(key != null);
this.Remove(key);
}
}
/// <summary>
/// Removes the range.
/// </summary>
/// <param name="keys">The keys.</param>
public void RemoveRange(TKey[] keys)
{
Contract.Requires(keys != null);
foreach (var key in keys)
{
Contract.Assume(key != null);
this.Remove(key);
}
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Remove(TKey key)
{
Contract.Requires(key != null);
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next)
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
{
if (last < 0)
{
buckets[bucket] = entries[i].next;
}
else
{
entries[last].next = entries[i].next;
}
entries[i].hashCode = -1;
entries[i].next = freeList;
entries[i].key = default(TKey);
entries[i].value = default(TValue);
freeList = i;
freeCount++;
#if DEBUG
version++;
#endif
if (freeCount > count / 2)
Shrink();
return true;
}
}
}
return false;
}
internal void InternalRemoveOrFail(TKey key)
{
Contract.Requires(key != null);
if (!this.Remove(key))
Contract.Assert(false);
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool TryGetValue(TKey key, out TValue value)
{
Contract.Requires(key != null);
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
{
value = entries[i].value;
return true;
}
}
}
value = default(TValue);
return false;
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
[Conditional("DEBUG")]
private static void VerifyKey(object key)
{
Contract.Assert(key != null);
Contract.Assert(key is TKey, "bad key");
}
private static bool IsCompatibleKey(object key)
{
Contract.Assert(key != null);
return (key is TKey);
}
[Conditional("DEBUG")]
private static void VerifyValueType(object value)
{
Contract.Assert(
(value is TValue) || (value == null && !typeof(TValue).IsValueType),
"bad value");
}
/// <summary>
///
/// </summary>
[Serializable()]
[StructLayout(LayoutKind.Auto)]
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>,
IDictionaryEnumerator
{
private CDictionary<TKey, TValue> dictionary; // null after Dispose()
#if DEBUG
private int version;
#endif
private int index;
private KeyValuePair<TKey, TValue> current;
private int getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(CDictionary<TKey, TValue> dictionary, int getEnumeratorRetType)
{
Contract.Requires(dictionary != null);
this.dictionary = dictionary;
#if DEBUG
version = dictionary.version;
#endif
index = 0;
this.getEnumeratorRetType = getEnumeratorRetType;
current = new KeyValuePair<TKey, TValue>();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
Contract.Assume(dictionary != null);
#if DEBUG
Contract.Assert(version == dictionary.version, "invalid operation");
#endif
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue
var count = dictionary.count;
var entries = dictionary.entries;
while ((uint)index < (uint)count)
{
if (entries[index].hashCode >= 0)
{
current = new KeyValuePair<TKey, TValue>(entries[index].key, entries[index].value);
index++;
return true;
}
index++;
}
index = count + 1;
current = new KeyValuePair<TKey, TValue>();
return false;
}
/// <summary>
///
/// </summary>
public KeyValuePair<TKey, TValue> Current
{
get { return current; }
}
/// <summary>
///
/// </summary>
public void Dispose()
{
if (dictionary != null)
dictionary = null;
}
object IEnumerator.Current
{
get
{
Contract.Assert(index != 0 && (index != dictionary.count + 1), "invalid operation");
if (getEnumeratorRetType == DictEntry)
{
Contract.Assume(current.Key != null);
return new System.Collections.DictionaryEntry(current.Key, current.Value);
}
else
{
return new KeyValuePair<TKey, TValue>(current.Key, current.Value);
}
}
}
void IEnumerator.Reset()
{
Contract.Assume(dictionary != null);
#if DEBUG
Contract.Assert(version == dictionary.version, "invalid operation");
#endif
index = 0;
current = new KeyValuePair<TKey, TValue>();
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
Contract.Assume(current.Key != null);
Contract.Assert(dictionary != null);
Contract.Assert(index != 0 && (index != dictionary.count + 1), "invalid operation");
return new DictionaryEntry(current.Key, current.Value);
}
}
object IDictionaryEnumerator.Key
{
get
{
Contract.Assert(dictionary != null);
Contract.Assert(index != 0 && (index != dictionary.count + 1), "invalid operation");
return current.Key;
}
}
object IDictionaryEnumerator.Value
{
get
{
Contract.Assert(dictionary != null);
Contract.Assert(index != 0 && (index != dictionary.count + 1), "invalid operation");
return current.Value;
}
}
}
/// <summary>
///
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[Serializable()]
public sealed class KeyCollection : ICollection<TKey>, ICollection
{
private CDictionary<TKey, TValue> dictionary;
/// <summary>
///
/// </summary>
/// <param name="dictionary"></param>
public KeyCollection(CDictionary<TKey, TValue> dictionary)
{
Contract.Requires(dictionary != null);
this.dictionary = dictionary;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Enumerator GetEnumerator()
{
return new Enumerator(dictionary);
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
/// <param name="index"></param>
public void CopyTo(TKey[] array, int index)
{
Contract.Assert(array != null);
Contract.Assert((uint)index <= (uint)array.Length, "index out of range");
Contract.Assert(array.Length - index >= dictionary.Count, "array too small");
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) array[index++] = entries[i].key;
}
}
/// <summary>
///
/// </summary>
public int Count
{
get { return dictionary.Count; }
}
bool ICollection<TKey>.IsReadOnly
{
get { return true; }
}
void ICollection<TKey>.Add(TKey item)
{
Contract.Assert(false, "not supported");
}
void ICollection<TKey>.Clear()
{
Contract.Assert(false, "not supported");
}
/// <summary>
///
/// </summary>
public bool Contains(TKey item)
{
return dictionary.ContainsKey(item);
}
bool ICollection<TKey>.Remove(TKey item)
{
Contract.Assert(false, "not supported");
return false;
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
{
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index)
{
Contract.Assert(array != null);
Contract.Assert(array.Rank == 1, "rank multi dim not supported");
Contract.Assert(array.GetLowerBound(0) == 0, "non zero lower bound");
Contract.Assert((uint)index <= (uint)array.Length, "index out of bounds");
Contract.Assert(array.Length - index >= dictionary.Count, "array too small");
TKey[] keys = array as TKey[];
if (keys != null)
{
CopyTo(keys, index);
}
else
{
object[] objects = array as object[];
Contract.Assert(objects != null);
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) objects[index++] = entries[i].key;
}
}
catch (ArrayTypeMismatchException)
{
Contract.Assert(false, "invalid array type");
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
Object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
///
/// </summary>
[Serializable()]
[StructLayout(LayoutKind.Auto)]
public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator
{
private CDictionary<TKey, TValue> dictionary;
private int index;
#if DEBUG
private int version;
#endif
private TKey currentKey;
internal Enumerator(CDictionary<TKey, TValue> dictionary)
{
this.dictionary = dictionary;
#if DEBUG
version = dictionary.version;
#endif
index = 0;
currentKey = default(TKey);
}
/// <summary>
///
/// </summary>
public void Dispose()
{
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
#if DEBUG
Contract.Assert(version == dictionary.version, "invalid operation");
#endif
var count = dictionary.count;
var entries = dictionary.entries;
while ((uint)index < (uint)count)
{
if (entries[index].hashCode >= 0)
{
currentKey = entries[index].key;
index++;
return true;
}
index++;
}
index = count + 1;
currentKey = default(TKey);
return false;
}
/// <summary>
///
/// </summary>
public TKey Current
{
get
{
return currentKey;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
Contract.Assume(index != 0 && (index != dictionary.count + 1), "invalid operation");
return currentKey;
}
}
void System.Collections.IEnumerator.Reset()
{
#if DEBUG
Contract.Assert(version == dictionary.version, "invalid operation");
#endif
index = 0;
currentKey = default(TKey);
}
}
}
/// <summary>
///
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[Serializable()]
public sealed class ValueCollection : ICollection<TValue>, ICollection
{
private CDictionary<TKey, TValue> dictionary;
/// <summary>
///
/// </summary>
/// <param name="dictionary"></param>
public ValueCollection(CDictionary<TKey, TValue> dictionary)
{
Contract.Requires(dictionary != null);
this.dictionary = dictionary;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Enumerator GetEnumerator()
{
return new Enumerator(dictionary);
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
/// <param name="index"></param>
public void CopyTo(TValue[] array, int index)
{
Contract.Assert(array != null);
Contract.Assert((uint)index <= (uint)array.Length, "index out of range");
Contract.Assert(array.Length - index >= dictionary.Count, "array too small");
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) array[index++] = entries[i].value;
}
}
/// <summary>
///
/// </summary>
public int Count
{
get { return dictionary.Count; }
}
bool ICollection<TValue>.IsReadOnly
{
get { return true; }
}
void ICollection<TValue>.Add(TValue item)
{
Contract.Assert(false, "not supported");
}
bool ICollection<TValue>.Remove(TValue item)
{
Contract.Assert(false, "not supported");
return false;
}
void ICollection<TValue>.Clear()
{
Contract.Assert(false, "not supported");
}
bool ICollection<TValue>.Contains(TValue item)
{
Contract.Assert(false, "not supported");
return false;
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
{
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index)
{
Contract.Assert(array != null);
Contract.Assert(array.Rank == 1, "rank multi dim not supported");
Contract.Assert(array.GetLowerBound(0) == 0, "non zero lower bound");
Contract.Assert((uint)index <= (uint)array.Length, "index out of bounds");
Contract.Assert(array.Length - index >= dictionary.Count, "array too small");
TValue[] values = array as TValue[];
if (values != null)
{
CopyTo(values, index);
}
else
{
object[] objects = array as object[];
Contract.Assert(objects != null);
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) objects[index++] = entries[i].value;
}
}
catch (ArrayTypeMismatchException)
{
Contract.Assert(false, "invalid array type");
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
Object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
///
/// </summary>
[Serializable()]
[StructLayout(LayoutKind.Auto)]
public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator
{
private CDictionary<TKey, TValue> dictionary;
private int index;
#if DEBUG
private int version;
#endif
private TValue currentValue;
internal Enumerator(CDictionary<TKey, TValue> dictionary)
{
this.dictionary = dictionary;
#if DEBUG
version = dictionary.version;
#endif
index = 0;
currentValue = default(TValue);
}
/// <summary>
///
/// </summary>
public void Dispose()
{
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
Contract.Assume(dictionary != null);
#if DEBUG
Contract.Assert(version == dictionary.version, "invalid operation");
#endif
var count = dictionary.count;
var entries = dictionary.entries;
while ((uint)index < (uint)count)
{
if (entries[index].hashCode >= 0)
{
currentValue = entries[index].value;
index++;
return true;
}
index++;
}
index = count + 1;
currentValue = default(TValue);
return false;
}
/// <summary>
///
/// </summary>
public TValue Current
{
get
{
return currentValue;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
Contract.Assert(index != 0 && (index != dictionary.count + 1), "invalid operation");
return currentValue;
}
}
void System.Collections.IEnumerator.Reset()
{
Contract.Assume(dictionary != null);
#if DEBUG
Contract.Assert(version == dictionary.version, "invalid operation");
#endif
index = 0;
currentValue = default(TValue);
}
}
}
/// <summary>
/// enumerate key/value pairs sorted by key
/// </summary>
/// <returns></returns>
public IEnumerable<KeyValuePair<TKey, TValue>> EnumerateInOrder()
{
List<TKey> keys = new List<TKey>(this.Keys);
keys.Sort();
foreach (var key in keys)
yield return new KeyValuePair<TKey, TValue>(key, this[key]);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Csla;
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();
Fetch(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);
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads all <see cref="SupplierList"/> collection items from the given list of SupplierInfoDto.
/// </summary>
/// <param name="data">The list of <see cref="SupplierInfoDto"/>.</param>
private void Fetch(List<SupplierInfoDto> data)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
foreach (var dto in data)
{
Add(DataPortal.FetchChild<SupplierInfo>(dto));
}
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
}
}
| |
namespace AngleSharp.Css.Tests.Declarations
{
using NUnit.Framework;
using static CssConstructionFunctions;
[TestFixture]
public class CssColumnsPropertyTests
{
[Test]
public void CssColumnWidthLengthLegal()
{
var snippet = "column-width: 300px";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("300px", property.Value);
}
[Test]
public void CssColumnWidthPercentIllegal()
{
var snippet = "column-width: 30%";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssColumnWidthVwLegal()
{
var snippet = "column-width: 0.3vw";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0.3vw", property.Value);
}
[Test]
public void CssColumnWidthAutoUppercaseLegal()
{
var snippet = "column-width: AUTO";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("auto", property.Value);
}
[Test]
public void CssColumnCountAutoLowercaseLegal()
{
var snippet = "column-count: auto";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-count", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("auto", property.Value);
}
[Test]
public void CssColumnCountNumberLegal()
{
var snippet = "column-count: 3";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-count", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("3", property.Value);
}
[Test]
public void CssColumnCountZeroLegal()
{
var snippet = "column-count: 0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-count", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0", property.Value);
}
[Test]
public void CssColumsZeroLegal()
{
var snippet = "columns: 0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("columns", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0", property.Value);
}
[Test]
public void CssColumsLengthLegal()
{
var snippet = "columns: 10px";
var property = ParseDeclaration(snippet);
Assert.AreEqual("columns", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("10px", property.Value);
}
[Test]
public void CssColumsNumberLegal()
{
var snippet = "columns: 4";
var property = ParseDeclaration(snippet);
Assert.AreEqual("columns", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("4", property.Value);
}
[Test]
public void CssColumsLengthNumberLegal()
{
var snippet = "columns: 25em 5";
var property = ParseDeclaration(snippet);
Assert.AreEqual("columns", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("25em 5", property.Value);
}
[Test]
public void CssColumsNumberLengthLegal()
{
var snippet = "columns : 5 25em ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("columns", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("25em 5", property.Value);
}
[Test]
public void CssColumsAutoAutoLegal()
{
var snippet = "columns : auto auto";
var property = ParseDeclaration(snippet);
Assert.AreEqual("columns", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("auto auto", property.Value);
}
[Test]
public void CssColumsAutoLegal()
{
var snippet = "columns : auto ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("columns", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("auto", property.Value);
}
[Test]
public void CssColumsNumberPercenIllegal()
{
var snippet = "columns : 5 25% ";
var property = ParseDeclaration(snippet);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssColumSpanAllLegal()
{
var snippet = "column-span: all";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-span", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("all", property.Value);
}
[Test]
public void CssColumSpanNoneUppercaseLegal()
{
var snippet = "column-span: None";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-span", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("none", property.Value);
}
[Test]
public void CssColumSpanLengthIllegal()
{
var snippet = "column-span: 10px";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-span", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssColumGapLengthLegal()
{
var snippet = "column-gap: 20px";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-gap", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("20px", property.Value);
}
[Test]
public void CssColumGapNormalLegal()
{
var snippet = "column-gap: normal";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-gap", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("normal", property.Value);
}
[Test]
public void CssColumGapZeroLegal()
{
var snippet = "column-gap: 0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-gap", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0", property.Value);
}
[Test]
public void CssColumGapPercentLegal()
{
var snippet = "column-gap: 20%";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-gap", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("20%", property.Value);
}
[Test]
public void CssColumFillBalanceLegal()
{
var snippet = "column-fill: balance;";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-fill", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("balance", property.Value);
}
[Test]
public void CssColumFillAutoLegal()
{
var snippet = "column-fill: auto;";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-fill", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("auto", property.Value);
}
[Test]
public void CssColumRuleColorTransparentLegal()
{
var snippet = "column-rule-color: transparent";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(0, 0, 0, 0)", property.Value);
}
[Test]
public void CssColumRuleColorRgbLegal()
{
var snippet = "column-rule-color: rgb(192, 56, 78)";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(192, 56, 78, 1)", property.Value);
}
[Test]
public void CssColumRuleColorRedLegal()
{
var snippet = "column-rule-color: red";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(255, 0, 0, 1)", property.Value);
}
[Test]
public void CssColumRuleColorNoneIllegal()
{
var snippet = "column-rule-color: none";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssColumRuleStyleInsetTailUpperLegal()
{
var snippet = "column-rule-style: inSET";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("inset", property.Value);
}
[Test]
public void CssColumRuleStyleNoneLegal()
{
var snippet = "column-rule-style: none";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("none", property.Value);
}
[Test]
public void CssColumRuleStyleAutoIllegal()
{
var snippet = "column-rule-style: auto ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssColumRuleWidthLengthLegal()
{
var snippet = "column-rule-width: 2px";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("2px", property.Value);
}
[Test]
public void CssColumRuleWidthThickLegal()
{
var snippet = "column-rule-width: thick";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("5px", property.Value);
}
[Test]
public void CssColumRuleWidthMediumLegal()
{
var snippet = "column-rule-width : medium !important ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-width", property.Name);
Assert.IsTrue(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("3px", property.Value);
}
[Test]
public void CssColumRuleWidthThinUppercaseLegal()
{
var snippet = "column-rule-width: THIN";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("1px", property.Value);
}
[Test]
public void CssColumRuleDottedLegal()
{
var snippet = "column-rule: dotted";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("dotted", property.Value);
}
[Test]
public void CssColumRuleSolidBlueLegal()
{
var snippet = "column-rule: solid blue";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(0, 0, 255, 1) solid", property.Value);
}
[Test]
public void CssColumRuleSolidLengthLegal()
{
var snippet = "column-rule: solid 8px";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("8px solid", property.Value);
}
[Test]
public void CssColumRuleThickInsetBlueLegal()
{
var snippet = "column-rule: thick inset blue";
var property = ParseDeclaration(snippet);
Assert.AreEqual("column-rule", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(0, 0, 255, 1) 5px inset", property.Value);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Net;
using System.Reflection;
using Aurora.Simulation.Base;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Aurora.Framework;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services
{
public class AgentHandler
{
private readonly ISimulationService m_SimulationService;
protected bool m_Proxy;
protected IRegistryCore m_registry;
protected bool m_secure = true;
public AgentHandler()
{
}
public AgentHandler(ISimulationService sim, IRegistryCore registry, bool secure)
{
m_registry = registry;
m_SimulationService = sim;
m_secure = secure;
}
public Hashtable Handler(Hashtable request)
{
//MainConsole.Instance.Debug("[CONNECTION DEBUGGING]: AgentHandler Called");
//MainConsole.Instance.Debug("---------------------------");
//MainConsole.Instance.Debug(" >> uri=" + request["uri"]);
//MainConsole.Instance.Debug(" >> content-type=" + request["content-type"]);
//MainConsole.Instance.Debug(" >> http-method=" + request["http-method"]);
//MainConsole.Instance.Debug("---------------------------\n");
Hashtable responsedata = new Hashtable();
responsedata["content_type"] = "text/html";
responsedata["keepalive"] = false;
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = "";
UUID agentID;
UUID regionID;
string action;
string other;
string uri = ((string) request["uri"]);
if (m_secure)
uri = uri.Remove(0, 37); //Remove the secure UUID from the uri
if (!WebUtils.GetParams(uri, out agentID, out regionID, out action, out other))
{
MainConsole.Instance.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]);
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "false";
return responsedata;
}
// Next, let's parse the verb
string method = (string) request["http-method"];
if (method.Equals("PUT"))
{
DoAgentPut(request, responsedata);
return responsedata;
}
else if (method.Equals("POST"))
{
OSDMap map = null;
try
{
string data = request["body"].ToString();
map = (OSDMap) OSDParser.DeserializeJson(data);
}
catch
{
map = null;
}
if (map != null)
{
if (map["Method"] == "MakeChildAgent")
DoMakeChildAgent(agentID, regionID);
else if (map["Method"] == "FailedToMoveAgentIntoNewRegion")
FailedToMoveAgentIntoNewRegion(agentID, regionID);
else
DoAgentPost(request, responsedata, agentID);
}
return responsedata;
}
else if (method.Equals("GET"))
{
DoAgentGet(request, responsedata, agentID, regionID, bool.Parse(action));
return responsedata;
}
else if (method.Equals("DELETE"))
{
DoAgentDelete(request, responsedata, agentID, action, regionID);
return responsedata;
}
else if (method.Equals("QUERYACCESS"))
{
responsedata["int_response_code"] = HttpStatusCode.OK;
OSDMap resp = new OSDMap(2);
resp["success"] = OSD.FromBoolean(true);
resp["reason"] = OSD.FromString("");
responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
return responsedata;
}
else
{
MainConsole.Instance.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message", method);
responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
responsedata["str_response_string"] = "Method not allowed";
return responsedata;
}
}
private void DoMakeChildAgent(UUID agentID, UUID regionID)
{
m_SimulationService.MakeChildAgent(agentID, new GridRegion {RegionID = regionID});
}
public bool FailedToMoveAgentIntoNewRegion(UUID AgentID, UUID RegionID)
{
return m_SimulationService.FailedToMoveAgentIntoNewRegion(AgentID, RegionID);
}
protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
{
OSDMap args = WebUtils.GetOSDMap((string) request["body"]);
if (args == null)
{
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
// retrieve the input arguments
int x = 0, y = 0;
UUID uuid = UUID.Zero;
string regionname = string.Empty;
uint teleportFlags = 0;
if (args.ContainsKey("destination_x") && args["destination_x"] != null)
Int32.TryParse(args["destination_x"].AsString(), out x);
else
MainConsole.Instance.WarnFormat(" -- request didn't have destination_x");
if (args.ContainsKey("destination_y") && args["destination_y"] != null)
Int32.TryParse(args["destination_y"].AsString(), out y);
else
MainConsole.Instance.WarnFormat(" -- request didn't have destination_y");
if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
if (args.ContainsKey("destination_name") && args["destination_name"] != null)
regionname = args["destination_name"].ToString();
if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null)
teleportFlags = args["teleport_flags"].AsUInteger();
AgentData agent = null;
if (args.ContainsKey("agent_data") && args["agent_data"] != null)
{
try
{
OSDMap agentDataMap = (OSDMap) args["agent_data"];
agent = new AgentData();
agent.Unpack(agentDataMap);
}
catch (Exception ex)
{
MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex);
}
}
GridRegion destination = new GridRegion
{RegionID = uuid, RegionLocX = x, RegionLocY = y, RegionName = regionname};
AgentCircuitData aCircuit = new AgentCircuitData();
try
{
aCircuit.UnpackAgentCircuitData(args);
}
catch (Exception ex)
{
MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex);
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
OSDMap resp = new OSDMap(3);
string reason = String.Empty;
int requestedUDPPort = 0;
// This is the meaning of POST agent
bool result = CreateAgent(destination, ref aCircuit, teleportFlags, agent, out requestedUDPPort, out reason);
resp["reason"] = reason;
resp["requestedUDPPort"] = requestedUDPPort;
resp["success"] = OSD.FromBoolean(result);
// Let's also send out the IP address of the caller back to the caller (HG 1.5)
resp["your_ip"] = OSD.FromString(GetCallerIP(request));
// TODO: add reason if not String.Empty?
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
}
private string GetCallerIP(Hashtable request)
{
if (!m_Proxy)
return NetworkUtils.GetCallerIP(request);
// We're behind a proxy
Hashtable headers = (Hashtable) request["headers"];
if (headers.ContainsKey("X-Forwarded-For") && headers["X-Forwarded-For"] != null)
{
IPEndPoint ep = NetworkUtils.GetClientIPFromXFF((string) headers["X-Forwarded-For"]);
if (ep != null)
return ep.Address.ToString();
}
// Oops
return NetworkUtils.GetCallerIP(request);
}
// subclasses can override this
protected virtual bool CreateAgent(GridRegion destination, ref AgentCircuitData aCircuit, uint teleportFlags,
AgentData agent, out int requestedUDPPort, out string reason)
{
return m_SimulationService.CreateAgent(destination, ref aCircuit, teleportFlags, agent, out requestedUDPPort,
out reason);
}
protected void DoAgentPut(Hashtable request, Hashtable responsedata)
{
OSDMap args = WebUtils.GetOSDMap((string) request["body"]);
if (args == null)
{
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
// retrieve the input arguments
int x = 0, y = 0;
UUID uuid = UUID.Zero;
string regionname = string.Empty;
if (args.ContainsKey("destination_x") && args["destination_x"] != null)
Int32.TryParse(args["destination_x"].AsString(), out x);
if (args.ContainsKey("destination_y") && args["destination_y"] != null)
Int32.TryParse(args["destination_y"].AsString(), out y);
if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
if (args.ContainsKey("destination_name") && args["destination_name"] != null)
regionname = args["destination_name"].ToString();
GridRegion destination = new GridRegion
{RegionID = uuid, RegionLocX = x, RegionLocY = y, RegionName = regionname};
string messageType;
if (args["message_type"] != null)
messageType = args["message_type"].AsString();
else
{
MainConsole.Instance.Warn("[AGENT HANDLER]: Agent Put Message Type not found. ");
messageType = "AgentData";
}
bool result = true;
if ("AgentData".Equals(messageType))
{
AgentData agent = new AgentData();
try
{
agent.Unpack(args);
}
catch (Exception ex)
{
MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex);
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
//agent.Dump();
// This is one of the meanings of PUT agent
result = UpdateAgent(destination, agent);
}
else if ("AgentPosition".Equals(messageType))
{
AgentPosition agent = new AgentPosition();
try
{
agent.Unpack(args);
}
catch (Exception ex)
{
MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex);
return;
}
//agent.Dump();
// This is one of the meanings of PUT agent
result = m_SimulationService.UpdateAgent(destination, agent);
}
OSDMap resp = new OSDMap();
resp["Updated"] = result;
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
}
// subclasses can override this
protected virtual bool UpdateAgent(GridRegion destination, AgentData agent)
{
return m_SimulationService.UpdateAgent(destination, agent);
}
protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID,
bool agentIsLeaving)
{
if (m_SimulationService == null)
{
MainConsole.Instance.Debug("[AGENT HANDLER]: Agent GET called. Harmless but useless.");
responsedata["content_type"] = "application/json";
responsedata["int_response_code"] = HttpStatusCode.NotImplemented;
responsedata["str_response_string"] = string.Empty;
return;
}
GridRegion destination = new GridRegion {RegionID = regionID};
AgentData agent = null;
AgentCircuitData circuitData;
bool result = m_SimulationService.RetrieveAgent(destination, id, agentIsLeaving, out agent, out circuitData);
OSDMap map = new OSDMap();
string strBuffer = "";
if (result)
{
if (agent != null) // just to make sure
{
map["AgentData"] = agent.Pack();
map["CircuitData"] = circuitData.PackAgentCircuitData();
try
{
strBuffer = OSDParser.SerializeJsonString(map);
}
catch (Exception e)
{
MainConsole.Instance.WarnFormat("[AGENT HANDLER]: Exception thrown on serialization of DoAgentGet: {0}", e);
responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
// ignore. buffer will be empty, caller should check.
}
}
else
{
map = new OSDMap();
map["Result"] = "Internal error";
}
}
else
{
map = new OSDMap();
map["Result"] = "Not Found";
}
strBuffer = OSDParser.SerializeJsonString(map);
responsedata["content_type"] = "application/json";
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = strBuffer;
}
protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID)
{
MainConsole.Instance.Debug(" >>> DoDelete action:" + action + "; RegionID:" + regionID);
GridRegion destination = new GridRegion {RegionID = regionID};
if (action.Equals("release"))
{
object[] o = new object[2];
o[0] = id;
o[1] = destination;
//This is an OpenSim event... fire an event so that the OpenSim compat handlers can grab it
m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler(
"ReleaseAgent", o);
}
else
m_SimulationService.CloseAgent(destination, id);
responsedata["int_response_code"] = HttpStatusCode.OK;
OSDMap map = new OSDMap();
map["Agent"] = id;
responsedata["str_response_string"] = OSDParser.SerializeJsonString(map);
MainConsole.Instance.Debug("[AGENT HANDLER]: Agent Released/Deleted.");
}
}
}
| |
/*
* 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.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Text;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Mono.Addins;
using Amib.Threading;
/*****************************************************
*
* ScriptsHttpRequests
*
* Implements the llHttpRequest and http_response
* callback.
*
* Some stuff was already in LSLLongCmdHandler, and then
* there was this file with a stub class in it. So,
* I am moving some of the objects and functions out of
* LSLLongCmdHandler, such as the HttpRequestClass, the
* start and stop methods, and setting up pending and
* completed queues. These are processed in the
* LSLLongCmdHandler polling loop. Similiar to the
* XMLRPCModule, since that seems to work.
*
* //TODO
*
* This probably needs some throttling mechanism but
* it's wide open right now. This applies to both
* number of requests and data volume.
*
* Linden puts all kinds of header fields in the requests.
* Not doing any of that:
* User-Agent
* X-SecondLife-Shard
* X-SecondLife-Object-Name
* X-SecondLife-Object-Key
* X-SecondLife-Region
* X-SecondLife-Local-Position
* X-SecondLife-Local-Velocity
* X-SecondLife-Local-Rotation
* X-SecondLife-Owner-Name
* X-SecondLife-Owner-Key
*
* HTTPS support
*
* Configurable timeout?
* Configurable max response size?
* Configurable
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HttpRequestModule")]
public class HttpRequestModule : ISharedRegionModule, IHttpRequestModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private object HttpListLock = new object();
private int httpTimeout = 30000;
private string m_name = "HttpScriptRequests";
private OutboundUrlFilter m_outboundUrlFilter;
private string m_proxyurl = "";
private string m_proxyexcepts = "";
// <request id, HttpRequestClass>
private Dictionary<UUID, HttpRequestClass> m_pendingRequests;
private Scene m_scene;
// private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>();
public static SmartThreadPool ThreadPool = null;
public HttpRequestModule()
{
}
#region IHttpRequestModule Members
public UUID MakeHttpRequest(string url, string parameters, string body)
{
return UUID.Zero;
}
public UUID StartHttpRequest(
uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body,
out HttpInitialRequestStatus status)
{
UUID reqID = UUID.Random();
HttpRequestClass htc = new HttpRequestClass();
// Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/LlHTTPRequest
//
// Parameters are expected in {key, value, ... , key, value}
if (parameters != null)
{
string[] parms = parameters.ToArray();
for (int i = 0; i < parms.Length; i += 2)
{
switch (Int32.Parse(parms[i]))
{
case (int)HttpRequestConstants.HTTP_METHOD:
htc.HttpMethod = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_MIMETYPE:
htc.HttpMIMEType = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
int len;
if(int.TryParse(parms[i + 1], out len))
{
if(len > HttpRequestClass.HttpBodyMaxLenMAX)
len = HttpRequestClass.HttpBodyMaxLenMAX;
else if(len < 64) //???
len = 64;
htc.HttpBodyMaxLen = len;
}
break;
case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
break;
case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:
// TODO implement me
break;
case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
//Parameters are in pairs and custom header takes
//arguments in pairs so adjust for header marker.
++i;
//Maximum of 8 headers are allowed based on the
//Second Life documentation for llHTTPRequest.
for (int count = 1; count <= 8; ++count)
{
//Not enough parameters remaining for a header?
if (parms.Length - i < 2)
break;
if (htc.HttpCustomHeaders == null)
htc.HttpCustomHeaders = new List<string>();
htc.HttpCustomHeaders.Add(parms[i]);
htc.HttpCustomHeaders.Add(parms[i+1]);
int nexti = i + 2;
if (nexti >= parms.Length || Char.IsDigit(parms[nexti][0]))
break;
i = nexti;
}
break;
case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0);
break;
}
}
}
htc.RequestModule = this;
htc.LocalID = localID;
htc.ItemID = itemID;
htc.Url = url;
htc.ReqID = reqID;
htc.HttpTimeout = httpTimeout;
htc.OutboundBody = body;
htc.ResponseHeaders = headers;
htc.proxyurl = m_proxyurl;
htc.proxyexcepts = m_proxyexcepts;
// Same number as default HttpWebRequest.MaximumAutomaticRedirections
htc.MaxRedirects = 50;
if (StartHttpRequest(htc))
{
status = HttpInitialRequestStatus.OK;
return htc.ReqID;
}
else
{
status = HttpInitialRequestStatus.DISALLOWED_BY_FILTER;
return UUID.Zero;
}
}
/// <summary>
/// Would a caller to this module be allowed to make a request to the given URL?
/// </summary>
/// <returns></returns>
public bool CheckAllowed(Uri url)
{
return m_outboundUrlFilter.CheckAllowed(url);
}
public bool StartHttpRequest(HttpRequestClass req)
{
if (!CheckAllowed(new Uri(req.Url)))
return false;
lock (HttpListLock)
{
m_pendingRequests.Add(req.ReqID, req);
}
req.Process();
return true;
}
public void StopHttpRequest(uint m_localID, UUID m_itemID)
{
if (m_pendingRequests != null)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
{
tmpReq.Stop();
m_pendingRequests.Remove(m_itemID);
}
}
}
}
/*
* TODO
* Not sure how important ordering is is here - the next first
* one completed in the list is returned, based soley on its list
* position, not the order in which the request was started or
* finished. I thought about setting up a queue for this, but
* it will need some refactoring and this works 'enough' right now
*/
public IServiceRequest GetNextCompletedRequest()
{
lock (HttpListLock)
{
foreach (UUID luid in m_pendingRequests.Keys)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(luid, out tmpReq))
{
if (tmpReq.Finished)
{
return tmpReq;
}
}
}
}
return null;
}
public void RemoveCompletedRequest(UUID id)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(id, out tmpReq))
{
tmpReq.Stop();
tmpReq = null;
m_pendingRequests.Remove(id);
}
}
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
HttpRequestClass.HttpBodyMaxLenMAX = config.Configs["Network"].GetInt("HttpBodyMaxLenMAX", 16384);
m_outboundUrlFilter = new OutboundUrlFilter("Script HTTP request module", config);
int maxThreads = 15;
IConfig httpConfig = config.Configs["HttpRequestModule"];
if (httpConfig != null)
{
maxThreads = httpConfig.GetInt("MaxPoolThreads", maxThreads);
}
m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
// First instance sets this up for all sims
if (ThreadPool == null)
{
STPStartInfo startInfo = new STPStartInfo();
startInfo.IdleTimeout = 2000;
startInfo.MaxWorkerThreads = maxThreads;
startInfo.MinWorkerThreads = 0;
startInfo.ThreadPriority = ThreadPriority.BelowNormal;
startInfo.StartSuspended = true;
startInfo.ThreadPoolName = "ScriptsHttpReq";
ThreadPool = new SmartThreadPool(startInfo);
ThreadPool.Start();
}
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
}
public void RemoveRegion(Scene scene)
{
scene.UnregisterModuleInterface<IHttpRequestModule>(this);
if (scene == m_scene)
m_scene = null;
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void Close()
{
ThreadPool.Shutdown();
}
public string Name
{
get { return m_name; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
}
public class HttpRequestClass : IServiceRequest
{
// Constants for parameters
// public const int HTTP_BODY_MAXLENGTH = 2;
// public const int HTTP_METHOD = 0;
// public const int HTTP_MIMETYPE = 1;
// public const int HTTP_VERIFY_CERT = 3;
// public const int HTTP_VERBOSE_THROTTLE = 4;
// public const int HTTP_CUSTOM_HEADER = 5;
// public const int HTTP_PRAGMA_NO_CACHE = 6;
/// <summary>
/// Module that made this request.
/// </summary>
public HttpRequestModule RequestModule { get; set; }
private bool _finished;
public bool Finished
{
get { return _finished; }
}
public static int HttpBodyMaxLenMAX = 16384;
// Parameter members and default values
public int HttpBodyMaxLen = 2048;
public string HttpMethod = "GET";
public string HttpMIMEType = "text/plain;charset=utf-8";
public int HttpTimeout;
public bool HttpVerifyCert = true;
public IWorkItemResult WorkItem = null;
//public bool HttpVerboseThrottle = true; // not implemented
public List<string> HttpCustomHeaders = null;
public bool HttpPragmaNoCache = true;
// Request info
private UUID _itemID;
public UUID ItemID
{
get { return _itemID; }
set { _itemID = value; }
}
private uint _localID;
public uint LocalID
{
get { return _localID; }
set { _localID = value; }
}
public DateTime Next;
public string proxyurl;
public string proxyexcepts;
/// <summary>
/// Number of HTTP redirects that this request has been through.
/// </summary>
public int Redirects { get; private set; }
/// <summary>
/// Maximum number of HTTP redirects allowed for this request.
/// </summary>
public int MaxRedirects { get; set; }
public string OutboundBody;
private UUID _reqID;
public UUID ReqID
{
get { return _reqID; }
set { _reqID = value; }
}
public HttpWebRequest Request;
public string ResponseBody;
public List<string> ResponseMetadata;
public Dictionary<string, string> ResponseHeaders;
public int Status;
public string Url;
public void Process()
{
_finished = false;
lock (HttpRequestModule.ThreadPool)
WorkItem = HttpRequestModule.ThreadPool.QueueWorkItem(new WorkItemCallback(StpSendWrapper), null);
}
private object StpSendWrapper(object o)
{
SendRequest();
return null;
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
// If this is a web request we need to check the headers first
// We may want to ignore SSL
if (sender is HttpWebRequest)
{
HttpWebRequest Request = (HttpWebRequest)sender;
ServicePoint sp = Request.ServicePoint;
// We don't case about encryption, get out of here
if (Request.Headers.Get("NoVerifyCert") != null)
{
return true;
}
// If there was an upstream cert verification error, bail
if ((((int)sslPolicyErrors) & ~4) != 0)
return false;
// Check for policy and execute it if defined
#pragma warning disable 0618
if (ServicePointManager.CertificatePolicy != null)
{
return ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, Request, 0);
}
#pragma warning restore 0618
return true;
}
// If it's not HTTP, trust .NET to check it
if ((((int)sslPolicyErrors) & ~4) != 0)
return false;
return true;
}
/*
* TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception
*/
public void SendRequest()
{
HttpWebResponse response = null;
Stream resStream = null;
byte[] buf = new byte[HttpBodyMaxLenMAX + 16];
string tempString = null;
int count = 0;
try
{
Request = (HttpWebRequest)WebRequest.Create(Url);
Request.ServerCertificateValidationCallback = ValidateServerCertificate;
Request.AllowAutoRedirect = false;
Request.KeepAlive = false;
//This works around some buggy HTTP Servers like Lighttpd
Request.ServicePoint.Expect100Continue = false;
Request.Method = HttpMethod;
Request.ContentType = HttpMIMEType;
if (!HttpVerifyCert)
{
// We could hijack Connection Group Name to identify
// a desired security exception. But at the moment we'll use a dummy header instead.
Request.Headers.Add("NoVerifyCert", "true");
}
// else
// {
// Request.ConnectionGroupName="Verify";
// }
if (!HttpPragmaNoCache)
{
Request.Headers.Add("Pragma", "no-cache");
}
if (HttpCustomHeaders != null)
{
for (int i = 0; i < HttpCustomHeaders.Count; i += 2)
Request.Headers.Add(HttpCustomHeaders[i],
HttpCustomHeaders[i+1]);
}
if (!string.IsNullOrEmpty(proxyurl))
{
if (!string.IsNullOrEmpty(proxyexcepts))
{
string[] elist = proxyexcepts.Split(';');
Request.Proxy = new WebProxy(proxyurl, true, elist);
}
else
{
Request.Proxy = new WebProxy(proxyurl, true);
}
}
foreach (KeyValuePair<string, string> entry in ResponseHeaders)
if (entry.Key.ToLower().Equals("user-agent"))
Request.UserAgent = entry.Value;
else
Request.Headers[entry.Key] = entry.Value;
// Encode outbound data
if (!string.IsNullOrEmpty(OutboundBody))
{
byte[] data = Util.UTF8.GetBytes(OutboundBody);
Request.ContentLength = data.Length;
using (Stream bstream = Request.GetRequestStream())
bstream.Write(data, 0, data.Length);
}
Request.Timeout = HttpTimeout;
try
{
// execute the request
response = (HttpWebResponse) Request.GetResponse();
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.ProtocolError)
{
throw;
}
response = (HttpWebResponse)e.Response;
}
Status = (int)response.StatusCode;
resStream = response.GetResponseStream();
int totalBodyBytes = 0;
int maxBytes = HttpBodyMaxLen;
if(maxBytes > buf.Length)
maxBytes = buf.Length;
// we need to read all allowed or UFT8 conversion may fail
do
{
// fill the buffer with data
count = resStream.Read(buf, totalBodyBytes, maxBytes - totalBodyBytes);
totalBodyBytes += count;
if (totalBodyBytes >= maxBytes)
break;
} while (count > 0); // any more data to read?
if(totalBodyBytes > 0)
{
tempString = Util.UTF8.GetString(buf, 0, totalBodyBytes);
ResponseBody = tempString.Replace("\r", "");
}
else
ResponseBody = "";
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse webRsp = (HttpWebResponse)((WebException)e).Response;
Status = (int)webRsp.StatusCode;
try
{
using (Stream responseStream = webRsp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
ResponseBody = reader.ReadToEnd();
}
}
catch
{
ResponseBody = webRsp.StatusDescription;
}
}
else
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = e.Message;
}
}
// catch (Exception e)
catch
{
// Don't crash on anything else
}
finally
{
if (resStream != null)
resStream.Close();
if (response != null)
response.Close();
// We need to resubmit
if (
(Status == (int)HttpStatusCode.MovedPermanently
|| Status == (int)HttpStatusCode.Found
|| Status == (int)HttpStatusCode.SeeOther
|| Status == (int)HttpStatusCode.TemporaryRedirect))
{
if (Redirects >= MaxRedirects)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "Number of redirects exceeded max redirects";
_finished = true;
}
else
{
string location = response.Headers["Location"];
if (location == null)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "HTTP redirect code but no location header";
_finished = true;
}
else if (!RequestModule.CheckAllowed(new Uri(location)))
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "URL from HTTP redirect blocked: " + location;
_finished = true;
}
else
{
Status = 0;
Url = response.Headers["Location"];
Redirects++;
ResponseBody = null;
// m_log.DebugFormat("Redirecting to [{0}]", Url);
Process();
}
}
}
else
{
_finished = true;
if (ResponseBody == null)
ResponseBody = String.Empty;
}
}
}
public void Stop()
{
try
{
if (!WorkItem.Cancel())
{
WorkItem.Cancel(true);
}
}
catch (Exception)
{
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalUInt321()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogicalUInt321
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(UInt32);
private const int RetElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector256<UInt32> _clsVar;
private Vector256<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static SimpleUnaryOpTest__ShiftRightLogicalUInt321()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightLogicalUInt321()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ShiftRightLogical(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ShiftRightLogical(
Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ShiftRightLogical(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ShiftRightLogical(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt321();
var result = Avx2.ShiftRightLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ShiftRightLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
if ((uint)(firstOp[0] >> 1) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((uint)(firstOp[i] >> 1) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<UInt32>(Vector256<UInt32><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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.DirectoryServices.Protocols;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
public abstract class HttpClientHandler_Cancellation_Test : HttpClientHandlerTestBase
{
public HttpClientHandler_Cancellation_Test(ITestOutputHelper output) : base(output) { }
[Theory]
[InlineData(false, CancellationMode.Token)]
[InlineData(true, CancellationMode.Token)]
public async Task PostAsync_CancelDuringRequestContentSend_TaskCanceledQuickly(bool chunkedTransfer, CancellationMode mode)
{
if (!UseSocketsHttpHandler)
{
// Issue #27063: hangs / doesn't cancel
return;
}
if (LoopbackServerFactory.IsHttp2 && chunkedTransfer)
{
// There is no chunked encoding in HTTP/2
return;
}
var serverRelease = new TaskCompletionSource<bool>();
await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
{
try
{
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
var waitToSend = new TaskCompletionSource<bool>();
var contentSending = new TaskCompletionSource<bool>();
var req = new HttpRequestMessage(HttpMethod.Post, uri) { Version = VersionFromUseHttp2 };
req.Content = new ByteAtATimeContent(int.MaxValue, waitToSend.Task, contentSending, millisecondDelayBetweenBytes: 1);
req.Headers.TransferEncodingChunked = chunkedTransfer;
Task<HttpResponseMessage> resp = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
waitToSend.SetResult(true);
await contentSending.Task;
Cancel(mode, client, cts);
await ValidateClientCancellationAsync(() => resp);
}
}
finally
{
serverRelease.SetResult(true);
}
}, async server =>
{
try
{
await server.AcceptConnectionAsync(connection => serverRelease.Task);
}
catch { }; // Ignore any closing errors since we did not really process anything.
});
}
[Theory]
[MemberData(nameof(OneBoolAndCancellationMode))]
public async Task GetAsync_CancelDuringResponseHeadersReceived_TaskCanceledQuickly(bool connectionClose, CancellationMode mode)
{
if (LoopbackServerFactory.IsHttp2 && connectionClose)
{
// There is no Connection header in HTTP/2
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
var partialResponseHeadersSent = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestDataAsync();
await connection.SendResponseAsync(HttpStatusCode.OK, content: null, isFinal: false);
partialResponseHeadersSent.TrySetResult(true);
await clientFinished.Task;
});
await ValidateClientCancellationAsync(async () =>
{
var req = new HttpRequestMessage(HttpMethod.Get, url) { Version = VersionFromUseHttp2 };
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
await partialResponseHeadersSent.Task;
Cancel(mode, client, cts);
await getResponse;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[MemberData(nameof(TwoBoolsAndCancellationMode))]
public async Task GetAsync_CancelDuringResponseBodyReceived_Buffered_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, CancellationMode mode)
{
if (LoopbackServerFactory.IsHttp2 && (chunkedTransfer || connectionClose))
{
// There is no chunked encoding or connection header in HTTP/2
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
var responseHeadersSent = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
var headers = new List<HttpHeaderData>();
headers.Add(chunkedTransfer ? new HttpHeaderData("Transfer-Encoding", "chunked") : new HttpHeaderData("Content-Length", "20"));
if (connectionClose)
{
headers.Add(new HttpHeaderData("Connection", "close"));
}
await connection.ReadRequestDataAsync();
await connection.SendResponseAsync(HttpStatusCode.OK, headers: headers, content: "123", isFinal: false);
responseHeadersSent.TrySetResult(true);
await clientFinished.Task;
});
await ValidateClientCancellationAsync(async () =>
{
var req = new HttpRequestMessage(HttpMethod.Get, url) { Version = VersionFromUseHttp2 };
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseContentRead, cts.Token);
await responseHeadersSent.Task;
await Task.Delay(1); // make it more likely that client will have started processing response body
Cancel(mode, client, cts);
await getResponse;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[MemberData(nameof(ThreeBools))]
public async Task GetAsync_CancelDuringResponseBodyReceived_Unbuffered_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, bool readOrCopyToAsync)
{
if (IsCurlHandler)
{
// doesn't cancel
return;
}
if (LoopbackServerFactory.IsHttp2 && (chunkedTransfer || connectionClose))
{
// There is no chunked encoding or connection header in HTTP/2
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
var headers = new List<HttpHeaderData>();
headers.Add(chunkedTransfer ? new HttpHeaderData("Transfer-Encoding", "chunked") : new HttpHeaderData("Content-Length", "20"));
if (connectionClose)
{
headers.Add(new HttpHeaderData("Connection", "close"));
}
await connection.ReadRequestDataAsync();
await connection.SendResponseAsync(HttpStatusCode.OK, headers: headers, isFinal: false);
await clientFinished.Task;
});
var req = new HttpRequestMessage(HttpMethod.Get, url) { Version = VersionFromUseHttp2 };
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
await ValidateClientCancellationAsync(async () =>
{
HttpResponseMessage resp = await getResponse;
Stream respStream = await resp.Content.ReadAsStreamAsync();
Task readTask = readOrCopyToAsync ?
respStream.ReadAsync(new byte[1], 0, 1, cts.Token) :
respStream.CopyToAsync(Stream.Null, 10, cts.Token);
cts.Cancel();
await readTask;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[InlineData(CancellationMode.CancelPendingRequests, false)]
[InlineData(CancellationMode.DisposeHttpClient, false)]
[InlineData(CancellationMode.CancelPendingRequests, true)]
[InlineData(CancellationMode.DisposeHttpClient, true)]
public async Task GetAsync_CancelPendingRequests_DoesntCancelReadAsyncOnResponseStream(CancellationMode mode, bool copyToAsync)
{
if (IsCurlHandler)
{
// Issue #27065
// throws OperationCanceledException from Stream.CopyToAsync/ReadAsync
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
var clientReadSomeBody = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
var responseContentSegment = new string('s', 3000);
int responseSegments = 4;
int contentLength = responseContentSegment.Length * responseSegments;
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestDataAsync();
await connection.SendResponseAsync(HttpStatusCode.OK, headers: new HttpHeaderData[] { new HttpHeaderData("Content-Length", contentLength.ToString()) }, isFinal: false);
for (int i = 0; i < responseSegments; i++)
{
await connection.SendResponseBodyAsync(responseContentSegment, isFinal: i == responseSegments - 1);
if (i == 0)
{
await clientReadSomeBody.Task;
}
}
await clientFinished.Task;
});
using (HttpResponseMessage resp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
using (Stream respStream = await resp.Content.ReadAsStreamAsync())
{
var result = new MemoryStream();
int b = respStream.ReadByte();
Assert.NotEqual(-1, b);
result.WriteByte((byte)b);
Cancel(mode, client, null); // should not cancel the operation, as using ResponseHeadersRead
clientReadSomeBody.SetResult(true);
if (copyToAsync)
{
await respStream.CopyToAsync(result, 10, new CancellationTokenSource().Token);
}
else
{
byte[] buffer = new byte[10];
int bytesRead;
while ((bytesRead = await respStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
result.Write(buffer, 0, bytesRead);
}
}
Assert.Equal(contentLength, result.Length);
}
clientFinished.SetResult(true);
await serverTask;
});
}
}
[ConditionalFact]
public async Task MaxConnectionsPerServer_WaitingConnectionsAreCancelable()
{
if (IsCurlHandler)
{
// With CurlHandler, this test sometimes hangs.
throw new SkipTestException("Skipping on unstable platform handler");
}
if (LoopbackServerFactory.IsHttp2)
{
// HTTP/2 does not use connection limits.
throw new SkipTestException("Not supported on HTTP/2");
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
handler.MaxConnectionsPerServer = 1;
client.Timeout = Timeout.InfiniteTimeSpan;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var serverAboutToBlock = new TaskCompletionSource<bool>();
var blockServerResponse = new TaskCompletionSource<bool>();
Task serverTask1 = server.AcceptConnectionAsync(async connection1 =>
{
await connection1.ReadRequestHeaderAsync();
await connection1.Writer.WriteAsync($"HTTP/1.1 200 OK\r\nConnection: close\r\nDate: {DateTimeOffset.UtcNow:R}\r\n");
serverAboutToBlock.SetResult(true);
await blockServerResponse.Task;
await connection1.Writer.WriteAsync("Content-Length: 5\r\n\r\nhello");
});
Task get1 = client.GetAsync(url);
await serverAboutToBlock.Task;
var cts = new CancellationTokenSource();
Task get2 = ValidateClientCancellationAsync(() => client.GetAsync(url, cts.Token));
Task get3 = ValidateClientCancellationAsync(() => client.GetAsync(url, cts.Token));
Task get4 = client.GetAsync(url);
cts.Cancel();
await get2;
await get3;
blockServerResponse.SetResult(true);
await new[] { get1, serverTask1 }.WhenAllOrAnyFailed();
Task serverTask4 = server.AcceptConnectionSendResponseAndCloseAsync();
await new[] { get4, serverTask4 }.WhenAllOrAnyFailed();
});
}
}
[Fact]
public async Task SendAsync_Cancel_CancellationTokenPropagates()
{
TaskCompletionSource<bool> clientCanceled = new TaskCompletionSource<bool>();
await LoopbackServerFactory.CreateClientAndServerAsync(
async uri =>
{
var cts = new CancellationTokenSource();
cts.Cancel();
using (HttpClient client = CreateHttpClient())
{
OperationCanceledException ex = null;
try
{
await client.GetAsync(uri, cts.Token);
}
catch (OperationCanceledException e)
{
ex = e;
}
Assert.True(ex != null, "Expected OperationCancelledException, but no exception was thrown.");
Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested");
// .NET Framework has bug where it doesn't propagate token information.
Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested");
clientCanceled.SetResult(true);
}
},
async server =>
{
Task serverTask = server.HandleRequestAsync();
await clientCanceled.Task;
});
}
public static IEnumerable<object[]> PostAsync_Cancel_CancellationTokenPassedToContent_MemberData()
{
// Note: For HTTP2, the actual token will be a linked token and will not be an exact match for the original token.
// Verify that it behaves as expected by cancelling it and validating that cancellation propagates.
// StreamContent
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
var actualToken = new StrongBox<CancellationToken>();
bool called = false;
var content = new StreamContent(new DelegateStream(
canReadFunc: () => true,
readAsyncFunc: (buffer, offset, count, cancellationToken) =>
{
int result = 1;
if (called)
{
result = 0;
Assert.False(cancellationToken.IsCancellationRequested);
tokenSource.Cancel();
Assert.True(cancellationToken.IsCancellationRequested);
}
called = true;
return Task.FromResult(result);
}
));
yield return new object[] { content, tokenSource };
}
// MultipartContent
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
var actualToken = new StrongBox<CancellationToken>();
bool called = false;
var content = new MultipartContent();
content.Add(new StreamContent(new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => true,
lengthFunc: () => 1,
positionGetFunc: () => 0,
positionSetFunc: _ => {},
readAsyncFunc: (buffer, offset, count, cancellationToken) =>
{
int result = 1;
if (called)
{
result = 0;
Assert.False(cancellationToken.IsCancellationRequested);
tokenSource.Cancel();
Assert.True(cancellationToken.IsCancellationRequested);
}
called = true;
return Task.FromResult(result);
}
)));
yield return new object[] { content, tokenSource };
}
// MultipartFormDataContent
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
var actualToken = new StrongBox<CancellationToken>();
bool called = false;
var content = new MultipartFormDataContent();
content.Add(new StreamContent(new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => true,
lengthFunc: () => 1,
positionGetFunc: () => 0,
positionSetFunc: _ => {},
readAsyncFunc: (buffer, offset, count, cancellationToken) =>
{
int result = 1;
if (called)
{
result = 0;
Assert.False(cancellationToken.IsCancellationRequested);
tokenSource.Cancel();
Assert.True(cancellationToken.IsCancellationRequested);
}
called = true;
return Task.FromResult(result);
}
)));
yield return new object[] { content, tokenSource };
}
}
[OuterLoop("Uses Task.Delay")]
[Theory]
[MemberData(nameof(PostAsync_Cancel_CancellationTokenPassedToContent_MemberData))]
public async Task PostAsync_Cancel_CancellationTokenPassedToContent(HttpContent content, CancellationTokenSource cancellationTokenSource)
{
await LoopbackServerFactory.CreateClientAndServerAsync(
async uri =>
{
using (var invoker = new HttpMessageInvoker(CreateHttpClientHandler()))
using (var req = new HttpRequestMessage(HttpMethod.Post, uri) { Content = content, Version = VersionFromUseHttp2 })
try
{
using (HttpResponseMessage resp = await invoker.SendAsync(req, cancellationTokenSource.Token))
{
Assert.Equal("Hello World", await resp.Content.ReadAsStringAsync());
}
}
catch (OperationCanceledException) { }
},
async server =>
{
try
{
await server.HandleRequestAsync(content: "Hello World");
}
catch (Exception) { }
});
}
private async Task ValidateClientCancellationAsync(Func<Task> clientBodyAsync)
{
var stopwatch = Stopwatch.StartNew();
Exception error = await Record.ExceptionAsync(clientBodyAsync);
stopwatch.Stop();
Assert.NotNull(error);
Assert.True(
error is OperationCanceledException,
"Expected cancellation exception, got:" + Environment.NewLine + error);
Assert.True(stopwatch.Elapsed < new TimeSpan(0, 0, 60), $"Elapsed time {stopwatch.Elapsed} should be less than 60 seconds, was {stopwatch.Elapsed.TotalSeconds}");
}
private static void Cancel(CancellationMode mode, HttpClient client, CancellationTokenSource cts)
{
if ((mode & CancellationMode.Token) != 0)
{
cts?.Cancel();
}
if ((mode & CancellationMode.CancelPendingRequests) != 0)
{
client?.CancelPendingRequests();
}
if ((mode & CancellationMode.DisposeHttpClient) != 0)
{
client?.Dispose();
}
}
[Flags]
public enum CancellationMode
{
Token = 0x1,
CancelPendingRequests = 0x2,
DisposeHttpClient = 0x4
}
private static readonly bool[] s_bools = new[] { true, false };
public static IEnumerable<object[]> OneBoolAndCancellationMode() =>
from first in s_bools
from mode in new[] { CancellationMode.Token, CancellationMode.CancelPendingRequests, CancellationMode.DisposeHttpClient, CancellationMode.Token | CancellationMode.CancelPendingRequests }
select new object[] { first, mode };
public static IEnumerable<object[]> TwoBoolsAndCancellationMode() =>
from first in s_bools
from second in s_bools
from mode in new[] { CancellationMode.Token, CancellationMode.CancelPendingRequests, CancellationMode.DisposeHttpClient, CancellationMode.Token | CancellationMode.CancelPendingRequests }
select new object[] { first, second, mode };
public static IEnumerable<object[]> ThreeBools() =>
from first in s_bools
from second in s_bools
from third in s_bools
select new object[] { first, second, third };
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Scripting;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests
{
public class ScriptTests : TestBase
{
public class Globals
{
public int X;
public int Y;
}
[Fact]
public void TestCreateScript()
{
var script = CSharpScript.Create("1 + 2");
Assert.Equal("1 + 2", script.Code);
}
[Fact]
public async Task TestGetCompilation()
{
var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests());
var compilation = state.Script.GetCompilation();
Assert.Equal(state.Script.Code, compilation.SyntaxTrees.First().GetText().ToString());
}
[Fact]
public void TestCreateScriptDelegate()
{
// create a delegate for the entire script
var script = CSharpScript.Create("1 + 2");
var fn = script.CreateDelegate();
Assert.Equal(3, fn().Result);
Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object()));
}
[Fact]
public void TestCreateScriptDelegateWithGlobals()
{
// create a delegate for the entire script
var script = CSharpScript.Create<int>("X + Y", globalsType: typeof(Globals));
var fn = script.CreateDelegate();
Assert.ThrowsAsync<ArgumentException>("globals", () => fn());
Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object()));
Assert.Equal(4, fn(new Globals { X = 1, Y = 3 }).Result);
}
[Fact]
public async Task TestRunScript()
{
var state = await CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestCreateAndRunScript()
{
var script = CSharpScript.Create("1 + 2");
var state = await script.RunAsync();
Assert.Same(script, state.Script);
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestEvalScript()
{
var value = await CSharpScript.EvaluateAsync("1 + 2");
Assert.Equal(3, value);
}
[Fact]
public async Task TestRunScriptWithSpecifiedReturnType()
{
var state = await CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestRunVoidScript()
{
var state = await CSharpScript.RunAsync("System.Console.WriteLine(0);");
Assert.Null(state.ReturnValue);
}
[WorkItem(5279, "https://github.com/dotnet/roslyn/issues/5279")]
[Fact]
public async void TestRunExpressionStatement()
{
var state = await CSharpScript.RunAsync(
@"int F() { return 1; }
F();");
Assert.Null(state.ReturnValue);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public void TestRunDynamicVoidScriptWithTerminatingSemicolon()
{
var result = CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do();"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public void TestRunDynamicVoidScriptWithoutTerminatingSemicolon()
{
var result = CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do()"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[Fact]
public async Task TestRunScriptWithGlobals()
{
var state = await CSharpScript.RunAsync("X + Y", globals: new Globals { X = 1, Y = 2 });
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestRunCreatedScriptWithExpectedGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
var state = await script.RunAsync(new Globals { X = 1, Y = 2 });
Assert.Equal(3, state.ReturnValue);
Assert.Same(script, state.Script);
}
[Fact]
public void TestRunCreatedScriptWithUnexpectedGlobals()
{
var script = CSharpScript.Create("X + Y");
// Global variables passed to a script without a global type
Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new Globals { X = 1, Y = 2 }));
}
[Fact]
public void TestRunCreatedScriptWithoutGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
// The script requires access to global variables but none were given
Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync());
}
[Fact]
public void TestRunCreatedScriptWithMismatchedGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
// The globals of type 'System.Object' is not assignable to 'Microsoft.CodeAnalysis.CSharp.Scripting.Test.ScriptTests+Globals'
Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new object()));
}
[Fact]
public async Task ContinueAsync_Error1()
{
var state = await CSharpScript.RunAsync("X + Y", globals: new Globals());
await Assert.ThrowsAsync<ArgumentNullException>("previousState", () => state.Script.RunFromAsync(null));
}
[Fact]
public async Task ContinueAsync_Error2()
{
var state1 = await CSharpScript.RunAsync("X + Y + 1", globals: new Globals());
var state2 = await CSharpScript.RunAsync("X + Y + 2", globals: new Globals());
await Assert.ThrowsAsync<ArgumentException>("previousState", () => state1.Script.RunFromAsync(state2));
}
[Fact]
public async Task TestRunScriptWithScriptState()
{
// run a script using another scripts end state as the starting state (globals)
var state = await CSharpScript.RunAsync("int X = 100;").ContinueWith("X + X");
Assert.Equal(200, state.ReturnValue);
}
[Fact]
public async Task TestRepl()
{
string[] submissions = new[]
{
"int x = 100;",
"int y = x * x;",
"x + y"
};
var state = await CSharpScript.RunAsync("");
foreach (var submission in submissions)
{
state = await state.ContinueWithAsync(submission);
}
Assert.Equal(10100, state.ReturnValue);
}
#if TODO // https://github.com/dotnet/roslyn/issues/3720
[Fact]
public void TestCreateMethodDelegate()
{
// create a delegate to a method declared in the script
var state = CSharpScript.Run("int Times(int x) { return x * x; }");
var fn = state.CreateDelegate<Func<int, int>>("Times");
var result = fn(5);
Assert.Equal(25, result);
}
#endif
[Fact]
public async Task ScriptVariables_Chain()
{
var globals = new Globals { X = 10, Y = 20 };
var script =
CSharpScript.Create(
"var a = '1';",
globalsType: globals.GetType()).
ContinueWith("var b = 2u;").
ContinueWith("var a = 3m;").
ContinueWith("var x = a + b;").
ContinueWith("var X = Y;");
var state = await script.RunAsync(globals);
AssertEx.Equal(new[] { "a", "b", "a", "x", "X" }, state.Variables.Select(v => v.Name));
AssertEx.Equal(new object[] { '1', 2u, 3m, 5m, 20 }, state.Variables.Select(v => v.Value));
AssertEx.Equal(new Type[] { typeof(char), typeof(uint), typeof(decimal), typeof(decimal), typeof(int) }, state.Variables.Select(v => v.Type));
Assert.Equal(3m, state.GetVariable("a").Value);
Assert.Equal(2u, state.GetVariable("b").Value);
Assert.Equal(5m, state.GetVariable("x").Value);
Assert.Equal(20, state.GetVariable("X").Value);
Assert.Equal(null, state.GetVariable("A"));
Assert.Same(state.GetVariable("X"), state.GetVariable("X"));
}
[Fact]
public async Task ScriptVariable_SetValue()
{
var script = CSharpScript.Create("var x = 1;");
var s1 = await script.RunAsync();
s1.GetVariable("x").Value = 2;
Assert.Equal(2, s1.GetVariable("x").Value);
// rerunning the script from the beginning rebuilds the state:
var s2 = await s1.Script.RunAsync();
Assert.Equal(1, s2.GetVariable("x").Value);
// continuing preserves the state:
var s3 = await s1.ContinueWithAsync("x");
Assert.Equal(2, s3.GetVariable("x").Value);
Assert.Equal(2, s3.ReturnValue);
}
[Fact]
public async Task ScriptVariable_SetValue_Errors()
{
var state = await CSharpScript.RunAsync(@"
var x = 1;
readonly var y = 2;
const int z = 3;
");
Assert.False(state.GetVariable("x").IsReadOnly);
Assert.True(state.GetVariable("y").IsReadOnly);
Assert.True(state.GetVariable("z").IsReadOnly);
Assert.Throws<ArgumentException>(() => state.GetVariable("x").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = 0);
Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = 0);
}
[Fact]
public async Task TestBranchingSubscripts()
{
// run script to create declaration of M
var state1 = await CSharpScript.RunAsync("int M(int x) { return x + x; }");
// run second script starting from first script's end state
// this script's new declaration should hide the old declaration
var state2 = await state1.ContinueWithAsync("int M(int x) { return x * x; } M(5)");
Assert.Equal(25, state2.ReturnValue);
// run third script also starting from first script's end state
// it should not see any declarations made by the second script.
var state3 = await state1.ContinueWithAsync("M(5)");
Assert.Equal(10, state3.ReturnValue);
}
[Fact]
public async Task ReturnIntAsObject()
{
var expected = 42;
var script = CSharpScript.Create<object>($"return {expected};");
var result = await script.EvaluateAsync();
Assert.Equal(expected, result);
}
[Fact]
public async Task NoReturn()
{
var script = CSharpScript.Create<object>("System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task ReturnAwait()
{
var script = CSharpScript.Create<int>("return await System.Threading.Tasks.Task.FromResult(42);");
var result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInNestedScopeNoTrailingExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}");
var result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task ReturnInNestedScopeWithTrailingVoidExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task ReturnInNestedScopeWithTrailingVoidExpressionAsInt()
{
var script = CSharpScript.Create<int>(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Equal(0, result);
script = CSharpScript.Create<int>(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine()");
result = await script.EvaluateAsync();
Assert.Equal(0, result);
}
[Fact]
public async Task ReturnIntWithTrailingDoubleExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}
1.1");
var result = await script.EvaluateAsync();
Assert.Equal(1.1, result);
script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
return 1;
}
1.1");
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task ReturnGenericAsInterface()
{
var script = CSharpScript.Create<IEnumerable<int>>(@"
if (false)
{
return new System.Collections.Generic.List<int> { 1, 2, 3 };
}");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create<IEnumerable<int>>(@"
if (true)
{
return new System.Collections.Generic.List<int> { 1, 2, 3 };
}");
result = await script.EvaluateAsync();
Assert.Equal(new List<int> { 1, 2, 3 }, result);
}
[Fact]
public async Task ReturnNullable()
{
var script = CSharpScript.Create<int?>(@"
if (false)
{
return 42;
}");
var result = await script.EvaluateAsync();
Assert.False(result.HasValue);
script = CSharpScript.Create<int?>(@"
if (true)
{
return 42;
}");
result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInLoadedFile()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 42;"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Equal(42, result);
script = CSharpScript.Create(@"
#load ""a.csx""
-1", options);
result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInLoadedFileTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
if (false)
{
return 42;
}
1"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
2", options);
result = await script.EvaluateAsync();
Assert.Equal(2, result);
}
[Fact]
public async Task ReturnInLoadedFileTrailingVoidExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
if (false)
{
return 1;
}
System.Console.WriteLine(42)"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
2", options);
result = await script.EvaluateAsync();
Assert.Equal(2, result);
}
[Fact]
public async Task MultipleLoadedFilesWithTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "1"),
KeyValuePair.Create("b.csx", @"
#load ""a.csx""
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"b.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "1"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
result = await script.EvaluateAsync();
Assert.Null(result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "1"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
3", options);
result = await script.EvaluateAsync();
Assert.Equal(3, result);
}
[Fact]
public async Task MultipleLoadedFilesWithReturnAndTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 1;"),
KeyValuePair.Create("b.csx", @"
#load ""a.csx""
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"b.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Equal(1, result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 1;"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
result = await script.EvaluateAsync();
Assert.Equal(1, result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 1;"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
return 3;", options);
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task LoadedFileWithReturnAndGoto()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
goto EOF;
NEXT:
return 1;
EOF:;
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create(@"
#load ""a.csx""
goto NEXT;
return 3;
NEXT:;", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
L1: goto EOF;
L2: return 3;
EOF:
EOF2: ;
4", options);
result = await script.EvaluateAsync();
Assert.Equal(4, result);
}
[Fact]
public async Task VoidReturn()
{
var script = CSharpScript.Create("return;");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
var b = true;
if (b)
{
return;
}
b");
result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task LoadedFileWithVoidReturn()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
var i = 42;
return;
i = -1;"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create<int>(@"
#load ""a.csx""
i", options);
var result = await script.EvaluateAsync();
Assert.Equal(0, result);
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.Serialization;
using System.Collections;
namespace Fungus
{
/// <summary>
/// The type of audio control to perform.
/// </summary>
public enum ControlAudioType
{
/// <summary> Play the audiosource once. </summary>
PlayOnce,
/// <summary> Play the audiosource in a loop. </summary>
PlayLoop,
/// <summary> Pause a looping audiosource. </summary>
PauseLoop,
/// <summary> Stop a looping audiosource. </summary>
StopLoop,
/// <summary> Change the volume level of an audiosource. </summary>
ChangeVolume
}
/// <summary>
/// Plays, loops, or stops an audiosource. Any AudioSources with the same tag as the target Audio Source will automatically be stoped.
/// </summary>
[CommandInfo("Audio",
"Control Audio",
"Plays, loops, or stops an audiosource. Any AudioSources with the same tag as the target Audio Source will automatically be stoped.")]
[ExecuteInEditMode]
public class ControlAudio : Command
{
[Tooltip("What to do to audio")]
[SerializeField] protected ControlAudioType control;
public virtual ControlAudioType Control { get { return control; } }
[Tooltip("Audio clip to play")]
[SerializeField] protected AudioSourceData _audioSource;
[Range(0,1)]
[Tooltip("Start audio at this volume")]
[SerializeField] protected float startVolume = 1;
[Range(0,1)]
[Tooltip("End audio at this volume")]
[SerializeField] protected float endVolume = 1;
[Tooltip("Time to fade between current volume level and target volume level.")]
[SerializeField] protected float fadeDuration;
[Tooltip("Wait until this command has finished before executing the next command.")]
[SerializeField] protected bool waitUntilFinished = false;
// If there's other music playing in the scene, assign it the same tag as the new music you want to play and
// the old music will be automatically stopped.
protected virtual void StopAudioWithSameTag()
{
// Don't stop audio if there's no tag assigned
if (_audioSource.Value == null ||
_audioSource.Value.tag == "Untagged")
{
return;
}
var audioSources = GameObject.FindObjectsOfType<AudioSource>();
for (int i = 0; i < audioSources.Length; i++)
{
var a = audioSources[i];
if (a != _audioSource.Value && a.tag == _audioSource.Value.tag)
{
StopLoop(a);
}
}
}
protected virtual void PlayOnce()
{
if (fadeDuration > 0)
{
// Fade volume in
LeanTween.value(_audioSource.Value.gameObject,
_audioSource.Value.volume,
endVolume,
fadeDuration
).setOnUpdate(
(float updateVolume)=>{
_audioSource.Value.volume = updateVolume;
});
}
_audioSource.Value.PlayOneShot(_audioSource.Value.clip);
if (waitUntilFinished)
{
StartCoroutine(WaitAndContinue());
}
}
protected virtual IEnumerator WaitAndContinue()
{
// Poll the audiosource until playing has finished
// This allows for things like effects added to the audiosource.
while (_audioSource.Value.isPlaying)
{
yield return null;
}
Continue();
}
protected virtual void PlayLoop()
{
if (fadeDuration > 0)
{
_audioSource.Value.volume = 0;
_audioSource.Value.loop = true;
_audioSource.Value.GetComponent<AudioSource>().Play();
LeanTween.value(_audioSource.Value.gameObject,0,endVolume,fadeDuration
).setOnUpdate(
(float updateVolume)=>{
_audioSource.Value.volume = updateVolume;
}
).setOnComplete(
()=>{
if (waitUntilFinished)
{
Continue();
}
}
);
}
else
{
_audioSource.Value.volume = 1;
_audioSource.Value.loop = true;
_audioSource.Value.GetComponent<AudioSource>().Play();
}
}
protected virtual void PauseLoop()
{
if (fadeDuration > 0)
{
LeanTween.value(_audioSource.Value.gameObject,_audioSource.Value.volume,0,fadeDuration
).setOnUpdate(
(float updateVolume)=>{
_audioSource.Value.volume = updateVolume;
}
).setOnComplete(
()=>{
_audioSource.Value.GetComponent<AudioSource>().Pause();
if (waitUntilFinished)
{
Continue();
}
}
);
}
else
{
_audioSource.Value.GetComponent<AudioSource>().Pause();
}
}
protected virtual void StopLoop(AudioSource source)
{
if (fadeDuration > 0)
{
LeanTween.value(source.gameObject,_audioSource.Value.volume,0,fadeDuration
).setOnUpdate(
(float updateVolume)=>{
source.volume = updateVolume;
}
).setOnComplete(
()=>{
source.GetComponent<AudioSource>().Stop();
if (waitUntilFinished)
{
Continue();
}
}
);
}
else
{
source.GetComponent<AudioSource>().Stop();
}
}
protected virtual void ChangeVolume()
{
LeanTween.value(_audioSource.Value.gameObject,_audioSource.Value.volume,endVolume,fadeDuration
).setOnUpdate(
(float updateVolume)=>{
_audioSource.Value.volume = updateVolume;
}).setOnComplete(
()=>{
if (waitUntilFinished)
{
Continue();
}
});
}
protected virtual void AudioFinished()
{
if (waitUntilFinished)
{
Continue();
}
}
#region Public members
public override void OnEnter()
{
if (_audioSource.Value == null)
{
Continue();
return;
}
if (control != ControlAudioType.ChangeVolume)
{
_audioSource.Value.volume = endVolume;
}
switch(control)
{
case ControlAudioType.PlayOnce:
StopAudioWithSameTag();
PlayOnce();
break;
case ControlAudioType.PlayLoop:
StopAudioWithSameTag();
PlayLoop();
break;
case ControlAudioType.PauseLoop:
PauseLoop();
break;
case ControlAudioType.StopLoop:
StopLoop(_audioSource.Value);
break;
case ControlAudioType.ChangeVolume:
ChangeVolume();
break;
}
if (!waitUntilFinished)
{
Continue();
}
}
public override string GetSummary()
{
if (_audioSource.Value == null)
{
return "Error: No sound clip selected";
}
string fadeType = "";
if (fadeDuration > 0)
{
fadeType = " Fade out";
if (control != ControlAudioType.StopLoop)
{
fadeType = " Fade in volume to " + endVolume;
}
if (control == ControlAudioType.ChangeVolume)
{
fadeType = " to " + endVolume;
}
fadeType += " over " + fadeDuration + " seconds.";
}
return control.ToString() + " \"" + _audioSource.Value.name + "\"" + fadeType;
}
public override Color GetButtonColor()
{
return new Color32(242, 209, 176, 255);
}
#endregion
#region Backwards compatibility
[HideInInspector] [FormerlySerializedAs("audioSource")] public AudioSource audioSourceOLD;
protected virtual void OnEnable()
{
if (audioSourceOLD != null)
{
_audioSource.Value = audioSourceOLD;
audioSourceOLD = null;
}
}
#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;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// Describes the context in which a validation is being performed.
/// </summary>
/// <remarks>
/// This class contains information describing the instance on which
/// validation is being performed.
/// <para>
/// It supports <see cref="IServiceProvider" /> so that custom validation
/// code can acquire additional services to help it perform its validation.
/// </para>
/// <para>
/// An <see cref="Items" /> property bag is available for additional contextual
/// information about the validation. Values stored in <see cref="Items" />
/// will be available to validation methods that use this <see cref="ValidationContext" />
/// </para>
/// </remarks>
public sealed class ValidationContext
// WinStore impl no longer inherits from IServiceProvider but still has GetService()???
// Also we use this ability in Validator.CreateValidationContext()??
: IServiceProvider
{
#region Member Fields
private readonly Dictionary<object, object> _items;
private string _displayName;
private Func<Type, object> _serviceProvider;
#endregion
#region Constructors
/// <summary>
/// Construct a <see cref="ValidationContext" /> for a given object instance being validated.
/// </summary>
/// <param name="instance">The object instance being validated. It cannot be <c>null</c>.</param>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is <c>null</c></exception>
public ValidationContext(object instance)
: this(instance, null, null)
{
}
/// <summary>
/// Construct a <see cref="ValidationContext" /> for a given object instance and an optional
/// property bag of <paramref name="items" />.
/// </summary>
/// <param name="instance">The object instance being validated. It cannot be null.</param>
/// <param name="items">
/// Optional set of key/value pairs to make available to consumers via <see cref="Items" />.
/// If null, an empty dictionary will be created. If not null, the set of key/value pairs will be copied into a
/// new dictionary, preventing consumers from modifying the original dictionary.
/// </param>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is <c>null</c></exception>
public ValidationContext(object instance, IDictionary<object, object> items)
: this(instance, null, items)
{
}
/// <summary>
/// Construct a <see cref="ValidationContext" /> for a given object instance, an optional
/// <paramref name="serviceProvider" />, and an optional
/// property bag of <paramref name="items" />.
/// </summary>
/// <param name="instance">The object instance being validated. It cannot be null.</param>
/// <param name="serviceProvider">
/// Optional <see cref="IServiceProvider" /> to use when <see cref="GetService" /> is called.
/// If it is null, <see cref="GetService" /> will always return null.
/// </param>
/// <param name="items">
/// Optional set of key/value pairs to make available to consumers via <see cref="Items" />.
/// If null, an empty dictionary will be created. If not null, the set of key/value pairs will be copied into a
/// new dictionary, preventing consumers from modifying the original dictionary.
/// </param>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is <c>null</c></exception>
public ValidationContext(object instance, IServiceProvider serviceProvider, IDictionary<object, object> items)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
if (serviceProvider != null)
{
InitializeServiceProvider(serviceType => serviceProvider.GetService(serviceType));
}
_items = items != null ? new Dictionary<object, object>(items) : new Dictionary<object, object>();
ObjectInstance = instance;
}
#endregion
#region Properties
/// <summary>
/// Gets the object instance being validated. While it will not be null, the state of the instance is indeterminate
/// as it might only be partially initialized during validation.
/// <para>Consume this instance with caution!</para>
/// </summary>
/// <remarks>
/// During validation, especially property-level validation, the object instance might be in an indeterminate state.
/// For example, the property being validated, as well as other properties on the instance might not have been
/// updated to their new values.
/// </remarks>
public object ObjectInstance { get; }
/// <summary>
/// Gets the type of the object being validated. It will not be null.
/// </summary>
public Type ObjectType => ObjectInstance.GetType();
/// <summary>
/// Gets or sets the user-visible name of the type or property being validated.
/// </summary>
/// <value>
/// If this name was not explicitly set, this property will consult an associated <see cref="DisplayAttribute" />
/// to see if can use that instead. Lacking that, it returns <see cref="MemberName" />. The
/// <see cref="ObjectInstance" />
/// type name will be used if MemberName has not been set.
/// </value>
public string DisplayName
{
get
{
if (string.IsNullOrEmpty(_displayName))
{
_displayName = GetDisplayName();
if (string.IsNullOrEmpty(_displayName))
{
_displayName = ObjectType.Name;
}
}
return _displayName;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException(nameof(value));
}
_displayName = value;
}
}
/// <summary>
/// Gets or sets the name of the type or property being validated.
/// </summary>
/// <value>
/// This name reflects the API name of the member being validated, not a localized name. It should be set
/// only for property or parameter contexts.
/// </value>
public string MemberName { get; set; }
/// <summary>
/// Gets the dictionary of key/value pairs associated with this context.
/// </summary>
/// <value>
/// This property will never be null, but the dictionary may be empty. Changes made
/// to items in this dictionary will never affect the original dictionary specified in the constructor.
/// </value>
public IDictionary<object, object> Items => _items;
#endregion
#region Methods
/// <summary>
/// Looks up the display name using the DisplayAttribute attached to the respective type or property.
/// </summary>
/// <returns>A display-friendly name of the member represented by the <see cref="MemberName" />.</returns>
private string GetDisplayName()
{
string displayName = null;
ValidationAttributeStore store = ValidationAttributeStore.Instance;
DisplayAttribute displayAttribute = null;
if (string.IsNullOrEmpty(MemberName))
{
displayAttribute = store.GetTypeDisplayAttribute(this);
}
else if (store.IsPropertyContext(this))
{
displayAttribute = store.GetPropertyDisplayAttribute(this);
}
if (displayAttribute != null)
{
displayName = displayAttribute.GetName();
}
return displayName ?? MemberName;
}
/// <summary>
/// Initializes the <see cref="ValidationContext" /> with a service provider that can return
/// service instances by <see cref="Type" /> when <see cref="GetService" /> is called.
/// </summary>
/// <param name="serviceProvider">
/// A <see cref="Func{T, TResult}" /> that can return service instances given the
/// desired <see cref="Type" /> when <see cref="GetService" /> is called.
/// If it is <c>null</c>, <see cref="GetService" /> will always return <c>null</c>.
/// </param>
public void InitializeServiceProvider(Func<Type, object> serviceProvider)
{
_serviceProvider = serviceProvider;
}
#endregion
#region IServiceProvider Members
/// <summary>
/// See <see cref="IServiceProvider.GetService(Type)" />.
/// </summary>
/// <param name="serviceType">The type of the service needed.</param>
/// <returns>An instance of that service or null if it is not available.</returns>
public object GetService(Type serviceType) => _serviceProvider?.Invoke(serviceType);
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
[ContractVerification(true)]
public class ReplaceSymbolicValueForAccessPath<Local, Parameter, Method, Field, Property, Event, Typ, Variable, Expression, Attribute, Assembly>
where Typ : IEquatable<Typ>
{
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.context != null);
Contract.Invariant(this.metaDataDecoder != null);
Contract.Invariant(this.boundVariables != null);
}
#endregion
#region State
private readonly IExpressionContext<Local, Parameter, Method, Field, Typ, Expression, Variable> context;
private readonly IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Typ, Attribute, Assembly> metaDataDecoder;
private readonly Set<BoxedExpression> boundVariables;
#endregion
public ReplaceSymbolicValueForAccessPath(
IExpressionContext<Local, Parameter, Method, Field, Typ, Expression, Variable> context,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Typ, Attribute, Assembly> metaDataDecoder)
{
Contract.Requires(context != null);
Contract.Requires(metaDataDecoder != null);
this.context = context;
this.metaDataDecoder = metaDataDecoder;
this.boundVariables = new Set<BoxedExpression>();
}
/// <summary>
/// If failIfCannotReplaceVarsWithAccessPaths is true, whenever we cannot convert a variable into an expression, we return null.
/// Otherwise (when failIfCannotReplaceVarsWithAccessPaths is false), then we return the same expression
/// </summary>
public BoxedExpression ReadAt(APC pc, BoxedExpression exp, bool failIfCannotReplaceVarsWithAccessPaths = true, Typ allowReturnValue = default(Typ))
{
Contract.Requires(exp != null);
if(this.boundVariables.Contains(exp))
{
return exp;
}
if (exp.IsVariable)
{
Variable var;
if (exp.TryGetFrameworkVariable(out var))
{
var accessPath = context.ValueContext.AccessPathList(pc, var, true, true, allowReturnValue);
if (accessPath != null)
{
return BoxedExpression.Var(var, accessPath);
}
Contract.Assert(accessPath == null, "Just for readibility: we are here if we do not have an access path for the variable");
return failIfCannotReplaceVarsWithAccessPaths ? null : exp;
}
return null;
}
BinaryOperator bop;
BoxedExpression left, right;
if (exp.IsBinaryExpression(out bop, out left, out right))
{
Variable leftVar, rightVar;
if (left.TryGetFrameworkVariable(out leftVar) && right.IsConstant)
{
var typeLeft = this.context.ValueContext.GetType(pc, leftVar);
if (typeLeft.IsNormal && IsInterestingBoundFromTheTypeRange(right, typeLeft.Value))
{
var recurse = ReadAt(pc, left, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
if (recurse != null)
return BoxedExpression.Binary(bop, recurse, right);
}
return null;
}
if (left.IsConstant && right.TryGetFrameworkVariable(out rightVar))
{
var typeRight = this.context.ValueContext.GetType(pc, rightVar);
if (typeRight.IsNormal && IsInterestingBoundFromTheTypeRange(left, typeRight.Value))
{
var recurse = ReadAt(pc, right, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
if (recurse != null)
return BoxedExpression.Binary(bop, left, recurse);
}
return null;
}
var recurseLeft = ReadAt(pc, left, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
var recurseRight = ReadAt(pc, right, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
if (recurseLeft != null && recurseRight != null)
return BoxedExpression.Binary(bop, recurseLeft, recurseRight);
else
return null;
}
UnaryOperator uop;
if (exp.IsUnaryExpression(out uop, out left))
{
var recurse = ReadAt(pc, left, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
if (recurse != null)
return BoxedExpression.Unary(uop, recurse);
return null;
}
object type;
if (exp.IsIsInstExpression(out left, out type)) {
var recurse = ReadAt(pc, left, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
if (recurse != null)
{
return ClousotExpression<Type>.MakeIsInst((Type)type, recurse);
}
return null;
}
bool isForAll;
BoxedExpression boundVar, inf, sup, body;
if (exp.IsQuantifiedExpression(out isForAll, out boundVar, out inf, out sup, out body))
{
Contract.Assert(boundVar != null);
Contract.Assert(inf != null);
Contract.Assert(sup != null);
Contract.Assert(body != null);
this.boundVariables.Add(boundVar);
var infRec = ReadAt(pc, inf, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
if (infRec != null)
{
var supRec = ReadAt(pc, sup, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
if (supRec != null)
{
var bodyRec = ReadAt(pc, body, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
if (bodyRec != null)
{
this.boundVariables.Remove(boundVar);
if (isForAll)
return new ForAllIndexedExpression(null, boundVar, infRec, supRec, bodyRec);
else
return new ExistsIndexedExpression(null, boundVar, infRec, supRec, bodyRec);
}
}
}
return null;
}
object t;
BoxedExpression array, index;
if (exp.IsArrayIndexExpression(out array, out index, out t) && t is Typ)
{
var arrayRec = ReadAt(pc, array, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
if (arrayRec != null)
{
var indexRec = ReadAt(pc, index, failIfCannotReplaceVarsWithAccessPaths, allowReturnValue);
if (indexRec != null)
{
return new BoxedExpression.ArrayIndexExpression<Typ>(arrayRec, indexRec, (Typ)t);
}
}
}
return exp;
}
public bool IsInterestingBoundFromTheTypeRange(BoxedExpression left, Typ t)
{
Contract.Requires(left != null);
int k;
if (left.IsConstantInt(out k))
{
if ((k == SByte.MaxValue || k == SByte.MinValue))
return !t.Equals(metaDataDecoder.System_Int8);
if ((k == Int16.MaxValue || k == Int16.MinValue))
return !t.Equals(metaDataDecoder.System_Int8) && !t.Equals(metaDataDecoder.System_Int16)
&& !t.Equals(metaDataDecoder.System_UInt8);
if ((k == Int32.MaxValue || k == Int32.MinValue))
return !t.Equals(metaDataDecoder.System_Int8) && !t.Equals(metaDataDecoder.System_Int16) && !t.Equals(metaDataDecoder.System_Int32)
&& !t.Equals(metaDataDecoder.System_UInt8) && !t.Equals(metaDataDecoder.System_UInt16);
}
long l;
if (left.IsConstantInt64(out l))
{
if ((l == SByte.MaxValue || l == SByte.MinValue))
return !t.Equals(metaDataDecoder.System_Int8);
if ((l == Int16.MaxValue || l == Int16.MinValue))
return !t.Equals(metaDataDecoder.System_Int8) && !t.Equals(metaDataDecoder.System_Int16)
&& !t.Equals(metaDataDecoder.System_UInt8);
if ((l == Int32.MaxValue || l == Int32.MinValue))
return !t.Equals(metaDataDecoder.System_Int8) && !t.Equals(metaDataDecoder.System_Int16) && !t.Equals(metaDataDecoder.System_Int32)
&& !t.Equals(metaDataDecoder.System_UInt8) && !t.Equals(metaDataDecoder.System_UInt16);
if ((l == Int64.MaxValue || l == Int64.MinValue))
return !t.Equals(metaDataDecoder.System_Int8) && !t.Equals(metaDataDecoder.System_Int16) && !t.Equals(metaDataDecoder.System_Int32) && !t.Equals(metaDataDecoder.System_Int64)
&& !t.Equals(metaDataDecoder.System_UInt8) && !t.Equals(metaDataDecoder.System_UInt16);
}
float f;
if (left.IsConstantFloat32(out f))
{
if ((float)f == Single.MaxValue || (float)f == Single.MinValue)
return !t.Equals(metaDataDecoder.System_Single);
}
double d;
if (left.IsConstantFloat64(out d))
{
if ((double)d == Double.MaxValue || (double)d == Double.MinValue)
return false;
}
return true;
}
}
}
| |
//
// UnityOSC - Open Sound Control interface for the Unity3d game engine
//
// Copyright (c) 2012 Jorge Garcia Martin
//
// 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.
//
// Inspired by http://www.unifycommunity.com/wiki/index.php?title=AManagerClass
using System;
using System.Net;
using System.Collections.Generic;
using UnityEngine;
using UnityOSC;
/// <summary>
/// Models a log of a server composed by an OSCServer, a List of OSCPacket and a List of
/// strings that represent the current messages in the log.
/// </summary>
public struct ServerLog
{
public OSCServer server;
public List<OSCPacket> packets;
public List<string> log;
}
/// <summary>
/// Models a log of a client composed by an OSCClient, a List of OSCMessage and a List of
/// strings that represent the current messages in the log.
/// </summary>
public struct ClientLog
{
public OSCClient client;
public List<OSCMessage> messages;
public List<string> log;
}
/// <summary>
/// Handles all the OSC servers and clients of the current Unity game/application.
/// Tracks incoming and outgoing messages.
/// </summary>
public class OSCHandler : MonoBehaviour
{
#region Singleton Constructors
static OSCHandler()
{
}
OSCHandler()
{
}
public static OSCHandler Instance
{
get
{
if (_instance == null)
{
_instance = new GameObject ("OSCHandler").AddComponent<OSCHandler>();
}
return _instance;
}
}
#endregion
#region Member Variables
private static OSCHandler _instance = null;
private Dictionary<string, ClientLog> _clients = new Dictionary<string, ClientLog>();
private Dictionary<string, ServerLog> _servers = new Dictionary<string, ServerLog>();
private const int _loglength = 25;
#endregion
/// <summary>
/// Initializes the OSC Handler.
/// Here you can create the OSC servers and clientes.
/// </summary>
public void Init()
{
//Initialize OSC clients (transmitters)
//Example:
//CreateClient("SuperCollider", IPAddress.Parse("127.0.0.1"), 5555);
//Initialize OSC servers (listeners)
//Example:
//CreateServer("AndroidPhone", 6666);
}
#region Properties
public Dictionary<string, ClientLog> Clients
{
get
{
return _clients;
}
}
public Dictionary<string, ServerLog> Servers
{
get
{
return _servers;
}
}
#endregion
#region Methods
/// <summary>
/// Ensure that the instance is destroyed when the game is stopped in the Unity editor
/// Close all the OSC clients and servers
/// </summary>
void OnApplicationQuit()
{
foreach(KeyValuePair<string,ClientLog> pair in _clients)
{
pair.Value.client.Close();
}
foreach(KeyValuePair<string,ServerLog> pair in _servers)
{
pair.Value.server.Close();
}
_instance = null;
}
/// <summary>
/// Creates an OSC Client (sends OSC messages) given an outgoing port and address.
/// </summary>
/// <param name="clientId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="destination">
/// A <see cref="IPAddress"/>
/// </param>
/// <param name="port">
/// A <see cref="System.Int32"/>
/// </param>
public void CreateClient(string clientId, IPAddress destination, int port)
{
ClientLog clientitem = new ClientLog();
clientitem.client = new OSCClient(destination, port);
clientitem.log = new List<string>();
clientitem.messages = new List<OSCMessage>();
_clients.Add(clientId, clientitem);
// Send test message
string testaddress = "/test/alive/";
OSCMessage message = new OSCMessage(testaddress, destination.ToString());
message.Append(port); message.Append("OK");
_clients[clientId].log.Add(String.Concat(DateTime.UtcNow.ToString(),".",
FormatMilliseconds(DateTime.Now.Millisecond), " : ",
testaddress," ", DataToString(message.Data)));
_clients[clientId].messages.Add(message);
_clients[clientId].client.Send(message);
}
/// <summary>
/// Creates an OSC Server (listens to upcoming OSC messages) given an incoming port.
/// </summary>
/// <param name="serverId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="port">
/// A <see cref="System.Int32"/>
/// </param>
public void CreateServer(string serverId, int port)
{
OSCServer server = new OSCServer(port);
server.PacketReceivedEvent += OnPacketReceived;
ServerLog serveritem = new ServerLog();
serveritem.server = server;
serveritem.log = new List<string>();
serveritem.packets = new List<OSCPacket>();
_servers.Add(serverId, serveritem);
}
void OnPacketReceived(OSCServer server, OSCPacket packet)
{
}
/// <summary>
/// Sends an OSC message to a specified client, given its clientId (defined at the OSC client construction),
/// OSC address and a single value. Also updates the client log.
/// </summary>
/// <param name="clientId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="address">
/// A <see cref="System.String"/>
/// </param>
/// <param name="value">
/// A <see cref="T"/>
/// </param>
public void SendMessageToClient<T>(string clientId, string address, T value)
{
List<object> temp = new List<object>();
temp.Add(value);
SendMessageToClient(clientId, address, temp);
}
/// <summary>
/// Sends an OSC message to a specified client, given its clientId (defined at the OSC client construction),
/// OSC address and a list of values. Also updates the client log.
/// </summary>
/// <param name="clientId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="address">
/// A <see cref="System.String"/>
/// </param>
/// <param name="values">
/// A <see cref="List<T>"/>
/// </param>
public void SendMessageToClient<T>(string clientId, string address, List<T> values)
{
if(_clients.ContainsKey(clientId))
{
OSCMessage message = new OSCMessage(address);
foreach(T msgvalue in values)
{
message.Append(msgvalue);
}
if(_clients[clientId].log.Count < _loglength)
{
_clients[clientId].log.Add(String.Concat(DateTime.UtcNow.ToString(),".",
FormatMilliseconds(DateTime.Now.Millisecond),
" : ", address, " ", DataToString(message.Data)));
_clients[clientId].messages.Add(message);
}
else
{
_clients[clientId].log.RemoveAt(0);
_clients[clientId].messages.RemoveAt(0);
_clients[clientId].log.Add(String.Concat(DateTime.UtcNow.ToString(),".",
FormatMilliseconds(DateTime.Now.Millisecond),
" : ", address, " ", DataToString(message.Data)));
_clients[clientId].messages.Add(message);
}
_clients[clientId].client.Send(message);
}
else
{
Debug.LogError(string.Format("Can't send OSC messages to {0}. Client doesn't exist.", clientId));
}
}
/// <summary>
/// Updates clients and servers logs.
/// </summary>
public void UpdateLogs()
{
foreach(KeyValuePair<string,ServerLog> pair in _servers)
{
if(_servers[pair.Key].server.LastReceivedPacket != null)
{
//Initialization for the first packet received
if(_servers[pair.Key].log.Count == 0)
{
_servers[pair.Key].packets.Add(_servers[pair.Key].server.LastReceivedPacket);
_servers[pair.Key].log.Add(String.Concat(DateTime.UtcNow.ToString(), ".",
FormatMilliseconds(DateTime.Now.Millisecond)," : ",
_servers[pair.Key].server.LastReceivedPacket.Address," ",
DataToString(_servers[pair.Key].server.LastReceivedPacket.Data)));
break;
}
if(_servers[pair.Key].server.LastReceivedPacket.TimeStamp
!= _servers[pair.Key].packets[_servers[pair.Key].packets.Count - 1].TimeStamp)
{
if(_servers[pair.Key].log.Count > _loglength - 1)
{
_servers[pair.Key].log.RemoveAt(0);
_servers[pair.Key].packets.RemoveAt(0);
}
_servers[pair.Key].packets.Add(_servers[pair.Key].server.LastReceivedPacket);
_servers[pair.Key].log.Add(String.Concat(DateTime.UtcNow.ToString(), ".",
FormatMilliseconds(DateTime.Now.Millisecond)," : ",
_servers[pair.Key].server.LastReceivedPacket.Address," ",
DataToString(_servers[pair.Key].server.LastReceivedPacket.Data)));
}
}
}
}
/// <summary>
/// Converts a collection of object values to a concatenated string.
/// </summary>
/// <param name="data">
/// A <see cref="List<System.Object>"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
private string DataToString(List<object> data)
{
string buffer = "";
for(int i = 0; i < data.Count; i++)
{
buffer += data[i].ToString() + " ";
}
buffer += "\n";
return buffer;
}
/// <summary>
/// Formats a milliseconds number to a 000 format. E.g. given 50, it outputs 050. Given 5, it outputs 005
/// </summary>
/// <param name="milliseconds">
/// A <see cref="System.Int32"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
private string FormatMilliseconds(int milliseconds)
{
if(milliseconds < 100)
{
if(milliseconds < 10)
return String.Concat("00",milliseconds.ToString());
return String.Concat("0",milliseconds.ToString());
}
return milliseconds.ToString();
}
#endregion
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Layout;
using Avalonia.LogicalTree;
using Avalonia.Platform;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class TopLevelTests
{
[Fact]
public void IsAttachedToLogicalTree_Is_True()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
var target = new TestTopLevel(impl.Object);
Assert.True(((ILogical)target).IsAttachedToLogicalTree);
}
}
[Fact]
public void ClientSize_Should_Be_Set_On_Construction()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
impl.Setup(x => x.ClientSize).Returns(new Size(123, 456));
var target = new TestTopLevel(impl.Object);
Assert.Equal(new Size(123, 456), target.ClientSize);
}
}
[Fact]
public void Width_Should_Not_Be_Set_On_Construction()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
impl.Setup(x => x.ClientSize).Returns(new Size(123, 456));
var target = new TestTopLevel(impl.Object);
Assert.Equal(double.NaN, target.Width);
}
}
[Fact]
public void Height_Should_Not_Be_Set_On_Construction()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
impl.Setup(x => x.ClientSize).Returns(new Size(123, 456));
var target = new TestTopLevel(impl.Object);
Assert.Equal(double.NaN, target.Height);
}
}
[Fact]
public void Layout_Pass_Should_Not_Be_Automatically_Scheduled()
{
var services = TestServices.StyledWindow.With(layoutManager: Mock.Of<ILayoutManager>());
using (UnitTestApplication.Start(services))
{
var impl = new Mock<ITopLevelImpl>();
var target = new TestTopLevel(impl.Object);
// The layout pass should be scheduled by the derived class.
var layoutManagerMock = Mock.Get(LayoutManager.Instance);
layoutManagerMock.Verify(x => x.ExecuteLayoutPass(), Times.Never);
}
}
[Fact]
public void Bounds_Should_Be_Set_After_Layout_Pass()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
impl.SetupProperty(x => x.Resized);
impl.SetupGet(x => x.Scaling).Returns(1);
var target = new TestTopLevel(impl.Object)
{
IsVisible = true,
Template = CreateTemplate(),
Content = new TextBlock
{
Width = 321,
Height = 432,
}
};
LayoutManager.Instance.ExecuteInitialLayoutPass(target);
Assert.Equal(new Rect(0, 0, 321, 432), target.Bounds);
}
}
[Fact]
public void Width_And_Height_Should_Not_Be_Set_After_Layout_Pass()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
impl.Setup(x => x.ClientSize).Returns(new Size(123, 456));
var target = new TestTopLevel(impl.Object);
LayoutManager.Instance.ExecuteLayoutPass();
Assert.Equal(double.NaN, target.Width);
Assert.Equal(double.NaN, target.Height);
}
}
[Fact]
public void Width_And_Height_Should_Be_Set_After_Window_Resize_Notification()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
impl.SetupAllProperties();
impl.Setup(x => x.ClientSize).Returns(new Size(123, 456));
// The user has resized the window, so we can no longer auto-size.
var target = new TestTopLevel(impl.Object);
impl.Object.Resized(new Size(100, 200));
Assert.Equal(100, target.Width);
Assert.Equal(200, target.Height);
}
}
[Fact]
public void Impl_Close_Should_Call_Raise_Closed_Event()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
impl.SetupAllProperties();
bool raised = false;
var target = new TestTopLevel(impl.Object);
target.Closed += (s, e) => raised = true;
impl.Object.Closed();
Assert.True(raised);
}
}
[Fact]
public void Impl_Input_Should_Pass_Input_To_InputManager()
{
var inputManagerMock = new Mock<IInputManager>();
var services = TestServices.StyledWindow.With(inputManager: inputManagerMock.Object);
using (UnitTestApplication.Start(services))
{
var impl = new Mock<ITopLevelImpl>();
impl.SetupAllProperties();
var target = new TestTopLevel(impl.Object);
var input = new RawKeyEventArgs(
new Mock<IKeyboardDevice>().Object,
0,
RawKeyEventType.KeyDown,
Key.A, InputModifiers.None);
impl.Object.Input(input);
inputManagerMock.Verify(x => x.ProcessInput(input));
}
}
[Fact]
public void Adding_Top_Level_As_Child_Should_Throw_Exception()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
impl.SetupAllProperties();
var target = new TestTopLevel(impl.Object);
var child = new TestTopLevel(impl.Object);
target.Template = CreateTemplate();
target.Content = child;
Assert.Throws<InvalidOperationException>(() => target.ApplyTemplate());
}
}
[Fact]
public void Exiting_Application_Notifies_Top_Level()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
impl.SetupAllProperties();
var target = new TestTopLevel(impl.Object);
UnitTestApplication.Current.Exit();
Assert.True(target.IsClosed);
}
}
[Fact]
public void Adding_Resource_To_Application_Should_Raise_ResourcesChanged()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<ITopLevelImpl>();
impl.SetupAllProperties();
var target = new TestTopLevel(impl.Object);
var raised = false;
target.ResourcesChanged += (_, __) => raised = true;
Application.Current.Resources.Add("foo", "bar");
Assert.True(raised);
}
}
private FuncControlTemplate<TestTopLevel> CreateTemplate()
{
return new FuncControlTemplate<TestTopLevel>(x =>
new ContentPresenter
{
Name = "PART_ContentPresenter",
[!ContentPresenter.ContentProperty] = x[!ContentControl.ContentProperty],
});
}
private class TestTopLevel : TopLevel
{
public bool IsClosed { get; private set; }
public TestTopLevel(ITopLevelImpl impl)
: base(impl)
{
}
protected override void HandleApplicationExiting()
{
base.HandleApplicationExiting();
IsClosed = true;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public static partial class UnprotectedAttributeTests
{
[Fact]
public static void TestUnprotectedAttributes0_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes();
VerifyUnprotectedAttributes0(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes0_FixedValue()
{
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818048"
+ "fea7a626159f3792b8daa8e064de2f986cf0e432428c6cb80ed4bf6e593db74a7f907e0918b4bee6d55e1e0f9da6b6519e42"
+ "23d58b0f717165a727d7dac87556916c800e2346beac5a825c973e9bba4fe6c549baafd151d85fd7c266769dbb57f28e45f8"
+ "6bb5478d018e132cb576079d8c2a7f4217973c3ff1f0617364809c302b06092a864886f70d010701301406082a864886f70d"
+ "030704083979569d26db4c278008d2fa4271358f9a2f").HexToByteArray();
VerifyUnprotectedAttributes0(encodedMessage);
}
private static void VerifyUnprotectedAttributes0(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(0, attributes.Length);
}
[Fact]
public static void TestUnprotectedAttributes1_DocumentDescription_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(new Pkcs9DocumentDescription("My Description"));
VerifyUnprotectedAttributes1_DocumentDescription(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_DocumentDescription_FixedValue()
{
byte[] encodedMessage =
("3082014006092a864886f70d010703a08201313082012d0201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "801dba607648ab56b88dffb4bfe36170d698910562cef64dc2f3098ca2d7fa97334e721b6d00250470f8a16b5d2f5f38cc84"
+ "c05d49e5aa7390ed4e0d6a7369f72f8bb0209545b6b8d3302c2c3fc8c8e7f5a54dd30b20855a77b5cd40c6f2b59376252aef"
+ "e1d90965916e25c63f509e32f86a9213b740796927bbb0573b024b7ba3302b06092a864886f70d010701301406082a864886"
+ "f70d03070408df8ced363e2a76288008262ce8fe027530a3a130302e060a2b0601040182375802023120041e4d0079002000"
+ "4400650073006300720069007000740069006f006e000000").HexToByteArray();
VerifyUnprotectedAttributes1_DocumentDescription(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_DocumentDescription(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
attributes[0].AssertIsDocumentationDescription("My Description");
}
[Fact]
public static void TestUnprotectedAttributes1_DocumenName_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(new Pkcs9DocumentName("My Name"));
VerifyUnprotectedAttributes1_DocumentName(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_DocumentName_FixedValue()
{
byte[] encodedMessage =
("3082013206092a864886f70d010703a08201233082011f0201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "8000d17895fe3d35a30f0666e4064cc40757251404f785c4878ab98d1440d7f1706991cf854b2498bca8781c7728805b03e8"
+ "d36329f34d7508bf38e4e4d5447e8c7d6d1c652f0a40bb3fc396e1139094d6349e08a7d233b9323c4760a96199660c87c7f0"
+ "2c891711efcee6085f07fa0060da6f9b22d895b312caed824916b14314302b06092a864886f70d010701301406082a864886"
+ "f70d03070408817ee1c4bb617f828008de69d9d27afef823a1223020060a2b060104018237580201311204104d0079002000"
+ "4e0061006d0065000000").HexToByteArray();
VerifyUnprotectedAttributes1_DocumentName(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_DocumentName(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
attributes[0].AssertIsDocumentationName("My Name");
}
[Fact]
public static void TestUnprotectedAttributes1_SigningTime_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(new Pkcs9SigningTime(new DateTime(2018, 4, 1, 8, 30, 05)));
VerifyUnprotectedAttributes1_SigningTime(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_SigningTime_FixedValue()
{
byte[] encodedMessage =
("3082012e06092a864886f70d010703a082011f3082011b0201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "801cf4efe18f457c32753fd3c908372ac8075cd4c4bdec98a912cc241b604b7ba46f44c657c769e84998384c28ee9a670d7d"
+ "8d7427f5a3bffb2a6e09269f1c89a7b1906eb0a828487d6e4fcb2c6e9023f3d9f8114701cf01c2fcb4db0c9ab7144c8e2b73"
+ "6551ca1a348ac3c25cca9de1bdef79c0bdd2ba8b79e6e668f947cf1bc7302b06092a864886f70d010701301406082a864886"
+ "f70d03070408e7575fbec5da862080084306defef088dd0ea11e301c06092a864886f70d010905310f170d31383034303130"
+ "38333030355a").HexToByteArray();
VerifyUnprotectedAttributes1_SigningTime(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_SigningTime(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
DateTime expectedSigningTIme = new DateTime(2018, 4, 1, 8, 30, 05);
attributes[0].AssertIsSigningTime(expectedSigningTIme);
}
[Fact]
public static void TestUnprotectedAttributes1_ContentType_RoundTrip()
{
byte[] rawData = "06072a9fa20082f300".HexToByteArray();
Pkcs9AttributeObject pkcs9ContentType = new Pkcs9AttributeObject(Oids.ContentType, rawData);
byte[] encodedMessage = CreateEcmsWithAttributes(pkcs9ContentType);
VerifyUnprotectedAttributes1_ContentType(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_ContentType_FixedValue()
{
byte[] encodedMessage =
("3082012806092a864886f70d010703a0820119308201150201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "804abd2e5b20b7d255234ffa6b025a9c6a35362ac4affc4d78ed02a647ac9d9cb8d02bf64f924f19c731fc6e7f333180c6f1"
+ "0be40c382b5da5db96b0303819573dc3598aa978704ee96a98113ec110d48aef57c745ee0188feceac27a3739663bb52fccc"
+ "37e106ed3d8ecf3806bcc4df83ce989080405e3e856e725a85aa205bda302b06092a864886f70d010701301406082a864886"
+ "f70d030704084a0375f470805f908008522c8448feaf357da118301606092a864886f70d010903310906072a9fa20082f300").HexToByteArray();
VerifyUnprotectedAttributes1_ContentType(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_ContentType(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
attributes[0].AssertIsContentType("1.2.512256.47488");
}
[Fact]
public static void TestUnprotectedAttributes1_MessageDigest_RoundTrip()
{
byte[] rawData = "0405032d58805d".HexToByteArray();
Pkcs9AttributeObject pkcs9MessageDigest = new Pkcs9AttributeObject(Oids.MessageDigest, rawData);
byte[] encodedMessage = CreateEcmsWithAttributes(pkcs9MessageDigest);
VerifyUnprotectedAttributes1_MessageDigest(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_MessageDigest_FixedValue()
{
byte[] encodedMessage =
("3082012606092a864886f70d010703a0820117308201130201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "802ed2085366bf01caca75c260d900c12ef3377f868d879c7b33734dd912aeffcb55f8f8fefea550bd75472ad20f56dd6edf"
+ "d1c9669f3653e41d48f03c0796513da5b922587415853fc46ef5f452cea25a58c6da296527c51111a2fa6e472651391e2c3a"
+ "ffb081ce6f7e4aee275d0f3d3e351b5e76c84afb5f80bb1ef594eb9b92302b06092a864886f70d010701301406082a864886"
+ "f70d030704088b5d38dad37f599280081d626f58eabeeb0aa116301406092a864886f70d01090431070405032d58805d").HexToByteArray();
VerifyUnprotectedAttributes1_MessageDigest(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_MessageDigest(byte[] encodedMessage)
{
byte[] expectedMessageDigest = "032d58805d".HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
attributes[0].AssertIsMessageDigest(expectedMessageDigest);
}
[Fact]
public static void TestUnprotectedAttributes1_Merge3_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(
new Pkcs9DocumentDescription("My Description 1"),
new Pkcs9DocumentDescription("My Description 2"),
new Pkcs9DocumentDescription("My Description 3")
);
VerifyUnprotectedAttributes_Merge3(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_Merge3_FixedValue()
{
byte[] encodedMessage =
("3082018c06092a864886f70d010703a082017d308201790201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "809203ec6ad0877ae56dbc8a480e59e94ca953839f8f769ec1b262b4f4916c9863ee9c41007c356fbf2fc3f3d03e4aa1ea46"
+ "575d0fbc0c5f47e41778f34535eea84e648009955f271a9e3c24f8c192d31406d46a40396b78d4013cfe3dcc443ac9ca9213"
+ "7ffa503297ca1d241f68e905c60134c02e7ce8e1e67481abebe3d7faa1302b06092a864886f70d010701301406082a864886"
+ "f70d030704085e2e9ca7859583a08008fb219dbb2a84a2eda17c307a060a2b060104018237580202316c04224d0079002000"
+ "4400650073006300720069007000740069006f006e0020003100000004224d00790020004400650073006300720069007000"
+ "740069006f006e0020003200000004224d00790020004400650073006300720069007000740069006f006e00200033000000").HexToByteArray();
VerifyUnprotectedAttributes_Merge3(encodedMessage);
}
private static void VerifyUnprotectedAttributes_Merge3(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(3, attributes.Length);
attributes[0].AssertIsDocumentationDescription("My Description 1");
attributes[1].AssertIsDocumentationDescription("My Description 2");
attributes[2].AssertIsDocumentationDescription("My Description 3");
}
[Fact]
public static void TestUnprotectedAttributes1_Heterogenous3_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(
new Pkcs9DocumentDescription("My Description 1"),
new Pkcs9DocumentDescription("My Description 2"),
new Pkcs9DocumentName("My Name 1")
);
VerifyUnprotectedAttributes_Heterogenous3(encodedMessage);
}
private static void VerifyUnprotectedAttributes_Heterogenous3(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(3, attributes.Length);
attributes[0].AssertIsDocumentationName("My Name 1");
attributes[1].AssertIsDocumentationDescription("My Description 1");
attributes[2].AssertIsDocumentationDescription("My Description 2");
}
[Fact]
public static void TestUnprotectedAttributes1_Arbitrary_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(
new AsnEncodedData(new Oid(Oids.Pkcs7Data), new byte[] { 4, 3, 6, 7, 8 })
);
VerifyUnprotectedAttributes_Arbitrary1(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_Arbitrary_FixedValue()
{
byte[] encodedMessage =
("3082012406092a864886f70d010703a0820115308201110201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "800f310e1c63177fd87bbacd13de65aae943fff87a1da112b9d1a2578c444ebfeb5d72db13104e1f72231651f1a46dec72c1"
+ "91ae859e2cd96df3f94599fff2fdc9074ea9722739c9b0ac870acd073c11375d79ab7679b0d2ebab839f0c2ee975d7ef4a59"
+ "5933aebfcae745f98109c0e5cfd298960cebd244d6a029d9f21bfe60fb302b06092a864886f70d010701301406082a864886"
+ "f70d03070408aa76edcbc0a03d7d8008aefe2086db6f8f7ca114301206092a864886f70d01070131050403060708").HexToByteArray();
VerifyUnprotectedAttributes_Arbitrary1(encodedMessage);
}
private static void VerifyUnprotectedAttributes_Arbitrary1(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
AsnEncodedData a = attributes[0];
Assert.Equal(Oids.Pkcs7Data, a.Oid.Value);
byte[] expectedRawData = { 4, 3, 6, 7, 8 };
Assert.Equal<byte>(expectedRawData, a.RawData);
}
[Fact]
public static void TestUnprotectedAttributes1_OutOfNamespace_RoundTrip()
{
byte[] constraintsRawData = "30070101ff02020100".HexToByteArray();
byte[] encodedMessage = CreateEcmsWithAttributes(
new AsnEncodedData(Oids.BasicConstraints2, constraintsRawData)
);
VerifyUnprotectedAttributes1_OutOfNamespace(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_OutOfNamespace_FixedValue()
{
byte[] encodedMessage =
("3082012206092a864886f70d010703a08201133082010f0201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "801dd92ffa848bc03011c8aae71d63c9a81fdbb2e2c82c284bcbe40d77c3f67beb8cdd2c017470a48189e8ccd3d310bde567"
+ "202e3a03cb9866d19262bda6a489c957e14b1068ecfb2ae8ea1cbf47c6a934a5eed8ce05965356e033f2a1c68001cd308604"
+ "50f28b7949af886727fb506d64ae7889f613c03729a7b834591881666c302b06092a864886f70d010701301406082a864886"
+ "f70d0307040814a020bca56417de8008a260d0e4e138743ea11230100603551d13310930070101ff02020100").HexToByteArray();
VerifyUnprotectedAttributes1_OutOfNamespace(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_OutOfNamespace(byte[] encodedMessage)
{
byte[] constraintsRawData = "30070101ff02020100".HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
AsnEncodedData a = attributes[0];
Assert.Equal(Oids.BasicConstraints2, a.Oid.Value);
Assert.Equal<byte>(constraintsRawData, a.RawData);
}
[Fact]
public static void TestUnprotectedAttributes_AlwaysReturnsPkcs9AttributeObject()
{
byte[] encodedMessage = CreateEcmsWithAttributes(
new AsnEncodedData(new Oid(Oids.Pkcs7Data), new byte[] { 4, 3, 6, 7, 8 })
);
// ecms.Decode() always populates UnprotectedAttribute objects with Pkcs9AttributeObjects (or one of its derived classes) rather than
// AsnEncodedData instances. Verify that any new implementation does this as someone out there is probably
// casting to Pkcs9AttributeObject without checking.
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
AsnEncodedData a = attributes[0];
Assert.True(a is Pkcs9AttributeObject);
}
private static void AssertIsDocumentationDescription(this AsnEncodedData attribute, string expectedDocumentDescription)
{
Assert.Equal(Oids.DocumentDescription, attribute.Oid.Value);
Pkcs9DocumentDescription enhancedAttribute = attribute as Pkcs9DocumentDescription;
Assert.NotNull(enhancedAttribute);
Assert.Equal(expectedDocumentDescription, enhancedAttribute.DocumentDescription);
}
private static void AssertIsDocumentationName(this AsnEncodedData attribute, string expectedDocumentName)
{
Assert.Equal(Oids.DocumentName, attribute.Oid.Value);
Pkcs9DocumentName enhancedAttribute = attribute as Pkcs9DocumentName;
Assert.NotNull(enhancedAttribute);
Assert.Equal(expectedDocumentName, enhancedAttribute.DocumentName);
}
private static void AssertIsSigningTime(this AsnEncodedData attribute, DateTime expectedTime)
{
Assert.Equal(Oids.SigningTime, attribute.Oid.Value);
Pkcs9SigningTime enhancedAttribute = attribute as Pkcs9SigningTime;
Assert.NotNull(enhancedAttribute);
Assert.Equal(expectedTime, enhancedAttribute.SigningTime);
}
private static void AssertIsContentType(this AsnEncodedData attribute, string expectedContentType)
{
Assert.Equal(Oids.ContentType, attribute.Oid.Value);
Pkcs9ContentType enhancedAttribute = attribute as Pkcs9ContentType;
Assert.NotNull(enhancedAttribute);
Assert.Equal(expectedContentType, enhancedAttribute.ContentType.Value);
}
private static void AssertIsMessageDigest(this AsnEncodedData attribute, byte[] expectedDigest)
{
Assert.Equal(Oids.MessageDigest, attribute.Oid.Value);
Pkcs9MessageDigest enhancedAttribute = attribute as Pkcs9MessageDigest;
Assert.NotNull(enhancedAttribute);
Assert.Equal<byte>(expectedDigest, enhancedAttribute.MessageDigest);
}
private static byte[] CreateEcmsWithAttributes(params AsnEncodedData[] attributes)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
foreach (AsnEncodedData attribute in attributes)
{
ecms.UnprotectedAttributes.Add(attribute);
}
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(cert);
ecms.Encrypt(cmsRecipient);
}
byte[] encodedMessage = ecms.Encode();
return encodedMessage;
}
private static AsnEncodedData[] FlattenAndSort(this CryptographicAttributeObjectCollection col)
{
List<AsnEncodedData> attributes = new List<AsnEncodedData>();
foreach (CryptographicAttributeObject cao in col)
{
AsnEncodedDataCollection acol = cao.Values;
foreach (AsnEncodedData a in acol)
{
attributes.Add(a);
}
}
return attributes.OrderBy(a => a.RawData.ByteArrayToHex()).ToArray();
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <michaldominik@gmail.com> //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included //
// in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE. //
// //
////////////////////////////////////////////////////////////////////////////////
namespace Diva.Editor.Gui {
using System;
using Mono.Unix;
using Gtk;
using Util;
using Widgets;
using Gdv;
public class JumpToWindow : Gtk.Window {
// Translatable ////////////////////////////////////////////////
readonly static string titleSS = Catalog.GetString
("Jump To");
readonly static string hoursSS = Catalog.GetString
("Hours:");
readonly static string minutesSS = Catalog.GetString
("Minutes:");
readonly static string secondsSS = Catalog.GetString
("Seconds:");
readonly static string framesSS = Catalog.GetString
("Frame");
readonly static string jumpToSS = Catalog.GetString
("Jump to:");
// Fields //////////////////////////////////////////////////////
Model.Root modelRoot = null;
VBox mainVBox = null;
HBox spinnerHBox = null;
HButtonBox buttonBox = null;
SpinButton spinHours = null;
SpinButton spinMinutes = null;
SpinButton spinSeconds = null;
SpinButton spinFrames = null;
Label jumpToLabel = null;
Gdv.Fraction fps;
// Properties //////////////////////////////////////////////////
// Public methods //////////////////////////////////////////////
/* CONSTRUCTOR */
public JumpToWindow (Model.Root root, Window parent) : base (titleSS)
{
modelRoot = root;
modelRoot.Pipeline.Ticker += OnTicker;
fps = modelRoot.ProjectDetails.Format.VideoFormat.Fps;
//realFps = fps.Numerator / fps.Denominator;
Console.WriteLine (fps.ToString());
Console.WriteLine (fps.FpsFrameDuration());
Console.WriteLine (fps);
spinHours = new SpinButton (0, 99, 1);
spinMinutes = new SpinButton (-1, 60, 1);
spinSeconds = new SpinButton (-1, 60, 1);
spinFrames = new SpinButton (-1, 25, 1);
SyncFromTicker();
spinHours.ValueChanged += SpinnerChanged;
spinMinutes.ValueChanged += SpinnerChanged;
spinSeconds.ValueChanged += SpinnerChanged;
spinFrames.ValueChanged += SpinnerChanged;
//spinner vbox
spinnerHBox = new HBox (false, 2);
Label hoursLabel = new Label (hoursSS);
Label minutesLabel = new Label (minutesSS);
Label secondsLabel = new Label (secondsSS);
Label framesLabel = new Label (framesSS);
VBox hoursHBox = new VBox (false, 6);
hoursHBox.Add (hoursLabel);
hoursHBox.Add (spinHours);
VBox minutesHBox = new VBox (false, 6);
minutesHBox.Add (minutesLabel);
minutesHBox.Add (spinMinutes);
VBox secondsHBox = new VBox (false, 6);
secondsHBox.Add (secondsLabel);
secondsHBox.Add (spinSeconds);
VBox framesHBox = new VBox (false, 6);
framesHBox.Add (framesLabel);
framesHBox.Add (spinFrames);
spinnerHBox.Add (hoursHBox);
spinnerHBox.Add (minutesHBox);
spinnerHBox.Add (secondsHBox);
spinnerHBox.Add (framesHBox);
mainVBox = new VBox (false, 6);
buttonBox = new HButtonBox ();
TransientFor = parent;
//buttons
Button closeButton = new Button (Stock.Close);
closeButton.Clicked += OnCloseButtonClicked;
//buttonBox
buttonBox.Add (closeButton);
buttonBox.Spacing = 6;
//cannonical time HBox
HBox canonicalHBox = new HBox ();
canonicalHBox.Spacing = 6;
jumpToLabel = new Label ();
SpinnerChanged (null, null);
canonicalHBox.Add (jumpToLabel);
//mainVBox
mainVBox.Spacing = 6;
mainVBox.PackStart (canonicalHBox);
mainVBox.PackStart (spinnerHBox);
mainVBox.PackStart (buttonBox);
Add (mainVBox);
//FIXME: change to CenterOfParent when the parent window is being sent correctly
SetDefaultSize (200, 300);
WindowPosition = WindowPosition.Center;
ShowAll();
}
// Private methods /////////////////////////////////////////////
void OnCloseButtonClicked (object o, EventArgs args)
{
Destroy ();
}
void OnTicker (object o, Model.PipelineTickerArgs args)
{
Console.WriteLine ("state changed!");
Console.WriteLine (args.Time);
SyncFromTicker();
}
void SpinnerChanged(object o, EventArgs args)
{
if ( spinFrames.Value == 25 )
{
spinFrames.Value = 0;
spinSeconds.Value += 1;
}else if ( spinFrames.Value == -1 )
{
if ( spinSeconds.Value == 0 )
{
if ( spinMinutes.Value == 0 )
{
if ( spinHours.Value == 0 )
{
spinFrames.Value = 0;
}else {
spinHours.Value -= 1;
spinMinutes.Value -= 1;
spinSeconds.Value -= 1;
spinFrames.Value = 25 -1;
}
}else {
spinMinutes.Value -= 1;
spinSeconds.Value = 59;
spinFrames.Value = 25 -1;
}
}else {
spinFrames.Value = 25 - 1;
spinSeconds.Value -= 1;
}
}
if ( spinSeconds.Value == 60 )
{
spinSeconds.Value = 0;
spinMinutes.Value += 1;
}else if ( spinSeconds.Value == -1 )
{
if ( spinMinutes.Value == 0 )
{
if ( spinHours.Value == 0 )
{
spinSeconds.Value = 0;
}
}else {
spinSeconds.Value = 59;
spinMinutes.Value -= 1;
}
}
if ( spinMinutes.Value == 60 )
{
spinMinutes.Value = 0;
spinHours.Value += 1;
}else if ( spinMinutes.Value == -1 )
{
if ( spinHours.Value == 0 )
{
spinMinutes.Value = 0;
}else {
spinHours.Value -= 1;
spinMinutes.Value = 59;
}
}
SyncToTicker();
}
private void SyncToTicker()
{
String smpte = String.Format ("{0}:{1}:{2}:{3}" , spinHours.Value, spinMinutes.Value, spinSeconds.Value, spinFrames.Value);
Gdv.Time t = TimeFu.FromSMPTE (smpte, fps);
jumpToLabel.UseMarkup = true;
jumpToLabel.Markup = String.Format ("<big><b>{0} {1}</b></big>" , jumpToSS, TimeFu.ToLongString (t) );
modelRoot.Pipeline.Seek(t);
}
private void SyncFromTicker()
{
Gdv.Time startTime = modelRoot.Pipeline.CurrentTicker;
String hours = TimeFu.SMPTEHours (startTime);
String minutes = TimeFu.SMPTEMinutes (startTime);
String seconds = TimeFu.SMPTESeconds (startTime);
String frames = TimeFu.SMPTEFrames (startTime, fps);
spinHours.Value = Double.Parse (hours);
spinMinutes.Value = Double.Parse (minutes);
spinSeconds.Value = Double.Parse (seconds);
spinFrames.Value = Double.Parse (frames);
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.ToolPackage;
using Microsoft.DotNet.Tools.Tool.Install;
using Microsoft.DotNet.Tools.Tests.ComponentMocks;
using Microsoft.DotNet.Tools.Test.Utilities;
using Microsoft.DotNet.Tools.Tool.Update;
using Microsoft.Extensions.DependencyModel.Tests;
using Microsoft.Extensions.EnvironmentAbstractions;
using Xunit;
using Parser = Microsoft.DotNet.Cli.Parser;
using LocalizableStrings = Microsoft.DotNet.Tools.Tool.Update.LocalizableStrings;
using Microsoft.DotNet.ShellShim;
using System.IO;
namespace Microsoft.DotNet.Tests.Commands.Tool
{
public class ToolUpdateGlobalOrToolPathCommandTests
{
private readonly BufferedReporter _reporter;
private readonly IFileSystem _fileSystem;
private readonly EnvironmentPathInstructionMock _environmentPathInstructionMock;
private readonly ToolPackageStoreMock _store;
private readonly PackageId _packageId = new PackageId("global.tool.console.demo");
private readonly List<MockFeed> _mockFeeds;
private const string LowerPackageVersion = "1.0.4";
private const string HigherPackageVersion = "1.0.5";
private const string HigherPreviewPackageVersion = "1.0.5-preview3";
private readonly string _shimsDirectory;
private readonly string _toolsDirectory;
public ToolUpdateGlobalOrToolPathCommandTests()
{
_reporter = new BufferedReporter();
_fileSystem = new FileSystemMockBuilder().UseCurrentSystemTemporaryDirectory().Build();
var tempDirectory = _fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath;
_shimsDirectory = Path.Combine(tempDirectory, "shims");
_toolsDirectory = Path.Combine(tempDirectory, "tools");
_environmentPathInstructionMock = new EnvironmentPathInstructionMock(_reporter, _shimsDirectory);
_store = new ToolPackageStoreMock(new DirectoryPath(_toolsDirectory), _fileSystem);
_mockFeeds = new List<MockFeed>
{
new MockFeed
{
Type = MockFeedType.FeedFromGlobalNugetConfig,
Packages = new List<MockFeedPackage>
{
new MockFeedPackage
{
PackageId = _packageId.ToString(),
Version = LowerPackageVersion,
ToolCommandName = "SimulatorCommand"
},
new MockFeedPackage
{
PackageId = _packageId.ToString(),
Version = HigherPackageVersion,
ToolCommandName = "SimulatorCommand"
},
new MockFeedPackage
{
PackageId = _packageId.ToString(),
Version = HigherPreviewPackageVersion,
ToolCommandName = "SimulatorCommand"
}
}
}
};
}
[Fact]
public void GivenANonFeedExistentPackageItErrors()
{
var packageId = "does.not.exist";
var command = CreateUpdateCommand($"-g {packageId}");
Action a = () => command.Execute();
a.ShouldThrow<GracefulException>().And.Message
.Should().Contain(
Tools.Tool.Install.LocalizableStrings.ToolInstallationRestoreFailed);
}
[Fact]
public void GivenANonExistentPackageItInstallTheLatest()
{
var command = CreateUpdateCommand($"-g {_packageId}");
command.Execute();
_store.EnumeratePackageVersions(_packageId).Single().Version.ToFullString().Should()
.Be(HigherPackageVersion);
}
[Fact]
public void GivenAnExistedLowerversionInstallationWhenCallItCanUpdateThePackageVersion()
{
CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute();
var command = CreateUpdateCommand($"-g {_packageId}");
command.Execute();
_store.EnumeratePackageVersions(_packageId).Single().Version.ToFullString().Should()
.Be(HigherPackageVersion);
}
[Fact]
public void GivenAnExistedLowerversionInstallationWhenCallFromRedirectorItCanUpdateThePackageVersion()
{
CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute();
ParseResult result = Parser.Instance.Parse("dotnet tool update " + $"-g {_packageId}");
AppliedOption appliedCommand = result["dotnet"]["tool"]["update"];
var toolUpdateGlobalOrToolPathCommand = new ToolUpdateGlobalOrToolPathCommand(
appliedCommand,
result,
(location, forwardArguments) => (_store, _store, new ToolPackageInstallerMock(
_fileSystem,
_store,
new ProjectRestorerMock(
_fileSystem,
_reporter,
_mockFeeds
)),
new ToolPackageUninstallerMock(_fileSystem, _store)),
(_) => GetMockedShellShimRepository(),
_reporter);
var toolUpdateCommand = new ToolUpdateCommand(
appliedCommand,
result,
_reporter,
toolUpdateGlobalOrToolPathCommand,
new ToolUpdateLocalCommand(appliedCommand, result));
toolUpdateCommand.Execute();
_store.EnumeratePackageVersions(_packageId).Single().Version.ToFullString().Should()
.Be(HigherPackageVersion);
}
[Fact]
public void GivenAnExistedLowerversionInstallationWhenCallItCanPrintSuccessMessage()
{
CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute();
_reporter.Lines.Clear();
var command = CreateUpdateCommand($"-g {_packageId}");
command.Execute();
_reporter.Lines.First().Should().Contain(string.Format(
LocalizableStrings.UpdateSucceeded,
_packageId, LowerPackageVersion, HigherPackageVersion));
}
[Fact]
public void GivenAnExistedLowerversionInstallationWhenCallWithWildCardVersionItCanPrintSuccessMessage()
{
CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute();
_reporter.Lines.Clear();
var command = CreateUpdateCommand($"-g {_packageId} --version 1.0.5-*");
command.Execute();
_reporter.Lines.First().Should().Contain(string.Format(
LocalizableStrings.UpdateSucceeded,
_packageId, LowerPackageVersion, HigherPreviewPackageVersion));
}
[Fact]
public void GivenAnExistedHigherVersionInstallationWhenCallWithLowerVersionItThrowsAndRollsBack()
{
CreateInstallCommand($"-g {_packageId} --version {HigherPackageVersion}").Execute();
_reporter.Lines.Clear();
var command = CreateUpdateCommand($"-g {_packageId} --version {LowerPackageVersion}");
Action a = () => command.Execute();
a.ShouldThrow<GracefulException>().And.Message
.Should().Contain(
string.Format(LocalizableStrings.UpdateToLowerVersion,
LowerPackageVersion,
HigherPackageVersion));
_store.EnumeratePackageVersions(_packageId).Single().Version.ToFullString().Should()
.Be(HigherPackageVersion);
}
[Fact]
public void GivenAnExistedSameVersionInstallationWhenCallItCanPrintSuccessMessage()
{
CreateInstallCommand($"-g {_packageId} --version {HigherPackageVersion}").Execute();
_reporter.Lines.Clear();
var command = CreateUpdateCommand($"-g {_packageId}");
command.Execute();
_reporter.Lines.First().Should().Contain(string.Format(
LocalizableStrings.UpdateSucceededVersionNoChange,
_packageId, HigherPackageVersion));
}
[Fact]
public void GivenAnExistedLowerversionWhenReinstallThrowsIthasTheFirstLineIndicateUpdateFailure()
{
CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute();
_reporter.Lines.Clear();
ParseResult result = Parser.Instance.Parse("dotnet tool update " + $"-g {_packageId}");
var command = new ToolUpdateGlobalOrToolPathCommand(
result["dotnet"]["tool"]["update"],
result,
(location, forwardArguments) => (_store, _store,
new ToolPackageInstallerMock(
_fileSystem,
_store,
new ProjectRestorerMock(
_fileSystem,
_reporter,
_mockFeeds
),
installCallback: () => throw new ToolConfigurationException("Simulated error")),
new ToolPackageUninstallerMock(_fileSystem, _store)),
_ => GetMockedShellShimRepository(),
_reporter);
Action a = () => command.Execute();
a.ShouldThrow<GracefulException>().And.Message.Should().Contain(
string.Format(LocalizableStrings.UpdateToolFailed, _packageId) + Environment.NewLine +
string.Format(Tools.Tool.Install.LocalizableStrings.InvalidToolConfiguration, "Simulated error"));
}
[Fact]
public void GivenAnExistedLowerversionWhenReinstallThrowsItRollsBack()
{
CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute();
_reporter.Lines.Clear();
ParseResult result = Parser.Instance.Parse("dotnet tool update " + $"-g {_packageId}");
var command = new ToolUpdateGlobalOrToolPathCommand(
result["dotnet"]["tool"]["update"],
result,
(location, forwardArguments) => (_store, _store,
new ToolPackageInstallerMock(
_fileSystem,
_store,
new ProjectRestorerMock(
_fileSystem,
_reporter,
_mockFeeds
),
installCallback: () => throw new ToolConfigurationException("Simulated error")),
new ToolPackageUninstallerMock(_fileSystem, _store)),
_ => GetMockedShellShimRepository(),
_reporter);
Action a = () => command.Execute();
_store.EnumeratePackageVersions(_packageId).Single().Version.ToFullString().Should()
.Be(LowerPackageVersion);
}
private ToolInstallGlobalOrToolPathCommand CreateInstallCommand(string options)
{
ParseResult result = Parser.Instance.Parse("dotnet tool install " + options);
return new ToolInstallGlobalOrToolPathCommand(
result["dotnet"]["tool"]["install"],
result,
(location, forwardArguments) => (_store, _store, new ToolPackageInstallerMock(
_fileSystem,
_store,
new ProjectRestorerMock(
_fileSystem,
_reporter,
_mockFeeds
))),
(_) => GetMockedShellShimRepository(),
_environmentPathInstructionMock,
_reporter);
}
private ToolUpdateGlobalOrToolPathCommand CreateUpdateCommand(string options)
{
ParseResult result = Parser.Instance.Parse("dotnet tool update " + options);
return new ToolUpdateGlobalOrToolPathCommand(
result["dotnet"]["tool"]["update"],
result,
(location, forwardArguments) => (_store, _store, new ToolPackageInstallerMock(
_fileSystem,
_store,
new ProjectRestorerMock(
_fileSystem,
_reporter,
_mockFeeds
)),
new ToolPackageUninstallerMock(_fileSystem, _store)),
(_) => GetMockedShellShimRepository(),
_reporter);
}
private ShellShimRepository GetMockedShellShimRepository()
{
return new ShellShimRepository(
new DirectoryPath(_shimsDirectory),
fileSystem: _fileSystem,
appHostShellShimMaker: new AppHostShellShimMakerMock(_fileSystem));
}
}
}
| |
namespace LuaInterface.Tests
{
using System;
using LuaInterface;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
using SharpLua;
/*
* Delegates used for testing Lua function -> delegate translation
*/
public delegate int TestDelegate1(int a, int b);
public delegate int TestDelegate2(int a, out int b);
public delegate void TestDelegate3(int a, ref int b);
public delegate TestClass TestDelegate4(int a, int b);
public delegate int TestDelegate5(TestClass a, TestClass b);
public delegate int TestDelegate6(int a, out TestClass b);
public delegate void TestDelegate7(int a, ref TestClass b);
/*
* Interface used for testing Lua table -> interface translation
*/
public interface ITest
{
int intProp
{
get;
set;
}
TestClass refProp
{
get;
set;
}
int test1(int a, int b);
int test2(int a, out int b);
void test3(int a, ref int b);
TestClass test4(int a, int b);
int test5(TestClass a, TestClass b);
int test6(int a, out TestClass b);
void test7(int a, ref TestClass b);
}
public interface IFoo1
{
int foo();
}
public interface IFoo2
{
int foo();
}
class MyClass
{
public int Func1() { return 1; }
}
/// <summary>
/// test structure passing
/// </summary>
public struct TestStruct
{
public TestStruct(float val)
{
v = val;
}
public float v;
public float val
{
get { return v; }
set { v = value; }
}
}
/*
* Sample class used in several test cases to check if
* Lua scripts are accessing objects correctly
*/
public class TestClass : IFoo1, IFoo2
{
public int val;
private string strVal;
public TestClass()
{
val = 0;
}
public TestClass(int val)
{
this.val = val;
}
public TestClass(string val)
{
this.strVal = val;
}
public static TestClass makeFromString(String str)
{
return new TestClass(str);
}
bool? nb2 = null;
public bool? NullableBool
{
get { return nb2; }
set { nb2 = value; }
}
TestStruct s = new TestStruct();
public TestStruct Struct
{
get { return s; }
set { s = (TestStruct)value; }
}
public int testval
{
get
{
return this.val;
}
set
{
this.val = value;
}
}
public int this[int index]
{
get { return 1; }
set { }
}
public int this[string index]
{
get { return 1; }
set { }
}
public int sum(int x, int y)
{
return x + y;
}
public void setVal(int newVal)
{
val = newVal;
}
public void setVal(string newVal)
{
strVal = newVal;
}
public int getVal()
{
return val;
}
public string getStrVal()
{
return strVal;
}
public int outVal(out int val)
{
val = 5;
return 3;
}
public int outVal(out int val, int val2)
{
val = 5;
return val2;
}
public int outVal(int val, ref int val2)
{
val2 = val + val2;
return val;
}
public int callDelegate1(TestDelegate1 del)
{
return del(2, 3);
}
public int callDelegate2(TestDelegate2 del)
{
int a = 3;
int b = del(2, out a);
return a + b;
}
public int callDelegate3(TestDelegate3 del)
{
int a = 3;
del(2, ref a);
//Console.WriteLine(a);
return a;
}
public int callDelegate4(TestDelegate4 del)
{
return del(2, 3).testval;
}
public int callDelegate5(TestDelegate5 del)
{
return del(new TestClass(2), new TestClass(3));
}
public int callDelegate6(TestDelegate6 del)
{
TestClass test = new TestClass();
int a = del(2, out test);
return a + test.testval;
}
public int callDelegate7(TestDelegate7 del)
{
TestClass test = new TestClass(3);
del(2, ref test);
return test.testval;
}
public int callInterface1(ITest itest)
{
return itest.test1(2, 3);
}
public int callInterface2(ITest itest)
{
int a = 3;
int b = itest.test2(2, out a);
return a + b;
}
public int callInterface3(ITest itest)
{
int a = 3;
itest.test3(2, ref a);
//Console.WriteLine(a);
return a;
}
public int callInterface4(ITest itest)
{
return itest.test4(2, 3).testval;
}
public int callInterface5(ITest itest)
{
return itest.test5(new TestClass(2), new TestClass(3));
}
public int callInterface6(ITest itest)
{
TestClass test = new TestClass();
int a = itest.test6(2, out test);
return a + test.testval;
}
public int callInterface7(ITest itest)
{
TestClass test = new TestClass(3);
itest.test7(2, ref test);
return test.testval;
}
public int callInterface8(ITest itest)
{
itest.intProp = 3;
return itest.intProp;
}
public int callInterface9(ITest itest)
{
itest.refProp = new TestClass(3);
return itest.refProp.testval;
}
public void exceptionMethod()
{
throw new Exception("exception test");
}
public virtual int overridableMethod(int x, int y)
{
return x + y;
}
public static int callOverridable(TestClass test, int x, int y)
{
return test.overridableMethod(x, y);
}
int IFoo1.foo()
{
return 3;
}
public int foo()
{
return 5;
}
}
/*
* Automated test cases for LuaInterface
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class TestLuaInterface
{
private LuaInterface lua;
/*
* Executed before each test case
*/
public void Init()
{
lua = new LuaInterface();
GC.Collect(); // runs GC to expose unprotected delegates
}
/*
* Executed after each test case
*/
public void Destroy()
{
lua = null;
}
#if false
// I've commented out the nunit based tests until they can run standalone - so that users don't need nunit to run TestLua
/*
* Tests if DoString is correctly returning values
*/
[Test]
public void DoString()
{
object[] res=lua.DoString("a=2\nreturn a,3");
//Console.WriteLine("a="+res[0]+", b="+res[1]);
Assertion.AssertEquals(res[0],2);
Assertion.AssertEquals(res[1],3);
}
/*
* Tests getting of global numeric variables
*/
[Test]
public void GetGlobalNumber()
{
lua.DoString("a=2");
double num=lua.GetNumber("a");
//Console.WriteLine("a="+num);
Assertion.AssertEquals(num,2);
}
/*
* Tests setting of global numeric variables
*/
[Test]
public void SetGlobalNumber()
{
lua.DoString("a=2");
lua["a"]=3;
double num=lua.GetNumber("a");
//Console.WriteLine("a="+num);
Assertion.AssertEquals(num,3);
}
/*
* Tests getting of numeric variables from tables
* by specifying variable path
*/
[Test]
public void GetNumberInTable()
{
lua.DoString("a={b={c=2}}");
double num=lua.GetNumber("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assertion.AssertEquals(num,2);
}
/*
* Tests setting of numeric variables from tables
* by specifying variable path
*/
[Test]
public void SetNumberInTable()
{
lua.DoString("a={b={c=2}}");
lua["a.b.c"]=3;
double num=lua.GetNumber("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assertion.AssertEquals(num,3);
}
/*
* Tests getting of global string variables
*/
[Test]
public void GetGlobalString()
{
lua.DoString("a=\"test\"");
string str=lua.GetString("a");
//Console.WriteLine("a="+str);
Assertion.AssertEquals(str,"test");
}
/*
* Tests setting of global string variables
*/
[Test]
public void SetGlobalString()
{
lua.DoString("a=\"test\"");
lua["a"]="new test";
string str=lua.GetString("a");
//Console.WriteLine("a="+str);
Assertion.AssertEquals(str,"new test");
}
/*
* Tests getting of string variables from tables
* by specifying variable path
*/
[Test]
public void GetStringInTable()
{
lua.DoString("a={b={c=\"test\"}}");
string str=lua.GetString("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assertion.AssertEquals(str,"test");
}
/*
* Tests setting of string variables from tables
* by specifying variable path
*/
[Test]
public void SetStringInTable()
{
lua.DoString("a={b={c=\"test\"}}");
lua["a.b.c"]="new test";
string str=lua.GetString("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assertion.AssertEquals(str,"new test");
}
/*
* Tests getting and setting of global table variables
*/
[Test]
public void GetAndSetTable()
{
lua.DoString("a={b={c=2}}\nb={c=3}");
LuaTable tab=lua.GetTable("b");
lua["a.b"]=tab;
double num=lua.GetNumber("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assertion.AssertEquals(num,3);
}
/*
* Tests getting of numeric field of a table
*/
[Test]
public void GetTableNumericField1()
{
lua.DoString("a={b={c=2}}");
LuaTable tab=lua.GetTable("a.b");
double num=(double)tab["c"];
//Console.WriteLine("a.b.c="+num);
Assertion.AssertEquals(num,2);
}
/*
* Tests getting of numeric field of a table
* (the field is inside a subtable)
*/
[Test]
public void GetTableNumericField2()
{
lua.DoString("a={b={c=2}}");
LuaTable tab=lua.GetTable("a");
double num=(double)tab["b.c"];
//Console.WriteLine("a.b.c="+num);
Assertion.AssertEquals(num,2);
}
/*
* Tests setting of numeric field of a table
*/
[Test]
public void SetTableNumericField1()
{
lua.DoString("a={b={c=2}}");
LuaTable tab=lua.GetTable("a.b");
tab["c"]=3;
double num=lua.GetNumber("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assertion.AssertEquals(num,3);
}
/*
* Tests setting of numeric field of a table
* (the field is inside a subtable)
*/
[Test]
public void SetTableNumericField2()
{
lua.DoString("a={b={c=2}}");
LuaTable tab=lua.GetTable("a");
tab["b.c"]=3;
double num=lua.GetNumber("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assertion.AssertEquals(num,3);
}
/*
* Tests getting of string field of a table
*/
[Test]
public void GetTableStringField1()
{
lua.DoString("a={b={c=\"test\"}}");
LuaTable tab=lua.GetTable("a.b");
string str=(string)tab["c"];
//Console.WriteLine("a.b.c="+str);
Assertion.AssertEquals(str,"test");
}
/*
* Tests getting of string field of a table
* (the field is inside a subtable)
*/
[Test]
public void GetTableStringField2()
{
lua.DoString("a={b={c=\"test\"}}");
LuaTable tab=lua.GetTable("a");
string str=(string)tab["b.c"];
//Console.WriteLine("a.b.c="+str);
Assertion.AssertEquals(str,"test");
}
/*
* Tests setting of string field of a table
*/
[Test]
public void SetTableStringField1()
{
lua.DoString("a={b={c=\"test\"}}");
LuaTable tab=lua.GetTable("a.b");
tab["c"]="new test";
string str=lua.GetString("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assertion.AssertEquals(str,"new test");
}
/*
* Tests setting of string field of a table
* (the field is inside a subtable)
*/
[Test]
public void SetTableStringField2()
{
lua.DoString("a={b={c=\"test\"}}");
LuaTable tab=lua.GetTable("a");
tab["b.c"]="new test";
string str=lua.GetString("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assertion.AssertEquals(str,"new test");
}
/*
* Tests calling of a global function with zero arguments
*/
[Test]
public void CallGlobalFunctionNoArgs()
{
lua.DoString("a=2\nfunction f()\na=3\nend");
lua.GetFunction("f").Call();
double num=lua.GetNumber("a");
//Console.WriteLine("a="+num);
Assertion.AssertEquals(num,3);
}
/*
* Tests calling of a global function with one argument
*/
[Test]
public void CallGlobalFunctionOneArg()
{
lua.DoString("a=2\nfunction f(x)\na=a+x\nend");
lua.GetFunction("f").Call(1);
double num=lua.GetNumber("a");
//Console.WriteLine("a="+num);
Assertion.AssertEquals(num,3);
}
/*
* Tests calling of a global function with two arguments
*/
[Test]
public void CallGlobalFunctionTwoArgs()
{
lua.DoString("a=2\nfunction f(x,y)\na=x+y\nend");
lua.GetFunction("f").Call(1,3);
double num=lua.GetNumber("a");
//Console.WriteLine("a="+num);
Assertion.AssertEquals(num,4);
}
/*
* Tests calling of a global function that returns one value
*/
[Test]
public void CallGlobalFunctionOneReturn()
{
lua.DoString("function f(x)\nreturn x+2\nend");
object[] ret=lua.GetFunction("f").Call(3);
//Console.WriteLine("ret="+ret[0]);
Assertion.AssertEquals(1,ret.Length);
Assertion.AssertEquals(5,ret[0]);
}
/*
* Tests calling of a global function that returns two values
*/
[Test]
public void CallGlobalFunctionTwoReturns()
{
lua.DoString("function f(x,y)\nreturn x,x+y\nend");
object[] ret=lua.GetFunction("f").Call(3,2);
//Console.WriteLine("ret="+ret[0]+","+ret[1]);
Assertion.AssertEquals(2,ret.Length);
Assertion.AssertEquals(3,ret[0]);
Assertion.AssertEquals(5,ret[1]);
}
/*
* Tests calling of a function inside a table
*/
[Test]
public void CallTableFunctionTwoReturns()
{
lua.DoString("a={}\nfunction a.f(x,y)\nreturn x,x+y\nend");
object[] ret=lua.GetFunction("a.f").Call(3,2);
//Console.WriteLine("ret="+ret[0]+","+ret[1]);
Assertion.AssertEquals(2,ret.Length);
Assertion.AssertEquals(3,ret[0]);
Assertion.AssertEquals(5,ret[1]);
}
/*
* Tests setting of a global variable to a CLR object value
*/
[Test]
public void SetGlobalObject()
{
TestClass t1=new TestClass();
t1.testval=4;
lua["netobj"]=t1;
object o=lua["netobj"];
TestClass t2=(TestClass)lua["netobj"];
Assertion.AssertEquals(t2.testval,4);
Assertion.Assert(t1==t2);
}
/*
* Tests if CLR object is being correctly collected by Lua
*/
[Test]
public void GarbageCollection()
{
TestClass t1=new TestClass();
t1.testval=4;
lua["netobj"]=t1;
TestClass t2=(TestClass)lua["netobj"];
Assertion.Assert(lua.translator.objects[0]!=null);
lua.DoString("netobj=nil;collectgarbage();");
Assertion.Assert(lua.translator.objects[0]==null);
}
/*
* Tests setting of a table field to a CLR object value
*/
[Test]
public void SetTableObjectField1()
{
lua.DoString("a={b={c=\"test\"}}");
LuaTable tab=lua.GetTable("a.b");
TestClass t1=new TestClass();
t1.testval=4;
tab["c"]=t1;
TestClass t2=(TestClass)lua["a.b.c"];
//Console.WriteLine("a.b.c="+t2.testval);
Assertion.AssertEquals(t2.testval,4);
Assertion.Assert(t1==t2);
}
/*
* Tests reading and writing of an object's field
*/
[Test]
public void AccessObjectField()
{
TestClass t1=new TestClass();
t1.val=4;
lua["netobj"]=t1;
lua.DoString("var=netobj.val");
double var=(double)lua["var"];
//Console.WriteLine("value from Lua="+var);
Assertion.AssertEquals(4,var);
lua.DoString("netobj.val=3");
Assertion.AssertEquals(3,t1.val);
//Console.WriteLine("new val (from Lua)="+t1.val);
}
/*
* Tests reading and writing of an object's non-indexed
* property
*/
[Test]
public void AccessObjectProperty()
{
TestClass t1=new TestClass();
t1.testval=4;
lua["netobj"]=t1;
lua.DoString("var=netobj.testval");
double var=(double)lua["var"];
//Console.WriteLine("value from Lua="+var);
Assertion.AssertEquals(4,var);
lua.DoString("netobj.testval=3");
Assertion.AssertEquals(3,t1.testval);
//Console.WriteLine("new val (from Lua)="+t1.testval);
}
/*
* Tests calling of an object's method with no overloads
*/
[Test]
public void CallObjectMethod()
{
TestClass t1=new TestClass();
t1.testval=4;
lua["netobj"]=t1;
lua.DoString("netobj:setVal(3)");
Assertion.AssertEquals(3,t1.testval);
//Console.WriteLine("new val(from C#)="+t1.testval);
lua.DoString("val=netobj:getVal()");
int val=(int)lua.GetNumber("val");
Assertion.AssertEquals(3,val);
//Console.WriteLine("new val(from Lua)="+val);
}
/*
* Tests calling of an object's method with overloading
*/
[Test]
public void CallObjectMethodByType()
{
TestClass t1=new TestClass();
lua["netobj"]=t1;
lua.DoString("netobj:setVal('str')");
Assertion.AssertEquals("str",t1.getStrVal());
//Console.WriteLine("new val(from C#)="+t1.getStrVal());
}
/*
* Tests calling of an object's method with no overloading
* and out parameters
*/
[Test]
public void CallObjectMethodOutParam()
{
TestClass t1=new TestClass();
lua["netobj"]=t1;
lua.DoString("a,b=netobj:outVal()");
int a=(int)lua.GetNumber("a");
int b=(int)lua.GetNumber("b");
Assertion.AssertEquals(3,a);
Assertion.AssertEquals(5,b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
/*
* Tests calling of an object's method with overloading and
* out params
*/
[Test]
public void CallObjectMethodOverloadedOutParam()
{
TestClass t1=new TestClass();
lua["netobj"]=t1;
lua.DoString("a,b=netobj:outVal(2)");
int a=(int)lua.GetNumber("a");
int b=(int)lua.GetNumber("b");
Assertion.AssertEquals(2,a);
Assertion.AssertEquals(5,b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
/*
* Tests calling of an object's method with ref params
*/
[Test]
public void CallObjectMethodByRefParam()
{
TestClass t1=new TestClass();
lua["netobj"]=t1;
lua.DoString("a,b=netobj:outVal(2,3)");
int a=(int)lua.GetNumber("a");
int b=(int)lua.GetNumber("b");
Assertion.AssertEquals(2,a);
Assertion.AssertEquals(5,b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
/*
* Tests calling of two versions of an object's method that have
* the same name and signature but implement different interfaces
*/
[Test]
public void CallObjectMethodDistinctInterfaces()
{
TestClass t1=new TestClass();
lua["netobj"]=t1;
lua.DoString("a=netobj:foo()");
lua.DoString("b=netobj['LuaInterface.Tests.IFoo1.foo'](netobj)");
int a=(int)lua.GetNumber("a");
int b=(int)lua.GetNumber("b");
Assertion.AssertEquals(5,a);
Assertion.AssertEquals(3,b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
/*
* Tests instantiating an object with no-argument constructor
*/
[Test]
public void CreateNetObjectNoArgsCons()
{
lua.DoString("load_assembly(\"SharpLua.InterfacingTests\")");
lua.DoString("TestClass=import_type(\"LuaInterface.Tests.TestClass\")");
lua.DoString("test=TestClass()");
lua.DoString("test:setVal(3)");
object[] res=lua.DoString("return test");
TestClass test=(TestClass)res[0];
//Console.WriteLine("returned: "+test.testval);
Assertion.AssertEquals(3,test.testval);
}
/*
* Tests instantiating an object with one-argument constructor
*/
[Test]
public void CreateNetObjectOneArgCons()
{
lua.DoString("load_assembly(\"SharpLua.InterfacingTests\")");
lua.DoString("TestClass=import_type(\"LuaInterface.Tests.TestClass\")");
lua.DoString("test=TestClass(3)");
object[] res=lua.DoString("return test");
TestClass test=(TestClass)res[0];
//Console.WriteLine("returned: "+test.testval);
Assertion.AssertEquals(3,test.testval);
}
/*
* Tests instantiating an object with overloaded constructor
*/
[Test]
public void CreateNetObjectOverloadedCons()
{
lua.DoString("load_assembly(\"SharpLua.InterfacingTests\")");
lua.DoString("TestClass=import_type(\"LuaInterface.Tests.TestClass\")");
lua.DoString("test=TestClass('str')");
object[] res=lua.DoString("return test");
TestClass test=(TestClass)res[0];
//Console.WriteLine("returned: "+test.getStrVal());
Assertion.AssertEquals("str",test.getStrVal());
}
/*
* Tests getting item of a CLR array
*/
[Test]
public void ReadArrayField()
{
string[] arr=new string[] { "str1", "str2", "str3" };
lua["netobj"]=arr;
lua.DoString("val=netobj[1]");
string val=lua.GetString("val");
Assertion.AssertEquals("str2",val);
//Console.WriteLine("new val(from array to Lua)="+val);
}
/*
* Tests setting item of a CLR array
*/
[Test]
public void WriteArrayField()
{
string[] arr=new string[] { "str1", "str2", "str3" };
lua["netobj"]=arr;
lua.DoString("netobj[1]='test'");
Assertion.AssertEquals("test",arr[1]);
//Console.WriteLine("new val(from Lua to array)="+arr[1]);
}
/*
* Tests creating a new CLR array
*/
[Test]
public void CreateArray()
{
lua.DoString("load_assembly(\"SharpLua.InterfacingTests\")");
lua.DoString("TestClass=import_type(\"LuaInterface.Tests.TestClass\")");
lua.DoString("arr=TestClass[3]");
lua.DoString("for i=0,2 do arr[i]=TestClass(i+1) end");
TestClass[] arr=(TestClass[])lua["arr"];
Assertion.AssertEquals(arr[1].testval,2);
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments
*/
[Test]
public void LuaDelegateValueTypes()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("function func(x,y) return x+y; end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callDelegate1(func)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(5,a);
//Console.WriteLine("delegate returned: "+a);
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments and out params
*/
[Test]
public void LuaDelegateValueTypesOutParam()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("function func(x) return x,x*2; end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callDelegate2(func)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(6,a);
//Console.WriteLine("delegate returned: "+a);
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments and ref params
*/
[Test]
public void LuaDelegateValueTypesByRefParam()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("function func(x,y) return x+y; end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callDelegate3(func)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(5,a);
//Console.WriteLine("delegate returned: "+a);
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments that returns a reference type
*/
[Test]
public void LuaDelegateValueTypesReturnReferenceType()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("function func(x,y) return TestClass(x+y); end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callDelegate4(func)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(5,a);
//Console.WriteLine("delegate returned: "+a);
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments
*/
[Test]
public void LuaDelegateReferenceTypes()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("function func(x,y) return x.testval+y.testval; end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callDelegate5(func)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(5,a);
//Console.WriteLine("delegate returned: "+a);
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments and an out param
*/
[Test]
public void LuaDelegateReferenceTypesOutParam()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("function func(x) return x,TestClass(x*2); end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callDelegate6(func)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(6,a);
//Console.WriteLine("delegate returned: "+a);
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments and a ref param
*/
[Test]
public void LuaDelegateReferenceTypesByRefParam()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("function func(x,y) return TestClass(x+y.testval); end");
lua.DoString("a=test:callDelegate7(func)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(5,a);
//Console.WriteLine("delegate returned: "+a);
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
*/
[Test]
public void LuaInterfaceValueTypes()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("itest={}");
lua.DoString("function itest:test1(x,y) return x+y; end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callInterface1(itest)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(5,a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
* and an out param
*/
[Test]
public void LuaInterfaceValueTypesOutParam()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("itest={}");
lua.DoString("function itest:test2(x) return x,x*2; end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callInterface2(itest)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(6,a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
* and a ref param
*/
[Test]
public void LuaInterfaceValueTypesByRefParam()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("itest={}");
lua.DoString("function itest:test3(x,y) return x+y; end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callInterface3(itest)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(5,a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
* returning a reference type param
*/
[Test]
public void LuaInterfaceValueTypesReturnReferenceType()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("itest={}");
lua.DoString("function itest:test4(x,y) return TestClass(x+y); end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callInterface4(itest)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(5,a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with reference type params
*/
[Test]
public void LuaInterfaceReferenceTypes()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("itest={}");
lua.DoString("function itest:test5(x,y) return x.testval+y.testval; end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callInterface5(itest)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(5,a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with reference type params
* and an out param
*/
[Test]
public void LuaInterfaceReferenceTypesOutParam()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("itest={}");
lua.DoString("function itest:test6(x) return x,TestClass(x*2); end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callInterface6(itest)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(6,a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with reference type params
* and a ref param
*/
[Test]
public void LuaInterfaceReferenceTypesByRefParam()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("itest={}");
lua.DoString("function itest:test7(x,y) return TestClass(x+y.testval); end");
lua.DoString("a=test:callInterface7(itest)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(5,a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests passing a Lua table as an interface and
* accessing one of its value-type properties
*/
[Test]
public void LuaInterfaceValueProperty()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("itest={}");
lua.DoString("function itest:get_intProp() return itest.int_prop; end");
lua.DoString("function itest:set_intProp(val) itest.int_prop=val; end");
lua.DoString("a=test:callInterface8(itest)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(3,a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests passing a Lua table as an interface and
* accessing one of its reference type properties
*/
[Test]
public void LuaInterfaceReferenceProperty()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("itest={}");
lua.DoString("function itest:get_refProp() return TestClass(itest.int_prop); end");
lua.DoString("function itest:set_refProp(val) itest.int_prop=val.testval; end");
lua.DoString("a=test:callInterface9(itest)");
int a=(int)lua.GetNumber("a");
Assertion.AssertEquals(3,a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests making an object from a Lua table and calling the base
* class version of one of the methods the table overrides.
*/
[Test]
public void LuaTableBaseMethod()
{
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test={}");
lua.DoString("function test:overridableMethod(x,y) return 2*self.base:overridableMethod(x,y); end");
lua.DoString("make_object(test,'LuaInterface.Tests.TestClass')");
lua.DoString("a=TestClass:callOverridable(test,2,3)");
int a=(int)lua.GetNumber("a");
lua.DoString("free_object(test)");
Assertion.AssertEquals(10,a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests getting an object's method by its signature
* (from object)
*/
[Test]
public void GetMethodBySignatureFromObj()
{
lua.DoString("load_assembly('mscorlib')");
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("setMethod=get_method_bysig(test,'setVal','System.String')");
lua.DoString("setMethod('test')");
TestClass test=(TestClass)lua["test"];
Assertion.AssertEquals("test",test.getStrVal());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
/*
* Tests getting an object's method by its signature
* (from type)
*/
[Test]
public void GetMethodBySignatureFromType()
{
lua.DoString("load_assembly('mscorlib')");
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("setMethod=get_method_bysig(TestClass,'setVal','System.String')");
lua.DoString("setMethod(test,'test')");
TestClass test=(TestClass)lua["test"];
Assertion.AssertEquals("test",test.getStrVal());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
/*
* Tests getting a type's method by its signature
*/
[Test]
public void GetStaticMethodBySignature()
{
lua.DoString("load_assembly('mscorlib')");
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("make_method=get_method_bysig(TestClass,'makeFromString','System.String')");
lua.DoString("test=make_method('test')");
TestClass test=(TestClass)lua["test"];
Assertion.AssertEquals("test",test.getStrVal());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
/*
* Tests getting an object's constructor by its signature
*/
[Test]
public void GetConstructorBySignature()
{
lua.DoString("load_assembly('mscorlib')");
lua.DoString("load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test_cons=get_constructor_bysig(TestClass,'System.String')");
lua.DoString("test=test_cons('test')");
TestClass test=(TestClass)lua["test"];
Assertion.AssertEquals("test",test.getStrVal());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
#endif
void TestOk(bool flag)
{
if (flag)
Console.WriteLine("Test Passed.");
else
Console.WriteLine("Test Failed!!!!");
}
/*
* Tests capturing an exception
*/
public void ThrowException()
{
Init();
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("err,errMsg=pcall(test.exceptionMethod,test)");
bool err = (bool)lua["err"];
Exception errMsg = (Exception)lua["errMsg"];
TestOk(!err);
TestOk("exception test" == errMsg.Message);
//Console.WriteLine("interface returned: "+errMsg.ToString());
Destroy();
}
/*
* Tests capturing an exception
*/
public void ThrowUncaughtException()
{
Init();
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
try
{
lua.DoString("test:exceptionMethod()");
Console.WriteLine("Test failed!!! Should have thrown an exception all the way out of Lua");
}
catch (Exception)
{
Console.WriteLine("Uncaught exception success");
}
Destroy();
}
/*
* Tests nullable fields
*/
public void TestNullable()
{
Init();
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("val=test.NullableBool");
TestOk(((object)lua["val"]) == null);
lua.DoString("test.NullableBool = true");
lua.DoString("val=test.NullableBool");
TestOk(((bool)lua["val"]) == true);
Destroy();
}
/*
* Tests structure assignment
*/
public void TestStructs()
{
Init();
lua.DoString("luanet.load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("TestStruct=luanet.import_type('LuaInterface.Tests.TestStruct')");
lua.DoString("struct=TestStruct(2)");
lua.DoString("test.Struct = struct");
lua.DoString("val=test.Struct.val");
TestOk(((double)lua["val"]) == 2.0);
Destroy();
}
/*
* Tests functions
*/
public void TestFunctions()
{
Init();
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('SharpLua.InterfacingTests')");
lua.RegisterFunction("p", null, typeof(System.Console).GetMethod("WriteLine", new Type[] { typeof(String) }));
/// Lua command that works (prints to console)
lua.DoString("p('Foo')");
/// Yet this works...
lua.DoString("string.gsub('some string', '(%w+)', function(s) p(s) end)");
/// This fails if you don't fix Lua5.1 lstrlib.c/add_value to treat LUA_TUSERDATA the same as LUA_FUNCTION
// lua.DoString("string.gsub('some string', '(%w+)', p)");
Destroy();
}
/*
* Tests making an object from a Lua table and calling one of
* methods the table overrides.
*/
public void LuaTableOverridedMethod()
{
Init();
lua.DoString("luanet.load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test={}");
lua.DoString("function test:overridableMethod(x,y) return x*y; end");
lua.DoString("luanet.make_object(test,'LuaInterface.Tests.TestClass')");
lua.DoString("a=TestClass.callOverridable(test,2,3)");
int a = (int)lua.GetNumber("a");
lua.DoString("luanet.free_object(test)");
TestOk(6 == a);
//Console.WriteLine("interface returned: "+a);
}
/*
* Tests making an object from a Lua table and calling a method
* the table does not override.
*/
public void LuaTableInheritedMethod()
{
Init();
lua.DoString("luanet.load_assembly('SharpLua.InterfacingTests')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
lua.DoString("test={}");
lua.DoString("function test:overridableMethod(x,y) return x*y; end");
lua.DoString("luanet.make_object(test,'LuaInterface.Tests.TestClass')");
lua.DoString("test:setVal(3)");
lua.DoString("a=test.testval");
int a = (int)lua.GetNumber("a");
lua.DoString("luanet.free_object(test)");
TestOk(3 == a);
//Console.WriteLine("interface returned: "+a);
}
/// <summary>
/// Basic multiply method which expects 2 floats
/// </summary>
/// <param name="val"></param>
/// <param name="val2"></param>
/// <returns></returns>
private float _TestException(float val, float val2)
{
return val * val2;
}
public void TestEventException()
{
Init();
//Register a C# function
MethodInfo testException = this.GetType().GetMethod("_TestException", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance, null, new Type[] { typeof(float), typeof(float) }, null);
lua.RegisterFunction("Multiply", this, testException);
//create the lua event handler code for the entity
//includes the bad code!
lua.DoString("function OnClick(sender, eventArgs)\r\n" +
"--Multiply expects 2 floats, but instead receives 2 strings\r\n" +
"Multiply(asd, we)\r\n" +
"end");
//create the lua event handler code for the entity
//good code
//lua.DoString("function OnClick(sender, eventArgs)\r\n" +
// "--Multiply expects 2 floats\r\n" +
// "Multiply(2, 50)\r\n" +
// "end");
//Create the event handler script
lua.DoString("function SubscribeEntity(e)\r\ne.Clicked:Add(OnClick)\r\nend");
//Create the entity object
Entity entity = new Entity();
//Register the entity object with the event handler inside lua
LuaFunction lf = lua.GetFunction("SubscribeEntity");
lf.Call(new object[1] { entity });
try
{
//Cause the event to be fired
entity.Click();
Console.WriteLine("Test failed!!! Should have thrown an exception all the way out of Lua");
}
catch (LuaException)
{
Console.WriteLine("Event exception success");
}
}
public static int func(int x, int y)
{
return x + y;
}
public int funcInstance(int x, int y)
{
return x + y;
}
public void RegisterFunctionStressTest()
{
LuaFunction fc = null;
const int Count = 200; // it seems to work with 41
Init();
MyClass t = new MyClass();
for (int i = 1; i < Count - 1; ++i)
{
fc = lua.RegisterFunction("func" + i, t, typeof(MyClass).GetMethod("Func1"));
}
fc = lua.RegisterFunction("func" + (Count - 1), t, typeof(MyClass).GetMethod("Func1"));
lua.DoString("print(func1())");
}
/*
* Sample test script that shows some of the capabilities of
* LuaInterface
*/
public static void Main()
{
Console.WriteLine("Starting interpreter...");
LuaInterface l = new LuaInterface();
// Pause so we can connect with the debugger
// Thread.Sleep(30000);
Console.WriteLine("Reading test.lua file...");
l.DoFile("test.lua");
double width = l.GetNumber("width");
double height = l.GetNumber("height");
string message = l.GetString("message");
double color_r = l.GetNumber("color.r");
double color_g = l.GetNumber("color.g");
double color_b = l.GetNumber("color.b");
Console.WriteLine("Printing values of global variables width, height and message...");
Console.WriteLine("width: " + width);
Console.WriteLine("height: " + height);
Console.WriteLine("message: " + message);
Console.WriteLine("Printing values of the 'color' table's fields...");
Console.WriteLine("color.r: " + color_r);
Console.WriteLine("color.g: " + color_g);
Console.WriteLine("color.b: " + color_b);
width = 150;
Console.WriteLine("Changing width's value and calling Lua function print to show it...");
l["width"] = width;
l.GetFunction("print").Call(width);
message = "LuaNet Interface Test";
Console.WriteLine("Changing message's value and calling Lua function print to show it...");
l["message"] = message;
l.GetFunction("print").Call(message);
color_r = 30;
color_g = 10;
color_b = 200;
Console.WriteLine("Changing color's fields' values and calling Lua function print to show it...");
l["color.r"] = color_r;
l["color.g"] = color_g;
l["color.b"] = color_b;
l.DoString("print(color.r,color.g,color.b)");
Console.WriteLine("Printing values of the tree table's fields...");
double leaf1 = l.GetNumber("tree.branch1.leaf1");
string leaf2 = l.GetString("tree.branch1.leaf2");
string leaf3 = l.GetString("tree.leaf3");
Console.WriteLine("leaf1: " + leaf1);
Console.WriteLine("leaf2: " + leaf2);
Console.WriteLine("leaf3: " + leaf3);
leaf1 = 30; leaf2 = "new leaf2";
Console.WriteLine("Changing tree's fields' values and calling Lua function print to show it...");
l["tree.branch1.leaf1"] = leaf1; l["tree.branch1.leaf2"] = leaf2;
l.DoString("print(tree.branch1.leaf1,tree.branch1.leaf2)");
Console.WriteLine("Returning values from Lua with 'return'...");
object[] vals = l.DoString("return 2,3");
Console.WriteLine("Returned: " + vals[0] + " and " + vals[1]);
Console.WriteLine("Calling a Lua function that returns multiple values...");
object[] vals1 = l.GetFunction("func").Call(2, 3);
Console.WriteLine("Returned: " + vals1[0] + " and " + vals1[1]);
Console.WriteLine("Creating a table and filling it from C#...");
l.NewTable("tab");
l.NewTable("tab.tab");
l["tab.a"] = "a!";
l["tab.b"] = 5.5;
l["tab.tab.c"] = 6.5;
l.DoString("print(tab.a,tab.b,tab.tab.c)");
Console.WriteLine("Setting a table as another table's field...");
l["tab.a"] = l["tab.tab"];
l.DoString("print(tab.a.c)");
Console.WriteLine("Registering a C# static method and calling it from Lua...");
// Pause so we can connect with the debugger
// Thread.Sleep(30000);
l.RegisterFunction("func1", null, typeof(TestLuaInterface).GetMethod("func"));
vals1 = l.GetFunction("func1").Call(2, 3);
Console.WriteLine("Returned: " + vals1[0]);
TestLuaInterface obj = new TestLuaInterface();
Console.WriteLine("Registering a C# instance method and calling it from Lua...");
l.RegisterFunction("func2", obj, typeof(TestLuaInterface).GetMethod("funcInstance"));
vals1 = l.GetFunction("func2").Call(2, 3);
Console.WriteLine("Returned: " + vals1[0]);
Console.WriteLine("Testing throwing an exception...");
obj.ThrowUncaughtException();
Console.WriteLine("Testing catching an exception...");
obj.ThrowException();
Console.WriteLine("Testing inheriting a method from Lua...");
obj.LuaTableInheritedMethod();
Console.WriteLine("Testing overriding a C# method with Lua...");
obj.LuaTableOverridedMethod();
Console.WriteLine("Stress test RegisterFunction (based on a reported bug)..");
obj.RegisterFunctionStressTest();
Console.WriteLine("Test structures...");
obj.TestStructs();
Console.WriteLine("Test Nullable types...");
obj.TestNullable();
Console.WriteLine("Test functions...");
obj.TestFunctions();
Console.WriteLine("Test event exceptions...");
obj.TestEventException();
Console.Write("Press any key to continue...");
Console.ReadKey(true);
//Console.ReadLine();
}
}
}
| |
using System;
using UnityEngine;
using System.Collections.Generic;
namespace UMA
{
/// <summary>
/// Default UMA character generator.
/// </summary>
public abstract class UMAGeneratorBuiltin : UMAGeneratorBase
{
[NonSerialized]
protected UMAData umaData;
[NonSerialized]
protected List<UMAData> umaDirtyList = new List<UMAData>();
private LinkedList<UMAData> cleanUmas = new LinkedList<UMAData>();
private LinkedList<UMAData> dirtyUmas = new LinkedList<UMAData>();
private UMAGeneratorCoroutine activeGeneratorCoroutine;
public Transform textureMergePrefab;
public UMAMeshCombiner meshCombiner;
/// <summary>
///
/// </summary>
[Tooltip("Increase scale factor to decrease texture usage. A value of 1 means the textures will not be downsampled. Values greater than 1 will result in texture savings. The size of the texture is divided by this value.")]
public int InitialScaleFactor = 1;
/// <summary>
/// If true, generate in a single update.
/// </summary>
[Tooltip("Set Fast Generation to true to have the UMA Avatar generated in a single update. Otherwise, generation can span multiple frames.")]
public bool fastGeneration = true;
private int forceGarbageCollect;
/// <summary>
/// Number of character updates before triggering System garbage collect.
/// </summary>
[Tooltip("Number of character updates before triggering garbage collection.")]
public int garbageCollectionRate = 8;
private System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
[NonSerialized]
public long ElapsedTicks;
[NonSerialized]
public long DnaChanged;
[NonSerialized]
public long TextureChanged;
[NonSerialized]
public long SlotsChanged;
public virtual void OnEnable()
{
activeGeneratorCoroutine = null;
}
public virtual void Awake()
{
activeGeneratorCoroutine = null;
if (atlasResolution == 0)
atlasResolution = 256;
if (defaultOverlayAsset != null)
_defaultOverlayData = new OverlayData (defaultOverlayAsset);
if (!textureMerge)
{
Transform tempTextureMerger = Instantiate(textureMergePrefab, Vector3.zero, Quaternion.identity) as Transform;
textureMerge = tempTextureMerger.GetComponent("TextureMerge") as TextureMerge;
textureMerge.transform.parent = transform;
textureMerge.gameObject.SetActive(false);
}
//Garbage Collection hack
var mb = (System.GC.GetTotalMemory(false) / (1024 * 1024));
if (mb < 10)
{
byte[] data = new byte[10 * 1024 * 1024];
data[0] = 0;
data[10 * 1024 * 1024 - 1] = 0;
}
}
void Update()
{
if (CheckRenderTextures())
return; // if render textures needs rebuild we'll not do anything else
if (forceGarbageCollect > garbageCollectionRate)
{
GC.Collect();
forceGarbageCollect = 0;
if (garbageCollectionRate < 1) garbageCollectionRate = 1;
}
else
{
Work();
}
}
private bool CheckRenderTextures()
{
var rt = FindRenderTexture();
if (rt != null && !rt.IsCreated())
{
RebuildAllRenderTextures();
return true;
}
return false;
}
private RenderTexture FindRenderTexture()
{
var iteratorNode = cleanUmas.First;
while (iteratorNode != null)
{
var rt = iteratorNode.Value.GetFirstRenderTexture();
if (rt != null)
return rt;
iteratorNode = iteratorNode.Next;
}
return null;
}
public override void Work()
{
if (!IsIdle())
{
stopWatch.Reset();
stopWatch.Start();
OnDirtyUpdate();
ElapsedTicks += stopWatch.ElapsedTicks;
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
stopWatch.Stop();
UMATime.ReportTimeSpendtThisFrameTicks(stopWatch.ElapsedTicks);
}
}
#pragma warning disable 618
public void RebuildAllRenderTextures()
{
var activeUmaData = umaData;
var storedGeneratorCoroutine = activeGeneratorCoroutine;
var iteratorNode = cleanUmas.First;
while (iteratorNode != null)
{
RebuildRenderTexture(iteratorNode.Value);
iteratorNode = iteratorNode.Next;
}
umaData = activeUmaData;
activeGeneratorCoroutine = storedGeneratorCoroutine;
}
private void RebuildRenderTexture(UMAData data)
{
var rt = data.GetFirstRenderTexture();
if (rt != null && !rt.IsCreated())
{
umaData = data;
TextureProcessBaseCoroutine textureProcessCoroutine;
textureProcessCoroutine = new TextureProcessPROCoroutine();
textureProcessCoroutine.Prepare(data, this);
activeGeneratorCoroutine = new UMAGeneratorCoroutine();
activeGeneratorCoroutine.Prepare(this, umaData, textureProcessCoroutine, true, InitialScaleFactor);
while (!activeGeneratorCoroutine.Work()) ;
activeGeneratorCoroutine = null;
TextureChanged++;
}
}
public virtual bool HandleDirtyUpdate(UMAData data)
{
if (data == null)
return true;
if (umaData != data)
{
umaData = data;
if (!umaData.Validate())
return true;
if (meshCombiner != null)
{
meshCombiner.Preprocess(umaData);
}
umaData.FireCharacterBegunEvents();
}
if (umaData.isTextureDirty)
{
if (activeGeneratorCoroutine == null)
{
TextureProcessBaseCoroutine textureProcessCoroutine;
textureProcessCoroutine = new TextureProcessPROCoroutine();
textureProcessCoroutine.Prepare(data, this);
activeGeneratorCoroutine = new UMAGeneratorCoroutine();
activeGeneratorCoroutine.Prepare(this, umaData, textureProcessCoroutine, !umaData.isMeshDirty, InitialScaleFactor);
}
bool workDone = activeGeneratorCoroutine.Work();
if (workDone)
{
activeGeneratorCoroutine = null;
umaData.isTextureDirty = false;
umaData.isAtlasDirty |= umaData.isMeshDirty;
TextureChanged++;
}
if (!workDone || !fastGeneration || umaData.isMeshDirty)
return false;
}
if (umaData.isMeshDirty)
{
UpdateUMAMesh(umaData.isAtlasDirty);
umaData.isAtlasDirty = false;
umaData.isMeshDirty = false;
SlotsChanged++;
forceGarbageCollect++;
if (!fastGeneration)
return false;
}
if (umaData.isShapeDirty)
{
if (!umaData.skeleton.isUpdating)
{
umaData.skeleton.BeginSkeletonUpdate();
}
UpdateUMABody(umaData);
umaData.isShapeDirty = false;
DnaChanged++;
}
else if (umaData.skeleton.isUpdating)
{
umaData.skeleton.EndSkeletonUpdate();
}
UMAReady();
return true;
}
public virtual void OnDirtyUpdate()
{
try
{
if (HandleDirtyUpdate(umaDirtyList[0]))
{
umaDirtyList.RemoveAt(0);
umaData.MoveToList(cleanUmas);
umaData = null;
}
else if (fastGeneration && HandleDirtyUpdate(umaDirtyList[0]))
{
umaDirtyList.RemoveAt(0);
umaData.MoveToList(cleanUmas);
umaData = null;
}
}
catch (Exception ex)
{
UnityEngine.Debug.LogWarning("Exception in UMAGeneratorBuiltin.OnDirtyUpdate: " + ex);
}
}
private void UpdateUMAMesh(bool updatedAtlas)
{
if (meshCombiner != null)
{
meshCombiner.UpdateUMAMesh(updatedAtlas, umaData, atlasResolution);
}
else
{
Debug.LogError("UMAGenerator.UpdateUMAMesh, no MeshCombiner specified", gameObject);
}
}
/// <inheritdoc/>
public override void addDirtyUMA(UMAData umaToAdd)
{
if (umaToAdd)
{
umaDirtyList.Add(umaToAdd);
umaToAdd.MoveToList(dirtyUmas);
}
}
/// <inheritdoc/>
public override bool IsIdle()
{
return umaDirtyList.Count == 0;
}
/// <inheritdoc/>
public override int QueueSize()
{
return umaDirtyList.Count;
}
public virtual void UMAReady()
{
if (umaData)
{
umaData.Show();
umaData.FireUpdatedEvent(false);
umaData.FireCharacterCompletedEvents();
if (umaData.skeleton.boneCount > 300)
{
Debug.LogWarning("Skeleton has " + umaData.skeleton.boneCount + " bones, may be an error with slots!");
}
}
}
public virtual void UpdateUMABody(UMAData umaData)
{
if (umaData)
{
umaData.skeleton.ResetAll();
// Put the skeleton into TPose so rotations will be valid for generating avatar
umaData.GotoTPose();
umaData.ApplyDNA();
umaData.FireDNAAppliedEvents();
umaData.skeleton.EndSkeletonUpdate();
UpdateAvatar(umaData);
}
}
#pragma warning restore 618
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt01.opt01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt01.opt01;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic i)
{
if (i == 0)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
int? a = 0;
return p.Foo(a);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt01a.opt01a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt01a.opt01a;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
int ? i)
{
if (i == null)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt02.opt02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt02.opt02;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic i)
{
if (i == 2)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt02a.opt02a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt02a.opt02a;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
int ? i)
{
if (i == 2)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt03.opt03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt03.opt03;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
using System;
public class Parent
{
public int Foo(int j, [Optional]
dynamic i)
{
if (j == 2 && i == Type.Missing)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt03a.opt03a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt03a.opt03a;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(int? j, [Optional]
int ? i)
{
if (j == 2 && i == null)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt04.opt04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt04.opt04;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic j, [Optional]
dynamic i)
{
if (j == 2 && i == System.Type.Missing)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt04a.opt04a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt04a.opt04a;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
int ? j, [Optional]
int ? i)
{
if (j == 2 && i == null)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt07.opt07
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt07.opt07;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic j, dynamic i)
{
if (j == System.Type.Missing && i == 2)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: 2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt07a.opt07a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt07a.opt07a;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
int ? j, int? i)
{
if (j == null && i == 2)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: 2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt08.opt08
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt08.opt08;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic j, int i)
{
if (j == System.Type.Missing && i == 0)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: 0);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt08a.opt08a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt08a.opt08a;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
int ? j, int? i)
{
if (j == null && i == 0)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: 0);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt09.opt09
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt09.opt09;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
using System;
public class Parent
{
public int Foo(
[Optional]
dynamic i)
{
if (i == System.Type.Missing)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo();
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt09a.opt09a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt09a.opt09a;
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
using System;
public class Parent
{
public int Foo(
[Optional]
string i)
{
if (i == null)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
}
| |
// 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.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.Text;
using Moq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests
{
public partial class InteractiveWindowTests : IDisposable
{
#region Helpers
private InteractiveWindowTestHost _testHost;
private List<InteractiveWindow.State> _states;
private readonly TestClipboard _testClipboard;
private readonly TaskFactory _factory = new TaskFactory(TaskScheduler.Default);
public InteractiveWindowTests()
{
_states = new List<InteractiveWindow.State>();
_testHost = new InteractiveWindowTestHost(_states.Add);
_testClipboard = new TestClipboard();
((InteractiveWindow)Window).InteractiveWindowClipboard = _testClipboard;
}
void IDisposable.Dispose()
{
_testHost.Dispose();
}
private IInteractiveWindow Window => _testHost.Window;
private Task TaskRun(Action action)
{
return _factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
private static IEnumerable<IInteractiveWindowCommand> MockCommands(params string[] commandNames)
{
foreach (var name in commandNames)
{
var mock = new Mock<IInteractiveWindowCommand>();
mock.Setup(m => m.Names).Returns(new[] { name });
mock.Setup(m => m.Description).Returns(string.Format("Description of {0} command.", name));
yield return mock.Object;
}
}
private static ITextSnapshot MockSnapshot(string content)
{
var snapshotMock = new Mock<ITextSnapshot>();
snapshotMock.Setup(m => m[It.IsAny<int>()]).Returns<int>(index => content[index]);
snapshotMock.Setup(m => m.Length).Returns(content.Length);
snapshotMock.Setup(m => m.GetText()).Returns(content);
snapshotMock.Setup(m => m.GetText(It.IsAny<int>(), It.IsAny<int>())).Returns<int, int>((start, length) => content.Substring(start, length));
snapshotMock.Setup(m => m.GetText(It.IsAny<Span>())).Returns<Span>(span => content.Substring(span.Start, span.Length));
return snapshotMock.Object;
}
#endregion
[WpfFact]
public void InteractiveWindow__CommandParsing()
{
var commandList = MockCommands("foo", "bar", "bz", "command1").ToArray();
var commands = new Commands.Commands(null, "%", commandList);
AssertEx.Equal(commands.GetCommands(), commandList);
var cmdBar = commandList[1];
Assert.Equal("bar", cmdBar.Names.First());
Assert.Equal("%", commands.CommandPrefix);
commands.CommandPrefix = "#";
Assert.Equal("#", commands.CommandPrefix);
//// 111111
//// 0123456789012345
var s1 = MockSnapshot("#bar arg1 arg2 ");
SnapshotSpan prefixSpan, commandSpan, argsSpan;
IInteractiveWindowCommand cmd;
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 0)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 1)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 2)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(2, commandSpan.End);
Assert.Equal(2, argsSpan.Start);
Assert.Equal(2, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 3)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(3, commandSpan.End);
Assert.Equal(3, argsSpan.Start);
Assert.Equal(3, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 4)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(4, argsSpan.Start);
Assert.Equal(4, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 5)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(5, argsSpan.Start);
Assert.Equal(5, argsSpan.End);
cmd = commands.TryParseCommand(s1.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(5, argsSpan.Start);
Assert.Equal(14, argsSpan.End);
////
//// 0123456789
var s2 = MockSnapshot(" #bar ");
cmd = commands.TryParseCommand(s2.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(2, prefixSpan.Start);
Assert.Equal(3, prefixSpan.End);
Assert.Equal(3, commandSpan.Start);
Assert.Equal(6, commandSpan.End);
Assert.Equal(9, argsSpan.Start);
Assert.Equal(9, argsSpan.End);
//// 111111
//// 0123456789012345
var s3 = MockSnapshot(" # bar args");
cmd = commands.TryParseCommand(s3.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(2, prefixSpan.Start);
Assert.Equal(3, prefixSpan.End);
Assert.Equal(6, commandSpan.Start);
Assert.Equal(9, commandSpan.End);
Assert.Equal(11, argsSpan.Start);
Assert.Equal(15, argsSpan.End);
}
[WpfFact]
public void InteractiveWindow_GetCommands()
{
var interactiveCommands = new InteractiveCommandsFactory(null, null).CreateInteractiveCommands(
Window,
"#",
_testHost.ExportProvider.GetExports<IInteractiveWindowCommand>().Select(x => x.Value).ToArray());
var commands = interactiveCommands.GetCommands();
Assert.NotEmpty(commands);
Assert.Equal(2, commands.Where(n => n.Names.First() == "cls").Count());
Assert.Equal(2, commands.Where(n => n.Names.Last() == "clear").Count());
Assert.NotNull(commands.Where(n => n.Names.First() == "help").SingleOrDefault());
Assert.NotNull(commands.Where(n => n.Names.First() == "reset").SingleOrDefault());
}
[WorkItem(8121, "https://github.com/dotnet/roslyn/issues/8121")]
[WpfFact]
public void InteractiveWindow_GetHelpShortcutDescriptionss()
{
var interactiveCommands = new InteractiveCommandsFactory(null, null).CreateInteractiveCommands(
Window,
string.Empty,
Enumerable.Empty<IInteractiveWindowCommand>());
var noSmartUpDownExpected =
@" Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line.
Ctrl-Enter Within the current submission, evaluate the current submission.
Within a previous submission, append the previous submission to the current submission.
Shift-Enter Insert a new line.
Escape Clear the current submission.
Alt-UpArrow Replace the current submission with a previous submission.
Alt-DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards).
Ctrl-Alt-UpArrow Replace the current submission with a previous submission beginning with the same text.
Ctrl-Alt-DownArrow Replace the current submission with a subsequent submission beginning with the same text (after having previously navigated backwards).
Ctrl-K, Ctrl-Enter Paste the selection at the end of interactive buffer, leave caret at the end of input.
Ctrl-E, Ctrl-Enter Paste and execute the selection before any pending input in the interactive buffer.
Ctrl-A First press, select the submission containing the cursor. Second press, select all text in the window.
";
// By default, SmartUpDown option is not set
var descriptions = ((Commands.Commands)interactiveCommands).ShortcutDescriptions;
Assert.Equal(noSmartUpDownExpected, descriptions);
var withSmartUpDownExpected =
@" Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line.
Ctrl-Enter Within the current submission, evaluate the current submission.
Within a previous submission, append the previous submission to the current submission.
Shift-Enter Insert a new line.
Escape Clear the current submission.
Alt-UpArrow Replace the current submission with a previous submission.
Alt-DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards).
Ctrl-Alt-UpArrow Replace the current submission with a previous submission beginning with the same text.
Ctrl-Alt-DownArrow Replace the current submission with a subsequent submission beginning with the same text (after having previously navigated backwards).
Ctrl-K, Ctrl-Enter Paste the selection at the end of interactive buffer, leave caret at the end of input.
Ctrl-E, Ctrl-Enter Paste and execute the selection before any pending input in the interactive buffer.
Ctrl-A First press, select the submission containing the cursor. Second press, select all text in the window.
UpArrow At the end of the current submission, replace the current submission with a previous submission.
Elsewhere, move the cursor up one line.
DownArrow At the end of the current submission, replace the current submission with a subsequent submission (after having previously navigated backwards).
Elsewhere, move the cursor down one line.
";
// Set SmartUpDown option to true
Window.TextView.Options.SetOptionValue(InteractiveWindowOptions.SmartUpDown, true);
descriptions = ((Commands.Commands)interactiveCommands).ShortcutDescriptions;
Assert.Equal(withSmartUpDownExpected, descriptions);
}
[WorkItem(6625, "https://github.com/dotnet/roslyn/issues/6625")]
[WpfFact]
public void InteractiveWindow_DisplayCommandsHelp()
{
var commandList = MockCommands("foo").ToArray();
var commands = new Commands.Commands(null, "&", commandList);
Assert.Equal(new string[] { "&foo Description of foo command." }, commands.Help().ToArray());
}
[WorkItem(3970, "https://github.com/dotnet/roslyn/issues/3970")]
[WpfFact]
public async Task ResetStateTransitions()
{
await Window.Operations.ResetAsync().ConfigureAwait(true);
Assert.Equal(_states, new[]
{
InteractiveWindow.State.Initializing,
InteractiveWindow.State.WaitingForInput,
InteractiveWindow.State.Resetting,
InteractiveWindow.State.WaitingForInput,
});
}
[WpfFact]
public async Task DoubleInitialize()
{
try
{
await Window.InitializeAsync().ConfigureAwait(true);
Assert.True(false);
}
catch (InvalidOperationException)
{
}
}
[WpfFact]
public void AccessPropertiesOnUIThread()
{
foreach (var property in typeof(IInteractiveWindow).GetProperties())
{
Assert.Null(property.SetMethod);
property.GetMethod.Invoke(Window, Array.Empty<object>());
}
Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties());
}
[WpfFact]
public async Task AccessPropertiesOnNonUIThread()
{
foreach (var property in typeof(IInteractiveWindow).GetProperties())
{
Assert.Null(property.SetMethod);
await TaskRun(() => property.GetMethod.Invoke(Window, Array.Empty<object>())).ConfigureAwait(true);
}
Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties());
}
/// <remarks>
/// Confirm that we are, in fact, running on a non-UI thread.
/// </remarks>
[WpfFact]
public async Task NonUIThread()
{
await TaskRun(() => Assert.False(((InteractiveWindow)Window).OnUIThread())).ConfigureAwait(true);
}
[WpfFact]
public async Task CallCloseOnNonUIThread()
{
await TaskRun(() => Window.Close()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallInsertCodeOnNonUIThread()
{
await TaskRun(() => Window.InsertCode("1")).ConfigureAwait(true);
}
[WpfFact]
public async Task CallSubmitAsyncOnNonUIThread()
{
await TaskRun(() => Window.SubmitAsync(Array.Empty<string>()).GetAwaiter().GetResult()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallWriteOnNonUIThread()
{
await TaskRun(() => Window.WriteLine("1")).ConfigureAwait(true);
await TaskRun(() => Window.Write("1")).ConfigureAwait(true);
await TaskRun(() => Window.WriteErrorLine("1")).ConfigureAwait(true);
await TaskRun(() => Window.WriteError("1")).ConfigureAwait(true);
}
[WpfFact]
public async Task CallFlushOutputOnNonUIThread()
{
Window.Write("1"); // Something to flush.
await TaskRun(() => Window.FlushOutput()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallAddInputOnNonUIThread()
{
await TaskRun(() => Window.AddInput("1")).ConfigureAwait(true);
}
/// <remarks>
/// Call is blocking, so we can't write a simple non-failing test.
/// </remarks>
[WpfFact]
public void CallReadStandardInputOnUIThread()
{
Assert.Throws<InvalidOperationException>(() => Window.ReadStandardInput());
}
[WpfFact]
public async Task CallBackspaceOnNonUIThread()
{
Window.InsertCode("1"); // Something to backspace.
await TaskRun(() => Window.Operations.Backspace()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallBreakLineOnNonUIThread()
{
await TaskRun(() => Window.Operations.BreakLine()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallClearHistoryOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
await TaskRun(() => Window.Operations.ClearHistory()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallClearViewOnNonUIThread()
{
Window.InsertCode("1"); // Something to clear.
await TaskRun(() => Window.Operations.ClearView()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallHistoryNextOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
await TaskRun(() => Window.Operations.HistoryNext()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallHistoryPreviousOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
await TaskRun(() => Window.Operations.HistoryPrevious()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallHistorySearchNextOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
await TaskRun(() => Window.Operations.HistorySearchNext()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallHistorySearchPreviousOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
await TaskRun(() => Window.Operations.HistorySearchPrevious()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallHomeOnNonUIThread()
{
Window.Operations.BreakLine(); // Distinguish Home from End.
await TaskRun(() => Window.Operations.Home(true)).ConfigureAwait(true);
}
[WpfFact]
public async Task CallEndOnNonUIThread()
{
Window.Operations.BreakLine(); // Distinguish Home from End.
await TaskRun(() => Window.Operations.End(true)).ConfigureAwait(true);
}
[WpfFact]
public void ScrollToCursorOnHomeAndEndOnNonUIThread()
{
Window.InsertCode(new string('1', 512)); // a long input string
var textView = Window.TextView;
Window.Operations.Home(false);
Assert.True(textView.TextViewModel.IsPointInVisualBuffer(textView.Caret.Position.BufferPosition,
textView.Caret.Position.Affinity));
Window.Operations.End(false);
Assert.True(textView.TextViewModel.IsPointInVisualBuffer(textView.Caret.Position.BufferPosition,
textView.Caret.Position.Affinity));
}
[WpfFact]
public async Task CallSelectAllOnNonUIThread()
{
Window.InsertCode("1"); // Something to select.
await TaskRun(() => Window.Operations.SelectAll()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallPasteOnNonUIThread()
{
await TaskRun(() => Window.Operations.Paste()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallCutOnNonUIThread()
{
await TaskRun(() => Window.Operations.Cut()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallDeleteOnNonUIThread()
{
await TaskRun(() => Window.Operations.Delete()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallReturnOnNonUIThread()
{
await TaskRun(() => Window.Operations.Return()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallTrySubmitStandardInputOnNonUIThread()
{
await TaskRun(() => Window.Operations.TrySubmitStandardInput()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallResetAsyncOnNonUIThread()
{
await TaskRun(() => Window.Operations.ResetAsync()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallExecuteInputOnNonUIThread()
{
await TaskRun(() => Window.Operations.ExecuteInput()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallCancelOnNonUIThread()
{
await TaskRun(() => Window.Operations.Cancel()).ConfigureAwait(true);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[WpfFact]
public void TestIndentation1()
{
TestIndentation(indentSize: 1);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[WpfFact]
public void TestIndentation2()
{
TestIndentation(indentSize: 2);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[WpfFact]
public void TestIndentation3()
{
TestIndentation(indentSize: 3);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[WpfFact]
public void TestIndentation4()
{
TestIndentation(indentSize: 4);
}
private void TestIndentation(int indentSize)
{
const int promptWidth = 2;
_testHost.ExportProvider.GetExport<TestSmartIndentProvider>().Value.SmartIndent = new TestSmartIndent(
promptWidth,
promptWidth + indentSize,
promptWidth
);
AssertCaretVirtualPosition(0, promptWidth);
Window.InsertCode("{");
AssertCaretVirtualPosition(0, promptWidth + 1);
Window.Operations.BreakLine();
AssertCaretVirtualPosition(1, promptWidth + indentSize);
Window.InsertCode("Console.WriteLine();");
Window.Operations.BreakLine();
AssertCaretVirtualPosition(2, promptWidth);
Window.InsertCode("}");
AssertCaretVirtualPosition(2, promptWidth + 1);
}
private void AssertCaretVirtualPosition(int expectedLine, int expectedColumn)
{
ITextSnapshotLine actualLine;
int actualColumn;
Window.TextView.Caret.Position.VirtualBufferPosition.GetLineAndColumn(out actualLine, out actualColumn);
Assert.Equal(expectedLine, actualLine.LineNumber);
Assert.Equal(expectedColumn, actualColumn);
}
[WpfFact]
public void ResetCommandArgumentParsing_Success()
{
bool initialize;
Assert.True(ResetCommand.TryParseArguments("", out initialize));
Assert.True(initialize);
Assert.True(ResetCommand.TryParseArguments(" ", out initialize));
Assert.True(initialize);
Assert.True(ResetCommand.TryParseArguments("\r\n", out initialize));
Assert.True(initialize);
Assert.True(ResetCommand.TryParseArguments("noconfig", out initialize));
Assert.False(initialize);
Assert.True(ResetCommand.TryParseArguments(" noconfig ", out initialize));
Assert.False(initialize);
Assert.True(ResetCommand.TryParseArguments("\r\nnoconfig\r\n", out initialize));
Assert.False(initialize);
}
[WpfFact]
public void ResetCommandArgumentParsing_Failure()
{
bool initialize;
Assert.False(ResetCommand.TryParseArguments("a", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfi", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfig1", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfig 1", out initialize));
Assert.False(ResetCommand.TryParseArguments("1 noconfig", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfig\r\na", out initialize));
Assert.False(ResetCommand.TryParseArguments("nOcOnfIg", out initialize));
}
[WpfFact]
public void ResetCommandNoConfigClassification()
{
Assert.Empty(ResetCommand.GetNoConfigPositions(""));
Assert.Empty(ResetCommand.GetNoConfigPositions("a"));
Assert.Empty(ResetCommand.GetNoConfigPositions("noconfi"));
Assert.Empty(ResetCommand.GetNoConfigPositions("noconfig1"));
Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig"));
Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig1"));
Assert.Empty(ResetCommand.GetNoConfigPositions("nOcOnfIg"));
Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig"));
Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig "));
Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig"));
Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig "));
Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig"));
Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig\r\n"));
Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig\r\n"));
Assert.Equal(new[] { 6 }, ResetCommand.GetNoConfigPositions("error noconfig"));
Assert.Equal(new[] { 0, 9 }, ResetCommand.GetNoConfigPositions("noconfig noconfig"));
Assert.Equal(new[] { 0, 15 }, ResetCommand.GetNoConfigPositions("noconfig error noconfig"));
}
[WorkItem(4755, "https://github.com/dotnet/roslyn/issues/4755")]
[WpfFact]
public void ReformatBraces()
{
var buffer = Window.CurrentLanguageBuffer;
var snapshot = buffer.CurrentSnapshot;
Assert.Equal(0, snapshot.Length);
// Text before reformatting.
snapshot = ApplyChanges(
buffer,
new TextChange(0, 0, "{ {\r\n } }"));
// Text after reformatting.
Assert.Equal(9, snapshot.Length);
snapshot = ApplyChanges(
buffer,
new TextChange(1, 1, "\r\n "),
new TextChange(5, 1, " "),
new TextChange(7, 1, "\r\n"));
// Text from language buffer.
var actualText = snapshot.GetText();
Assert.Equal("{\r\n {\r\n }\r\n}", actualText);
// Text including prompts.
buffer = Window.TextView.TextBuffer;
snapshot = buffer.CurrentSnapshot;
actualText = snapshot.GetText();
Assert.Equal("> {\r\n> {\r\n> }\r\n> }", actualText);
// Prompts should be read-only.
var regions = buffer.GetReadOnlyExtents(new Span(0, snapshot.Length));
AssertEx.SetEqual(regions,
new Span(0, 2),
new Span(5, 2),
new Span(14, 2),
new Span(23, 2));
}
[WpfFact]
public async Task CancelMultiLineInput()
{
ApplyChanges(
Window.CurrentLanguageBuffer,
new TextChange(0, 0, "{\r\n {\r\n }\r\n}"));
// Text including prompts.
var buffer = Window.TextView.TextBuffer;
var snapshot = buffer.CurrentSnapshot;
Assert.Equal("> {\r\n> {\r\n> }\r\n> }", snapshot.GetText());
await TaskRun(() => Window.Operations.Cancel()).ConfigureAwait(true);
// Text after cancel.
snapshot = buffer.CurrentSnapshot;
Assert.Equal("> ", snapshot.GetText());
}
[WpfFact]
public void SelectAllInHeader()
{
Window.WriteLine("Header");
Window.FlushOutput();
var fullText = GetTextFromCurrentSnapshot();
Assert.Equal("Header\r\n> ", fullText);
Window.TextView.Caret.MoveTo(new SnapshotPoint(Window.TextView.TextBuffer.CurrentSnapshot, 1));
Window.Operations.SelectAll(); // Used to throw.
// Everything is selected.
Assert.Equal(new Span(0, fullText.Length), Window.TextView.Selection.SelectedSpans.Single().Span);
}
[WpfFact]
public async Task DeleteWithOutSelectionInReadOnlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("2");
var caret = Window.TextView.Caret;
// with empty selection, Delete() only handles caret movement,
// so we can only test caret location.
// Delete() with caret in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.Delete();
AssertCaretVirtualPosition(1, 1);
// Delete() with caret in active prompt, move caret to
// closest editable buffer
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(2, 0);
Window.Operations.Delete();
AssertCaretVirtualPosition(2, 2);
}
[WpfFact]
public async Task DeleteWithSelectionInReadonlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("23");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
// Delete() with selection in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
Window.Operations.Delete();
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
// Delete() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
Window.Operations.Delete();
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
// Delete() with selection overlaps with editable buffer,
// delete editable content and move caret to closest editable location
selection.Clear();
caret.MoveToPreviousCaretPosition();
start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 3);
selection.Select(start, end);
Window.Operations.Delete();
Assert.Equal("> 1\r\n1\r\n> 3", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
}
[WpfFact]
public async Task BackspaceWithOutSelectionInReadOnlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
var caret = Window.TextView.Caret;
// Backspace() with caret in readonly area, no-op
Window.Operations.Home(false);
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.Backspace();
AssertCaretVirtualPosition(1, 1);
Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot());
// Backspace() with caret in 2nd active prompt, move caret to
// closest editable buffer then delete previous character (breakline)
caret.MoveToNextCaretPosition();
Window.Operations.End(false);
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(3, 1);
Window.Operations.Backspace();
AssertCaretVirtualPosition(2, 7);
Assert.Equal("> 1\r\n1\r\n> int x;", GetTextFromCurrentSnapshot());
}
[WpfFact]
public async Task BackspaceWithSelectionInReadonlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
// Backspace() with selection in readonly area, no-op
Window.Operations.Home(false);
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
Window.Operations.Backspace();
Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot());
// Backspace() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
Window.Operations.Backspace();
Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot());
// Backspace() with selection overlaps with editable buffer
selection.Clear();
Window.Operations.End(false);
start = caret.Position.VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(3, 2);
selection.Select(start, end);
Window.Operations.Backspace();
Assert.Equal("> 1\r\n1\r\n> int x;", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 7);
}
[WpfFact]
public async Task ReturnWithOutSelectionInReadOnlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
var caret = Window.TextView.Caret;
// Return() with caret in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.Return();
AssertCaretVirtualPosition(1, 1);
// Return() with caret in active prompt, move caret to
// closest editable buffer first
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(2, 0);
Window.Operations.Return();
AssertCaretVirtualPosition(3, 2);
}
[WpfFact]
public async Task ReturnWithSelectionInReadonlyArea()
{
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("23");
// Return() with selection in readonly area, no-op
// > 1
// |1 |
// > 23
MoveCaretToPreviousPosition(5);
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
Window.Operations.Return();
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
// Return() with selection in active prompt
// > 1
// 1
// |> |23
selection.Clear();
MoveCaretToNextPosition(1);
var start = caret.Position.VirtualBufferPosition;
MoveCaretToNextPosition(2);
var end = caret.Position.VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
Window.Operations.Return();
Assert.Equal("> 1\r\n1\r\n> \r\n> 23", GetTextFromCurrentSnapshot());
// Return() with selection overlaps with editable buffer,
// > 1
// 1
// >
// |> 2|3
selection.Clear();
MoveCaretToPreviousPosition(2);
start = caret.Position.VirtualBufferPosition;
MoveCaretToNextPosition(3);
end = caret.Position.VirtualBufferPosition;
AssertCaretVirtualPosition(3, 3);
selection.Select(start, end);
Window.Operations.Return();
Assert.Equal("> 1\r\n1\r\n> \r\n> \r\n> 3", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(4, 2);
}
[WpfFact]
public async Task DeleteLineWithOutSelection()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
var caret = Window.TextView.Caret;
// DeleteLine with caret in readonly area
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(1, 1);
// DeleteLine with caret in active prompt
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
for (int i = 0; i < 11; ++i)
{
caret.MoveToPreviousCaretPosition();
}
AssertCaretVirtualPosition(2, 0);
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ;", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
// DeleteLine with caret in editable area
caret.MoveToNextCaretPosition();
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
}
[WpfFact]
public async Task DeleteLineWithSelection()
{
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
await Submit(
@"1",
@"1
").ConfigureAwait(true);
// DeleteLine with selection in readonly area
// > 1
// |1 |
// >
MoveCaretToPreviousPosition(3);
Window.Operations.SelectAll();
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
// DeleteLine with selection in active prompt
// > 1
// 1
// |>| int x
// > ;
selection.Clear();
MoveCaretToNextPosition(3);
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
MoveCaretToPreviousPosition(11);
var start = caret.Position.VirtualBufferPosition;
MoveCaretToNextPosition(1);
var end = caret.Position.VirtualBufferPosition;
selection.Select(start, end);
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ;", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
Assert.True(selection.IsEmpty);
// DeleteLine with selection in editable area
// > 1
// 1
// > int |x|;
Window.InsertCode("int x");
MoveCaretToPreviousPosition(1);
start = caret.Position.VirtualBufferPosition;
MoveCaretToNextPosition(1);
end = caret.Position.VirtualBufferPosition;
selection.Select(start, end);
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
Assert.True(selection.IsEmpty);
// DeleteLine with selection spans all areas, no-op
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
Window.Operations.SelectAll();
Window.Operations.SelectAll();
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot());
}
[WpfFact]
public async Task SubmitAsyncNone()
{
await SubmitAsync().ConfigureAwait(true);
}
[WpfFact]
public async Task SubmitAsyncSingle()
{
await SubmitAsync("1").ConfigureAwait(true);
}
[WorkItem(5964, "https://github.com/dotnet/roslyn/issues/5964")]
[WpfFact]
public async Task SubmitAsyncMultiple()
{
await SubmitAsync("1", "2", "1 + 2").ConfigureAwait(true);
}
private async Task SubmitAsync(params string[] submissions)
{
var actualSubmissions = new List<string>();
var evaluator = _testHost.Evaluator;
EventHandler<string> onExecute = (_, s) => actualSubmissions.Add(s.TrimEnd());
evaluator.OnExecute += onExecute;
await TaskRun(() => Window.SubmitAsync(submissions)).ConfigureAwait(true);
evaluator.OnExecute -= onExecute;
AssertEx.Equal(submissions, actualSubmissions);
}
[WorkItem(6397, "https://github.com/dotnet/roslyn/issues/6397")]
[WpfFact]
public void TypeCharWithUndoRedo()
{
Window.Operations.TypeChar('a');
Window.Operations.TypeChar('b');
Window.Operations.TypeChar('c');
Assert.Equal("> abc", GetTextFromCurrentSnapshot());
// undo/redo for consecutive TypeChar's shold be a single action
((InteractiveWindow)Window).Undo_TestOnly(1);
Assert.Equal("> ", GetTextFromCurrentSnapshot());
((InteractiveWindow)Window).Redo_TestOnly(1);
Assert.Equal("> abc", GetTextFromCurrentSnapshot());
// make a stream selection as follows:
// > |aaa|
Window.Operations.SelectAll();
Window.Operations.TypeChar('1');
Window.Operations.TypeChar('2');
Window.Operations.TypeChar('3');
Assert.Equal("> 123", GetTextFromCurrentSnapshot());
((InteractiveWindow)Window).Undo_TestOnly(1);
Assert.Equal("> abc", GetTextFromCurrentSnapshot());
((InteractiveWindow)Window).Undo_TestOnly(1);
Assert.Equal("> ", GetTextFromCurrentSnapshot());
// type in active prompt
MoveCaretToPreviousPosition(2);
Window.Operations.TypeChar('x');
Window.Operations.TypeChar('y');
Window.Operations.TypeChar('z');
Assert.Equal("> xyz", GetTextFromCurrentSnapshot());
}
// TODO (https://github.com/dotnet/roslyn/issues/7976): delete this
[WorkItem(7976, "https://github.com/dotnet/roslyn/issues/7976")]
[WpfFact]
public void Workaround7976()
{
Thread.Sleep(TimeSpan.FromSeconds(10));
}
private string GetTextFromCurrentSnapshot()
{
return Window.TextView.TextBuffer.CurrentSnapshot.GetText();
}
private async Task Submit(string submission, string output)
{
await TaskRun(() => Window.SubmitAsync(new[] { submission })).ConfigureAwait(true);
// TestInteractiveEngine.ExecuteCodeAsync() simply returns
// success rather than executing the submission, so add the
// expected output to the output buffer.
var buffer = Window.OutputBuffer;
using (var edit = buffer.CreateEdit())
{
edit.Replace(buffer.CurrentSnapshot.Length, 0, output);
edit.Apply();
}
}
private struct TextChange
{
internal readonly int Start;
internal readonly int Length;
internal readonly string Text;
internal TextChange(int start, int length, string text)
{
Start = start;
Length = length;
Text = text;
}
}
private static ITextSnapshot ApplyChanges(ITextBuffer buffer, params TextChange[] changes)
{
using (var edit = buffer.CreateEdit())
{
foreach (var change in changes)
{
edit.Replace(change.Start, change.Length, change.Text);
}
return edit.Apply();
}
}
}
internal static class OperationsExtensions
{
internal static void Copy(this IInteractiveWindowOperations operations)
{
((IInteractiveWindowOperations2)operations).Copy();
}
internal static void CopyCode(this IInteractiveWindowOperations operations)
{
((IInteractiveWindowOperations2)operations).CopyCode();
}
internal static void DeleteLine(this IInteractiveWindowOperations operations)
{
((IInteractiveWindowOperations2)operations).DeleteLine();
}
internal static void CutLine(this IInteractiveWindowOperations operations)
{
((IInteractiveWindowOperations2)operations).CutLine();
}
internal static void TypeChar(this IInteractiveWindowOperations operations, char typedChar)
{
((IInteractiveWindowOperations2)operations).TypeChar(typedChar);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Menu.cs" company="sgmunn">
// (c) sgmunn 2012
//
// 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>
// --------------------------------------------------------------------------------------------------------------------
//
// Created by Levey on 11/30/11.
// Copyright (c) 2011 Levey & Other Contributors. All rights reserved.
// https://github.com/levey/AwesomeMenu
namespace MonoKit.UI.AwesomeMenu
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.CoreAnimation;
using MonoTouch.CoreGraphics;
using MonoTouch.ObjCRuntime;
using MonoTouch.UIKit;
public enum LayoutMode
{
Radial,
Vertical,
Horizontal
}
public sealed class Menu : UIView
{
private readonly List<MenuItem> menuItems;
private int flag;
private NSTimer timer;
private MenuItem addButton;
private bool isAnimating;
private bool expanded;
private PointF startPoint;
public Menu(RectangleF frame) : base(frame)
{
this.BackgroundColor = UIColor.Clear;
this.Mode = LayoutMode.Radial;
this.NearRadius = MenuDefaults.NearRadius;
this.EndRadius = MenuDefaults.EndRadius;
this.FarRadius = MenuDefaults.FarRadius;
this.TimeOffset = MenuDefaults.TimeOffset;
this.RotateAngle = MenuDefaults.RotateAngle;
this.MenuWholeAngle = (float)MenuDefaults.MenuWholeAngle;
this.StartPoint = new PointF(MenuDefaults.StartPointX, MenuDefaults.StartPointY);
this.ExpandRotation = (float)MenuDefaults.ExpandRotation;
this.CloseRotation = (float)MenuDefaults.CloseRotation;
this.menuItems = new List<MenuItem>();
this.addButton = new MenuItem(UIImage.FromFile("Images/bg-addbutton.png"),
UIImage.FromFile("Images/bg-addbutton-highlighted.png"),
UIImage.FromFile("Images/icon-plus.png"),
UIImage.FromFile("Images/icon-plus-highlighted.png"));
this.addButton.Center = this.StartPoint;
this.addButton.Touched += (sender, e) => this.Expanded = !this.Expanded;
this.AddSubview(this.addButton);
}
public Menu(RectangleF frame, IEnumerable<MenuItem> menus) : base(frame)
{
this.BackgroundColor = UIColor.Clear;
this.Mode = LayoutMode.Radial;
this.NearRadius = MenuDefaults.NearRadius;
this.EndRadius = MenuDefaults.EndRadius;
this.FarRadius = MenuDefaults.FarRadius;
this.TimeOffset = MenuDefaults.TimeOffset;
this.RotateAngle = MenuDefaults.RotateAngle;
this.MenuWholeAngle = (float)MenuDefaults.MenuWholeAngle;
this.StartPoint = new PointF(MenuDefaults.StartPointX, MenuDefaults.StartPointY);
this.ExpandRotation = (float)MenuDefaults.ExpandRotation;
this.CloseRotation = (float)MenuDefaults.CloseRotation;
this.menuItems = new List<MenuItem>(menus);
this.addButton = new MenuItem(UIImage.FromFile("Images/bg-addbutton.png"),
UIImage.FromFile("Images/bg-addbutton-highlighted.png"),
UIImage.FromFile("Images/icon-plus.png"),
UIImage.FromFile("Images/icon-plus-highlighted.png"));
this.addButton.Touched += (sender, e) => this.Expanded = !this.Expanded;
this.addButton.Center = this.StartPoint;
this.AddSubview(this.addButton);
}
public event EventHandler<MenuItemSelectedEventArgs> MenuItemSelected;
public List<MenuItem> MenuItems
{
get
{
return this.menuItems;
}
}
public PointF StartPoint
{
get
{
return this.startPoint;
}
set
{
this.startPoint = value;
if (this.addButton != null)
{
this.addButton.Center = value;
}
}
}
public LayoutMode Mode { get; set; }
public double TimeOffset { get; set; }
public float NearRadius { get; set; }
public float EndRadius { get; set; }
public float FarRadius { get; set; }
public float RotateAngle { get; set; }
public float MenuWholeAngle { get; set; }
public float ExpandRotation { get; set; }
public float CloseRotation { get; set; }
public float RadiusStep { get; set; }
public UIImage Image
{
get
{
return this.addButton.Image;
}
set
{
this.addButton.Image = value;
}
}
public UIImage HighlightedImage
{
get
{
return this.addButton.HighlightedImage;
}
set
{
this.addButton.HighlightedImage = value;
}
}
public UIImage ContentImage
{
get
{
return this.addButton.ContentImageView.Image;
}
set
{
this.addButton.ContentImageView.Image = value;
}
}
public UIImage HighlightedContentImage
{
get
{
return this.addButton.ContentImageView.HighlightedImage;
}
set
{
this.addButton.ContentImageView.HighlightedImage = value;
}
}
public bool Expanded
{
get
{
return this.expanded;
}
set
{
if (value)
{
this.SetMenu();
}
this.expanded = value;
float angle = this.Expanded ? - (float)(Math.PI / 4) : 0.0f;
UIView.Animate(0.2f, () =>
{
this.addButton.Transform = CGAffineTransform.MakeRotation(angle);
});
if (this.timer == null)
{
this.flag = this.Expanded ? 0 : (this.MenuItems.Count - 1);
Selector action = this.Expanded ? new Selector("expand:") : new Selector("close:");
this.timer = new NSTimer(NSDate.Now, this.TimeOffset, this, action, null, true);
NSRunLoop.Current.AddTimer(this.timer, NSRunLoopMode.Common);
this.isAnimating = true;
}
}
}
public void SetMenuItems(IEnumerable<MenuItem> items)
{
this.MenuItems.Clear();
this.MenuItems.AddRange(items);
foreach (MenuItem view in this.Subviews.OfType<MenuItem>().ToList())
{
if (view.MenuTag >= 1000)
{
view.RemoveFromSuperview();
}
}
}
public override bool PointInside(PointF point, UIEvent @event)
{
if (this.isAnimating)
{
return false;
}
if (this.Expanded)
{
return true;
}
else
{
var result = this.addButton.Frame.Contains(point);
return result;
}
}
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
this.Expanded = !this.Expanded;
}
public override void TouchesMoved(NSSet touches, UIEvent evt)
{
base.TouchesMoved(touches, evt);
}
public override void TouchesCancelled(NSSet touches, UIEvent evt)
{
base.TouchesCancelled(touches, evt);
}
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
base.TouchesEnded(touches, evt);
}
private static PointF RotateCGPointAroundCenter(PointF point, PointF center, float angle)
{
CGAffineTransform translation = CGAffineTransform.MakeTranslation(center.X, center.Y);
CGAffineTransform rotation = CGAffineTransform.MakeRotation(angle);
var inverted = CGAffineTransform.CGAffineTransformInvert(translation);
CGAffineTransform transformGroup = inverted * rotation * translation;
return transformGroup.TransformPoint(point);
}
private void AwesomeMenuItemTouchesEnd(MenuItem item)
{
if (item == this.addButton)
{
return;
}
CAAnimationGroup blowup = this.BlowupAnimationAtPoint(item.Center);
item.Layer.AddAnimation(blowup, "blowup");
item.Center = item.StartPoint;
for (int i = 0; i < this.MenuItems.Count; i++)
{
MenuItem otherItem = this.MenuItems[i];
CAAnimationGroup shrink = this.ShrinkAnimationAtPoint(otherItem.Center);
if (otherItem.MenuTag == item.MenuTag)
{
continue;
}
otherItem.Layer.AddAnimation(shrink, "shrink");
otherItem.Center = otherItem.StartPoint;
}
this.expanded = false;
float angle = this.Expanded ? - (float)Math.PI / 4 : 0.0f;
UIView.Animate(0.2f, () =>
{
this.addButton.Transform = CGAffineTransform.MakeRotation(angle);
});
var handler = this.MenuItemSelected;
if (handler != null)
{
handler(this, new MenuItemSelectedEventArgs(item.MenuTag - 1000));
}
}
private MenuItem GetByTag(int menuTag)
{
return this.menuItems.Where(x => x.MenuTag == menuTag).First();
}
[Export("expand:")]
private void Expand()
{
if (flag == this.MenuItems.Count)
{
this.isAnimating = false;
this.timer.Invalidate();
this.timer = null;
return;
}
int tag = 1000 + this.flag;
MenuItem item = this.GetByTag(tag);
item.Selected -= this.ItemSelected;
item.Selected += this.ItemSelected;
var rotateAnimation = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath("transform.rotation.z");
rotateAnimation.Values = new NSNumber[] {this.ExpandRotation, 0.0f};
rotateAnimation.Duration = 0.5f;
rotateAnimation.KeyTimes = new NSNumber[] {0.3f, 0.4f};
var positionAnimation = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath("position");
positionAnimation.Duration = 0.5f;
var path = new CGPath();
path.MoveToPoint(item.StartPoint.X, item.StartPoint.Y);
path.AddLineToPoint(item.FarPoint.X, item.FarPoint.Y);
path.AddLineToPoint(item.NearPoint.X, item.NearPoint.Y);
path.AddLineToPoint(item.EndPoint.X, item.EndPoint.Y);
positionAnimation.Path = path;
var animationGroup = new CAAnimationGroup();
animationGroup.Animations = new[] {positionAnimation, rotateAnimation};
animationGroup.Duration = 0.5f;
animationGroup.FillMode = CAFillMode.Forwards;
animationGroup.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseIn);
item.Layer.AddAnimation(animationGroup, "Expand");
item.Alpha = 1f;
item.Center = item.EndPoint;
this.flag++;
}
private void SetMenu()
{
int count = this.MenuItems.Count;
float step = 0f;
for (int i = 0; i < count; i++)
{
MenuItem item = this.MenuItems[i];
item.MenuTag = 1000 + i;
item.StartPoint = this.StartPoint;
switch (this.Mode)
{
case LayoutMode.Radial:
this.LayoutMenuItemRadial(item, i, count, step);
break;
case LayoutMode.Horizontal:
this.LayoutMenuItemHorizontal(item, i, count, step);
break;
case LayoutMode.Vertical:
this.LayoutMenuItemVertical(item, i, count, step);
break;
}
item.Center = item.StartPoint;
this.InsertSubviewBelow(item, this.addButton);
step += this.RadiusStep;
}
}
private void LayoutMenuItemRadial(MenuItem item, int index, int count, float step)
{
var endPoint = new PointF(this.StartPoint.X + (this.EndRadius - step) * (float)Math.Sin(index * this.MenuWholeAngle / count),
this.StartPoint.Y - (this.EndRadius - step) * (float)Math.Cos(index * this.MenuWholeAngle / count));
item.EndPoint = RotateCGPointAroundCenter(endPoint, this.StartPoint, this.RotateAngle);
var nearPoint = new PointF(this.StartPoint.X + (this.NearRadius - step) * (float)Math.Sin(index * this.MenuWholeAngle / count),
this.StartPoint.Y - (this.NearRadius - step) * (float)Math.Cos(index * this.MenuWholeAngle / count));
item.NearPoint = RotateCGPointAroundCenter(nearPoint, this.StartPoint, this.RotateAngle);
var farPoint = new PointF(this.StartPoint.X + (this.FarRadius - step) * (float)Math.Sin(index * this.MenuWholeAngle / count),
this.StartPoint.Y - (this.FarRadius - step) * (float)Math.Cos(index * this.MenuWholeAngle / count));
item.FarPoint = RotateCGPointAroundCenter(farPoint, this.StartPoint, this.RotateAngle);
}
private void LayoutMenuItemHorizontal(MenuItem item, int index, int count, float step)
{
var endPoint = new PointF(this.StartPoint.X + (this.EndRadius - step), this.StartPoint.Y);
item.EndPoint = RotateCGPointAroundCenter(endPoint, this.StartPoint, this.RotateAngle);
var nearPoint = new PointF(this.StartPoint.X + (this.NearRadius - step), this.StartPoint.Y);
item.NearPoint = RotateCGPointAroundCenter(nearPoint, this.StartPoint, this.RotateAngle);
var farPoint = new PointF(this.StartPoint.X + (this.FarRadius - step), this.StartPoint.Y);
item.FarPoint = RotateCGPointAroundCenter(farPoint, this.StartPoint, this.RotateAngle);
}
private void LayoutMenuItemVertical(MenuItem item, int index, int count, float step)
{
var endPoint = new PointF(this.StartPoint.X, this.StartPoint.Y + (this.EndRadius - step));
item.EndPoint = RotateCGPointAroundCenter(endPoint, this.StartPoint, this.RotateAngle);
var nearPoint = new PointF(this.StartPoint.X, this.StartPoint.Y + (this.NearRadius - step));
item.NearPoint = RotateCGPointAroundCenter(nearPoint, this.StartPoint, this.RotateAngle);
var farPoint = new PointF(this.StartPoint.X, this.StartPoint.Y + (this.FarRadius - step));
item.FarPoint = RotateCGPointAroundCenter(farPoint, this.StartPoint, this.RotateAngle);
}
[Export("close:")]
private void Close()
{
if (flag == -1)
{
this.isAnimating = false;
this.timer.Invalidate();
this.timer = null;
return;
}
int tag = 1000 + flag;
MenuItem item = this.GetByTag(tag);
item.Selected -= this.ItemSelected;
var rotateAnimation = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath("transform.rotation.z");
rotateAnimation.Values = new NSNumber[] {0f, this.CloseRotation, 0f};
rotateAnimation.Duration = 0.5f;
rotateAnimation.KeyTimes = new NSNumber[] {0f, 0.4f, 0.5f};
var positionAnimation = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath("position");
positionAnimation.Duration = 0.5f;
var path = new CGPath();
path.MoveToPoint(item.EndPoint.X, item.EndPoint.Y);
path.AddLineToPoint(item.FarPoint.X, item.FarPoint.Y);
path.AddLineToPoint(item.StartPoint.X, item.StartPoint.Y);
positionAnimation.Path = path;
var alphaAnimation = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath("opacity");
alphaAnimation.Values = new NSNumber[] {1f, 1f, 0f};
alphaAnimation.Duration = 0.5f;
alphaAnimation.KeyTimes = new NSNumber[] {0f, 0.8f, 1f};
var animationGroup = new CAAnimationGroup();
animationGroup.Animations = new[] { positionAnimation, rotateAnimation, alphaAnimation };
animationGroup.Duration = 0.5f;
animationGroup.FillMode = CAFillMode.Forwards;
animationGroup.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseIn);
item.Layer.AddAnimation(animationGroup, "Close");
item.Alpha = 0f;
item.Center = item.StartPoint;
flag--;
}
private void ItemSelected(object sender, EventArgs args)
{
this.AwesomeMenuItemTouchesEnd(sender as MenuItem);
}
// todo: animate opacity to match expand / close
private CAAnimationGroup BlowupAnimationAtPoint(PointF p)
{
var positionAnimation = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath("position");
positionAnimation.Values = new NSObject[] { NSValue.FromPointF(p)};
positionAnimation.KeyTimes = new NSNumber[] {0.3f};
var scaleAnimation = CABasicAnimation.FromKeyPath("transform");
scaleAnimation.To = NSValue.FromCATransform3D(CATransform3D.MakeScale(3, 3, 1));
var opacityAnimation = CABasicAnimation.FromKeyPath("opacity");
opacityAnimation.To = NSNumber.FromFloat(0);
var animationGroup = new CAAnimationGroup();
animationGroup.Animations = new CAAnimation[] { positionAnimation, scaleAnimation, opacityAnimation };
animationGroup.Duration = 0.3f;
animationGroup.FillMode = CAFillMode.Forwards;
return animationGroup;
}
private CAAnimationGroup ShrinkAnimationAtPoint(PointF p)
{
var positionAnimation = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath("position");
positionAnimation.Values = new NSObject[] { NSValue.FromPointF(p)};
positionAnimation.KeyTimes = new NSNumber[] {0.3f};
var scaleAnimation = CABasicAnimation.FromKeyPath("transform");
scaleAnimation.To = NSValue.FromCATransform3D(CATransform3D.MakeScale(0.01f, 0.01f, 1f));
var opacityAnimation = CABasicAnimation.FromKeyPath("opacity");
opacityAnimation.To = NSNumber.FromFloat(0);
var animationGroup = new CAAnimationGroup();
animationGroup.Animations = new CAAnimation[] { positionAnimation, scaleAnimation, opacityAnimation };
animationGroup.Duration = 0.3f;
animationGroup.FillMode = CAFillMode.Forwards;
return animationGroup;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition
{
using Microsoft.Azure.Management.ContainerRegistry.Fluent;
using Microsoft.Azure.Management.ContainerRegistry.Fluent.Models;
using System.Collections.Generic;
/// <summary>
/// The stage of the container registry task definition for TaskRunRequests that allows the user to specify overriding values
/// and whether archiving is enabled or not.
/// </summary>
public interface IRegistryTaskRunRequest :
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestExecutable
{
/// <summary>
/// The function that specifies archiving will or will not be enabled.
/// </summary>
/// <param name="enabled">Whether archive will be enabled.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRegistryTaskRunRequest WithArchiveEnabled(bool enabled);
/// <summary>
/// The function that specifies whether a single value will be overridden and what it will be overridden by.
/// </summary>
/// <param name="name">The name of the value to be overridden.</param>
/// <param name="overridingValue">The OverridingValue specifying what the value will be overridden with.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRegistryTaskRunRequest WithOverridingValue(string name, OverridingValue overridingValue);
/// <summary>
/// The function that specifies whether there are any values that will be overridden and what they will be overridden by.
/// </summary>
/// <param name="overridingValues">A map that has the name of the value to be overridden as the key and the value is an OverridingValue.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRegistryTaskRunRequest WithOverridingValues(IDictionary<string,Microsoft.Azure.Management.ContainerRegistry.Fluent.OverridingValue> overridingValues);
}
/// <summary>
/// The stage of the container registry task run that specifies the AgentConfiguration for the container registry task run.
/// </summary>
public interface IAgentConfiguration
{
/// <summary>
/// The function that specifies the count of the CPU.
/// </summary>
/// <param name="count">The CPU count.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestExecutable WithCpuCount(int count);
}
/// <summary>
/// The stage of the container registry task run definition which contains all the minimum required inputs for the resource to be executed
/// if the task run request type is either file, encoded, or Docker, but also allows for any other optional settings to be specified.
/// </summary>
public interface IRunRequestExecutableWithSourceLocation :
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IAgentConfiguration,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestExecutable
{
/// <summary>
/// The function that specifies the location of the source control.
/// </summary>
/// <param name="location">The location of the source control.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestExecutableWithSourceLocation WithSourceLocation(string location);
/// <summary>
/// The function that specifies the timeout.
/// </summary>
/// <param name="timeout">The time the timeout lasts.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestExecutableWithSourceLocation WithTimeout(int timeout);
}
/// <summary>
/// The stage of the definition that specifies the task run request type.
/// </summary>
public interface IRunRequestType
{
/// <summary>
/// The function that specifies the task run request type will be a Docker task.
/// </summary>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryDockerTaskRunRequest.Definition.IBlank WithDockerTaskRunRequest();
/// <summary>
/// The function that specifies the task run request type will be an encoded task.
/// </summary>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryEncodedTaskRunRequest.Definition.IBlank WithEncodedTaskRunRequest();
/// <summary>
/// The function that specifies the task run request type will be a file task.
/// </summary>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryFileTaskRunRequest.Definition.IBlank WithFileTaskRunRequest();
}
/// <summary>
/// The stage of the container registry task definition that specifies the platform for the container registry task run.
/// </summary>
public interface IPlatform
{
/// <summary>
/// The function that specifies the platform will have a Linux OS.
/// </summary>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestType WithLinux();
/// <summary>
/// The function that specifies the platform will have a Linux OS with Architecture architecture.
/// </summary>
/// <param name="architecture">The architecture the platform will have.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestType WithLinux(Architecture architecture);
/// <summary>
/// The function that specifies the platform will have a Linux OS with Architecture architecture and Variant variant.
/// </summary>
/// <param name="architecture">The architecture the platform will have.</param>
/// <param name="variant">The variant the platform will have.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestType WithLinux(Architecture architecture, Variant variant);
/// <summary>
/// The function that specifies the platform properties of the registry task run.
/// </summary>
/// <param name="platformProperties">The properties of the platform.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestType WithPlatform(PlatformProperties platformProperties);
/// <summary>
/// The function that specifies the platform will have a Windows OS.
/// </summary>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestType WithWindows();
/// <summary>
/// The function that specifies the platform will have a Windows OS with Architecture architecture.
/// </summary>
/// <param name="architecture">The architecture the platform will have.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestType WithWindows(Architecture architecture);
/// <summary>
/// The function that specifies the platform will have a Windows OS with Architecture architecture and Variant variant.
/// </summary>
/// <param name="architecture">The architecture the platform will have.</param>
/// <param name="variant">The variant the platform will have.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestType WithWindows(Architecture architecture, Variant variant);
}
/// <summary>
/// Container interface for all the definitions related to a RegistryTaskRun.
/// </summary>
public interface IDefinition :
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IBlankFromRegistry,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IBlankFromRuns,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IPlatform,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IPlatformAltTaskRunRequest,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRegistryTaskRunRequest,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestType,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestExecutableWithSourceLocation,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestExecutable
{
}
/// <summary>
/// The stage of the definition in the case of using a TaskRunRequest which contains
/// all the minimum required inputs for the resource to be executed, but also allows for any other optional settings
/// to be specified.
/// </summary>
public interface IRunRequestExecutable :
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IArchive,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IExecutable<Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryTaskRun>
{
}
/// <summary>
/// The stage of the container registry task run definition that specifies the enabling and disabling of archiving.
/// </summary>
public interface IArchive
{
/// <summary>
/// The function that specifies archiving is enabled or disabled.
/// </summary>
/// <param name="enabled">Whether archiving is enabled or not.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRunRequestExecutable WithArchiveEnabled(bool enabled);
}
/// <summary>
/// The stage of the container registry task run definition that allows to specify the task run is going to be run
/// with a TaskRunRequest.
/// </summary>
public interface IPlatformAltTaskRunRequest :
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IPlatform
{
/// <summary>
/// The function that specifies the name of the existing task to run.
/// </summary>
/// <param name="taskName">The name of the created task to pass into the task run request.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IRegistryTaskRunRequest WithTaskRunRequest(string taskName);
}
/// <summary>
/// The first stage of a a RegistryTaskRun definition if originating from a call on a registry.
/// </summary>
public interface IBlankFromRegistry :
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IPlatformAltTaskRunRequest
{
}
/// <summary>
/// The first stage of a RegistryTaskRun definition if definition is originating from a call on an existing RegistryTaskRun.
/// </summary>
public interface IBlankFromRuns
{
/// <summary>
/// The function that specifies the registry this task run is called on.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group of the registry.</param>
/// <param name="registryName">The name of the registry.</param>
/// <return>The next stage of the container registry task run definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTaskRun.Definition.IPlatformAltTaskRunRequest WithExistingRegistry(string resourceGroupName, string registryName);
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace XmlNotepad {
public class NoBorderTabControlEventArgs {
NoBorderTabPage page;
public NoBorderTabControlEventArgs(NoBorderTabPage page){
this.page = page;
}
public NoBorderTabPage TabPage {
get { return this.page; }
}
}
public delegate void NoBorderTabControlEventHandler(object sender, NoBorderTabControlEventArgs args);
public class NoBorderTabControl : UserControl {
TabControl tabs;
TabPageCollection pages;
public delegate void PageEventHandler(object sender, PageEventArgs args);
public event NoBorderTabControlEventHandler Selected;
public NoBorderTabControl() {
pages = new TabPageCollection();
tabs = new TabControl();
this.Controls.Add(tabs);
pages.PageAdded += new PageEventHandler(OnPageAdded);
pages.PageRemoved += new PageEventHandler(OnPageRemoved);
tabs.SelectedIndexChanged += new EventHandler(OnTabsSelectedIndexChanged);
}
public int SelectedIndex {
get { return tabs.SelectedIndex; }
set { tabs.SelectedIndex = value; }
}
public NoBorderTabPage SelectedTab {
get {
return (NoBorderTabPage)pages[tabs.SelectedIndex];
}
set {
foreach (NoBorderTabPage p in pages) {
if (p == value) {
this.tabs.SelectedTab = p.Page;
break;
}
}
}
}
void OnTabsSelectedIndexChanged(object sender, EventArgs e) {
TabPage page = tabs.SelectedTab;
foreach (NoBorderTabPage p in pages) {
if (p.Page == page) {
if (Selected != null) {
Selected(this, new NoBorderTabControlEventArgs(p));
}
this.Controls.SetChildIndex(p, 0); // put it on top!
break;
}
}
}
void OnPageRemoved(object sender, PageEventArgs e) {
NoBorderTabPage page = e.Page;
tabs.TabPages.Remove(page.Page);
if (this.Controls.Contains(page)) {
this.Controls.Remove(page);
}
}
void OnPageAdded(object sender, PageEventArgs e) {
NoBorderTabPage page = e.Page;
if (e.Index >= tabs.TabPages.Count) {
tabs.TabPages.Add(page.Page);
} else {
tabs.TabPages.Insert(e.Index, page.Page);
}
if (!this.Controls.Contains(page)) {
this.Controls.Add(page);
this.Controls.SetChildIndex(page, this.TabPages.IndexOf(page));
}
}
protected override void OnControlAdded(ControlEventArgs e) {
base.OnControlAdded(e);
NoBorderTabPage page = e.Control as NoBorderTabPage;
if (page != null && !tabs.TabPages.Contains(page.Page)) {
pages.Add(page);
}
}
protected override void OnControlRemoved(ControlEventArgs e) {
base.OnControlRemoved(e);
NoBorderTabPage page = e.Control as NoBorderTabPage;
if (page != null && tabs.TabPages.Contains(page.Page)) {
pages.Remove(page);
}
}
protected override void OnLayout(LayoutEventArgs e) {
tabs.MinimumSize = new Size(10, 10);
Size s = tabs.GetPreferredSize(new Size(this.Width, 20));
int height = tabs.ItemSize.Height + tabs.Padding.Y;
tabs.Bounds = new Rectangle(0, 0, this.Width, height);
foreach (NoBorderTabPage p in this.TabPages) {
p.Bounds = new Rectangle(0, height, this.Width, this.Height - height);
}
}
public TabPageCollection TabPages {
get {
return pages;
}
}
public class PageEventArgs : EventArgs {
int index;
NoBorderTabPage page;
public PageEventArgs(NoBorderTabPage page, int index) {
this.page = page;
this.index = index;
}
public NoBorderTabPage Page {
get {
return this.page;
}
set {
this.page = value;
}
}
public int Index {
get {
return this.index;
}
set {
this.index = value;
}
}
}
public class TabPageCollection : IList {
ArrayList list = new ArrayList();
public event PageEventHandler PageAdded;
public event PageEventHandler PageRemoved;
void OnPageAdded(NoBorderTabPage page, int index) {
PageAdded(this, new PageEventArgs(page, index));
}
void OnPageRemoved(NoBorderTabPage page) {
PageRemoved(this, new PageEventArgs(page, 0));
}
#region IList Members
public int Add(object value) {
int index = list.Count;
list.Add(value);
OnPageAdded((NoBorderTabPage)value, index);
return index;
}
public void Clear() {
foreach (NoBorderTabPage page in list) {
OnPageRemoved(page);
}
list.Clear();
}
public bool Contains(object value) {
return list.Contains(value);
}
public int IndexOf(object value) {
return list.IndexOf(value);
}
public void Insert(int index, object value) {
list.Insert(index, value);
OnPageAdded((NoBorderTabPage)value, index);
}
public bool IsFixedSize {
get { return false; }
}
public bool IsReadOnly {
get { return false; }
}
public void Remove(object value) {
OnPageRemoved((NoBorderTabPage)value);
list.Remove(value);
}
public void RemoveAt(int index) {
if (index >= 0 && index < list.Count) {
OnPageRemoved((NoBorderTabPage)list[index]);
list.RemoveAt(index);
}
}
public object this[int index] {
get {
return list[index];
}
set {
RemoveAt(index);
if (value != null) {
Insert(index, value);
}
}
}
#endregion
#region ICollection Members
public void CopyTo(Array array, int index) {
list.CopyTo(array, index);
}
public int Count {
get { return list.Count; }
}
public bool IsSynchronized {
get { return list.IsSynchronized; }
}
public object SyncRoot {
get { return list.SyncRoot; }
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator() {
return list.GetEnumerator();
}
#endregion
}
}
public class NoBorderTabPage : Panel {
TabPage page = new TabPage();
public NoBorderTabPage() {
}
[System.ComponentModel.Browsable(false)]
internal TabPage Page {
get { return this.page; }
}
public override string Text {
get {
return this.page.Text;
}
set {
this.page.Text = value;
}
}
}
}
| |
//
// server.cs: Web Server that uses ASP.NET hosting
//
// Authors:
// Sergey Zhukov
// Brian Nickel (brian.nickel@gmail.com)
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
// (C) Copyright 2004 Novell, Inc. (http://www.novell.com)
// (C) Copyright 2007 Brian Nickel
// (C) Copyright 2013 Sergey Zhukov
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Web.Hosting;
using Mono.WebServer;
//using System.Configuration;
using Mono.Unix;
using Mono.Unix.Native;
using HyperFastCgi.Helpers.Logging;
using HyperFastCgi.Helpers.Sockets;
using System.Threading;
using HyperFastCgi.ApplicationServers;
using HyperFastCgi.Transports;
using HyperFastCgi.Listeners;
using System.Net.Sockets;
using System.Collections.Generic;
using HyperFastCgi.Configuration;
using HyperFastCgi.Interfaces;
using HyperFastCgi.Helpers;
namespace HyperFastCgi
{
public class MainClass
{
static void ShowVersion ()
{
Assembly assembly = Assembly.GetExecutingAssembly ();
string version = assembly.GetName ().Version.ToString ();
object att;
att = assembly.GetCustomAttributes (typeof(AssemblyCopyrightAttribute), false) [0];
string copyright = ((AssemblyCopyrightAttribute)att).Copyright;
att = assembly.GetCustomAttributes (typeof(AssemblyDescriptionAttribute), false) [0];
string description = ((AssemblyDescriptionAttribute)att).Description;
Console.WriteLine ("{0} {1}\n(c) {2}\n{3}",
Path.GetFileName (assembly.Location), version,
copyright, description);
}
static void ShowHelp ()
{
string name = Path.GetFileName (Assembly.GetExecutingAssembly ().Location);
ShowVersion ();
Console.WriteLine ();
Console.WriteLine ("Usage is:\n");
Console.WriteLine (" {0} [...]", name);
Console.WriteLine ();
configmanager.PrintHelp ();
}
private static ConfigurationManager configmanager;
public static int Main (string[] args)
{
// Load the configuration file stored in the
// executable's resources.
configmanager = new ConfigurationManager (
typeof(MainClass).Assembly,
"ConfigurationManager.xml");
configmanager.LoadCommandLineArgs (args);
// Show the help and exit.
if ((bool)configmanager ["help"] || (bool)configmanager ["?"]) {
ShowHelp ();
return 0;
}
// Show the version and exit.
if ((bool)configmanager ["version"]) {
ShowVersion ();
return 0;
}
string config = (string) configmanager ["config"];
if (config == null) {
Console.WriteLine ("You must pass /config=<filename> option. See 'help' for more info");
return 1;
}
try {
string config_file = (string)configmanager ["configfile"];
if (config_file != null) configmanager.LoadXmlConfig (config_file);
} catch (ApplicationException e) {
Console.WriteLine (e.Message);
return 1;
} catch (System.Xml.XmlException e) {
Console.WriteLine ("Error reading XML configuration: {0}", e.Message);
return 1;
}
try {
string log_level = (string) configmanager ["loglevels"];
if (log_level != null)
Logger.Level = (LogLevel) Enum.Parse (typeof(LogLevel), log_level);
} catch {
Console.WriteLine ("Failed to parse log levels.");
Console.WriteLine ("Using default levels: {0}", Logger.Level);
}
// Enable console logging during Main ().
Logger.WriteToConsole = true;
try {
string log_file = (string) configmanager ["logfile"];
if (log_file != null) Logger.Open (log_file);
} catch (Exception e) {
Logger.Write (LogLevel.Error, "Error opening log file: {0}", e.Message);
Logger.Write (LogLevel.Error,"Events will not be logged.");
}
Logger.Write (LogLevel.Debug,
Assembly.GetExecutingAssembly ().GetName ().Name);
bool auto_map = false; //(bool) configmanager ["automappaths"];
string applications = (string) configmanager ["applications"];
string app_config_file;
string app_config_dir;
try {
app_config_file = (string) configmanager ["appconfigfile"];
app_config_dir = (string) configmanager ["appconfigdir"];
} catch (ApplicationException e) {
Logger.Write (LogLevel.Error, e.Message);
return 1;
}
// server.MaxConnections = (ushort)
// configmanager ["maxconns"];
// server.MaxRequests = (ushort)
// configmanager ["maxreqs"];
// server.MultiplexConnections = (bool)
// configmanager ["multiplex"];
// Logger.Write (LogLevel.Debug, "Max connections: {0}",
// server.MaxConnections);
// Logger.Write (LogLevel.Debug, "Max requests: {0}",
// server.MaxRequests);
// Logger.Write (LogLevel.Debug, "Multiplex connections: {0}",
// server.MultiplexConnections);
bool stoppable = (bool)configmanager ["stoppable"];
Logger.WriteToConsole = (bool)configmanager ["printlog"];
List<ConfigInfo> serverConfigs = ConfigUtils.GetConfigsFromFile (config, "server", typeof(AppServerConfig));
if (serverConfigs.Count != 1) {
if (serverConfigs.Count == 0) {
Console.WriteLine ("Could not find <server> node in file '{0}'", config);
} else {
Console.WriteLine ("Only one server is supported currently. Please remove redudant <server> node from file '{0}'", config);
}
return 1;
}
IApplicationServer srv = (IApplicationServer)Activator.CreateInstance (serverConfigs [0].Type);
srv.Configure (serverConfigs [0].Config);
List<ConfigInfo> listenerConfigs = ConfigUtils.GetConfigsFromFile (config, "listener", typeof(ListenerConfig));
if (listenerConfigs.Count != 1) {
if (listenerConfigs.Count == 0) {
Console.WriteLine ("Could not find <listener> node in file '{0}'", config);
} else {
Console.WriteLine ("Only one listener is supported currently. Please remove redudant <listener> node from file '{0}'", config);
}
return 1;
}
List<ConfigInfo> hostConfigs = ConfigUtils.GetConfigsFromFile (config, "apphost", typeof(AppHostConfig));
if (hostConfigs.Count == 0) {
Console.WriteLine ("Can't find <apphost> node in file '{0}'", config);
return 1;
}
IWebListener listener = (IWebListener)Activator.CreateInstance(listenerConfigs[0].Type);
listener.Configure (listenerConfigs[0].Config, srv,
listenerConfigs[0].ListenerTransport != null? listenerConfigs[0].ListenerTransport.Type: null,
listenerConfigs[0].ListenerTransport != null? listenerConfigs[0].ListenerTransport.Config: null,
listenerConfigs[0].AppHostTransport != null? listenerConfigs[0].AppHostTransport.Type: null,
listenerConfigs[0].AppHostTransport != null? listenerConfigs[0].AppHostTransport.Config: null
);
//read web applications. It must be done after server creation
//because server can change the root path to web apps
List<WebAppConfig> webapps = new List<WebAppConfig> ();
if (config != null) {
webapps.AddRange (ConfigUtils.GetApplicationsFromConfigFile (config));
}
if (applications != null) {
webapps.AddRange (ConfigUtils.GetApplicationsFromCommandLine (applications));
}
if (app_config_file != null) {
webapps.AddRange (ConfigUtils.GetApplicationsFromConfigFile (app_config_file));
}
if (app_config_dir != null) {
webapps.AddRange (ConfigUtils.GetApplicationsFromConfigDirectory (app_config_dir));
}
if (webapps.Count==0 && !auto_map) {
Logger.Write (LogLevel.Error,
"There are no applications defined, and path mapping is disabled.");
Logger.Write (LogLevel.Error,
"Define an application using /applications, /appconfigfile, /appconfigdir");
/*
Logger.Write (LogLevel.Error,
"or by enabling application mapping with /automappaths=True.");
*/
return 1;
}
foreach (WebAppConfig appConfig in webapps) {
srv.CreateApplicationHost (
hostConfigs[0].Type, hostConfigs[0].Config,
appConfig,
listener.Transport, listener.AppHostTransportType,
listenerConfigs[0].AppHostTransport != null ? listenerConfigs[0].AppHostTransport.Config: null);
}
if (listener.Listen () != 0) {
Logger.Write (LogLevel.Error, "Could not start server");
return 1;
}
configmanager = null;
if (stoppable) {
Console.WriteLine ("Hit Return to stop the server.");
Console.ReadLine ();
} else {
UnixSignal[] signals = new UnixSignal[] {
new UnixSignal (Signum.SIGINT),
new UnixSignal (Signum.SIGTERM),
};
// Wait for a unix signal
for (bool exit = false; !exit;) {
int id = UnixSignal.WaitAny (signals);
if (id >= 0 && id < signals.Length) {
if (signals [id].IsSet)
exit = true;
}
}
}
listener.Shutdown ();
return 0;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using i64 = System.Int64;
using u8 = System.Byte;
using u32 = System.UInt32;
using Pgno = System.UInt32;
namespace Community.CsharpSqlite
{
using sqlite3_int64 = System.Int64;
public partial class Sqlite3
{
/*
** 2008 December 3
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This module implements an object we call a "RowSet".
**
** The RowSet object is a collection of rowids. Rowids
** are inserted into the RowSet in an arbitrary order. Inserts
** can be intermixed with tests to see if a given rowid has been
** previously inserted into the RowSet.
**
** After all inserts are finished, it is possible to extract the
** elements of the RowSet in sorted order. Once this extraction
** process has started, no new elements may be inserted.
**
** Hence, the primitive operations for a RowSet are:
**
** CREATE
** INSERT
** TEST
** SMALLEST
** DESTROY
**
** The CREATE and DESTROY primitives are the constructor and destructor,
** obviously. The INSERT primitive adds a new element to the RowSet.
** TEST checks to see if an element is already in the RowSet. SMALLEST
** extracts the least value from the RowSet.
**
** The INSERT primitive might allocate additional memory. Memory is
** allocated in chunks so most INSERTs do no allocation. There is an
** upper bound on the size of allocated memory. No memory is freed
** until DESTROY.
**
** The TEST primitive includes a "batch" number. The TEST primitive
** will only see elements that were inserted before the last change
** in the batch number. In other words, if an INSERT occurs between
** two TESTs where the TESTs have the same batch nubmer, then the
** value added by the INSERT will not be visible to the second TEST.
** The initial batch number is zero, so if the very first TEST contains
** a non-zero batch number, it will see all prior INSERTs.
**
** No INSERTs may occurs after a SMALLEST. An assertion will fail if
** that is attempted.
**
** The cost of an INSERT is roughly constant. (Sometime new memory
** has to be allocated on an INSERT.) The cost of a TEST with a new
** batch number is O(NlogN) where N is the number of elements in the RowSet.
** The cost of a TEST using the same batch number is O(logN). The cost
** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
** primitives are constant time. The cost of DESTROY is O(N).
**
** There is an added cost of O(N) when switching between TEST and
** SMALLEST primitives.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** Target size for allocation chunks.
*/
//#define ROWSET_ALLOCATION_SIZE 1024
const int ROWSET_ALLOCATION_SIZE = 1024;
/*
** The number of rowset entries per allocation chunk.
*/
//#define ROWSET_ENTRY_PER_CHUNK \
// ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
const int ROWSET_ENTRY_PER_CHUNK = 63;
/*
** Each entry in a RowSet is an instance of the following object.
*/
public class RowSetEntry
{
public i64 v; /* ROWID value for this entry */
public RowSetEntry pRight; /* Right subtree (larger entries) or list */
public RowSetEntry pLeft; /* Left subtree (smaller entries) */
};
/*
** Index entries are allocated in large chunks (instances of the
** following structure) to reduce memory allocation overhead. The
** chunks are kept on a linked list so that they can be deallocated
** when the RowSet is destroyed.
*/
public class RowSetChunk
{
public RowSetChunk pNextChunk; /* Next chunk on list of them all */
public RowSetEntry[] aEntry = new RowSetEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
};
/*
** A RowSet in an instance of the following structure.
**
** A typedef of this structure if found in sqliteInt.h.
*/
public class RowSet
{
public RowSetChunk pChunk; /* List of all chunk allocations */
public sqlite3 db; /* The database connection */
public RowSetEntry pEntry; /* /* List of entries using pRight */
public RowSetEntry pLast; /* Last entry on the pEntry list */
public RowSetEntry[] pFresh; /* Source of new entry objects */
public RowSetEntry pTree; /* Binary tree of entries */
public int nFresh; /* Number of objects on pFresh */
public bool isSorted; /* True if pEntry is sorted */
public u8 iBatch; /* Current insert batch */
public RowSet( sqlite3 db, int N )
{
this.pChunk = null;
this.db = db;
this.pEntry = null;
this.pLast = null;
this.pFresh = new RowSetEntry[N];
this.pTree = null;
this.nFresh = N;
this.isSorted = true;
this.iBatch = 0;
}
};
/*
** Turn bulk memory into a RowSet object. N bytes of memory
** are available at pSpace. The db pointer is used as a memory context
** for any subsequent allocations that need to occur.
** Return a pointer to the new RowSet object.
**
** It must be the case that N is sufficient to make a Rowset. If not
** an assertion fault occurs.
**
** If N is larger than the minimum, use the surplus as an initial
** allocation of entries available to be filled.
*/
static RowSet sqlite3RowSetInit( sqlite3 db, object pSpace, u32 N )
{
RowSet p = new RowSet( db, (int)N );
//Debug.Assert(N >= ROUND8(sizeof(*p)) );
// p = pSpace;
// p.pChunk = 0;
// p.db = db;
// p.pEntry = 0;
// p.pLast = 0;
// p.pTree = 0;
// p.pFresh =(struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
// p.nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
// p.isSorted = 1;
// p.iBatch = 0;
return p;
}
/*
** Deallocate all chunks from a RowSet. This frees all memory that
** the RowSet has allocated over its lifetime. This routine is
** the destructor for the RowSet.
*/
static void sqlite3RowSetClear( RowSet p )
{
RowSetChunk pChunk, pNextChunk;
for ( pChunk = p.pChunk; pChunk != null; pChunk = pNextChunk )
{
pNextChunk = pChunk.pNextChunk;
sqlite3DbFree( p.db, ref pChunk );
}
p.pChunk = null;
p.nFresh = 0;
p.pEntry = null;
p.pLast = null;
p.pTree = null;
p.isSorted = true;
}
/*
** Insert a new value into a RowSet.
**
** The mallocFailed flag of the database connection is set if a
** memory allocation fails.
*/
static void sqlite3RowSetInsert( RowSet p, i64 rowid )
{
RowSetEntry pEntry; /* The new entry */
RowSetEntry pLast; /* The last prior entry */
Debug.Assert( p != null );
if ( p.nFresh == 0 )
{
RowSetChunk pNew;
pNew = new RowSetChunk();//sqlite3DbMallocRaw(p.db, sizeof(*pNew));
if ( pNew == null )
{
return;
}
pNew.pNextChunk = p.pChunk;
p.pChunk = pNew;
p.pFresh = pNew.aEntry;
p.nFresh = ROWSET_ENTRY_PER_CHUNK;
}
p.pFresh[p.pFresh.Length - p.nFresh] = new RowSetEntry();
pEntry = p.pFresh[p.pFresh.Length - p.nFresh];
p.nFresh--;
pEntry.v = rowid;
pEntry.pRight = null;
pLast = p.pLast;
if ( pLast != null )
{
if ( p.isSorted && rowid <= pLast.v )
{
p.isSorted = false;
}
pLast.pRight = pEntry;
}
else
{
Debug.Assert( p.pEntry == null );/* Fires if INSERT after SMALLEST */
p.pEntry = pEntry;
}
p.pLast = pEntry;
}
/*
** Merge two lists of RowSetEntry objects. Remove duplicates.
**
** The input lists are connected via pRight pointers and are
** assumed to each already be in sorted order.
*/
static RowSetEntry rowSetMerge(
RowSetEntry pA, /* First sorted list to be merged */
RowSetEntry pB /* Second sorted list to be merged */
)
{
RowSetEntry head = new RowSetEntry();
RowSetEntry pTail;
pTail = head;
while ( pA != null && pB != null )
{
Debug.Assert( pA.pRight == null || pA.v <= pA.pRight.v );
Debug.Assert( pB.pRight == null || pB.v <= pB.pRight.v );
if ( pA.v < pB.v )
{
pTail.pRight = pA;
pA = pA.pRight;
pTail = pTail.pRight;
}
else if ( pB.v < pA.v )
{
pTail.pRight = pB;
pB = pB.pRight;
pTail = pTail.pRight;
}
else
{
pA = pA.pRight;
}
}
if ( pA != null )
{
Debug.Assert( pA.pRight == null || pA.v <= pA.pRight.v );
pTail.pRight = pA;
}
else
{
Debug.Assert( pB == null || pB.pRight == null || pB.v <= pB.pRight.v );
pTail.pRight = pB;
}
return head.pRight;
}
/*
** Sort all elements on the pEntry list of the RowSet into ascending order.
*/
static void rowSetSort( RowSet p )
{
u32 i;
RowSetEntry pEntry;
RowSetEntry[] aBucket = new RowSetEntry[40];
Debug.Assert( p.isSorted == false );
//memset(aBucket, 0, sizeof(aBucket));
while ( p.pEntry != null )
{
pEntry = p.pEntry;
p.pEntry = pEntry.pRight;
pEntry.pRight = null;
for ( i = 0; aBucket[i] != null; i++ )
{
pEntry = rowSetMerge( aBucket[i], pEntry );
aBucket[i] = null;
}
aBucket[i] = pEntry;
}
pEntry = null;
for ( i = 0; i < aBucket.Length; i++ )//sizeof(aBucket)/sizeof(aBucket[0])
{
pEntry = rowSetMerge( pEntry, aBucket[i] );
}
p.pEntry = pEntry;
p.pLast = null;
p.isSorted = true;
}
/*
** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
** Convert this tree into a linked list connected by the pRight pointers
** and return pointers to the first and last elements of the new list.
*/
static void rowSetTreeToList(
RowSetEntry pIn, /* Root of the input tree */
ref RowSetEntry ppFirst, /* Write head of the output list here */
ref RowSetEntry ppLast /* Write tail of the output list here */
)
{
Debug.Assert( pIn != null );
if ( pIn.pLeft != null )
{
RowSetEntry p = new RowSetEntry();
rowSetTreeToList( pIn.pLeft, ref ppFirst, ref p );
p.pRight = pIn;
}
else
{
ppFirst = pIn;
}
if ( pIn.pRight != null )
{
rowSetTreeToList( pIn.pRight, ref pIn.pRight, ref ppLast );
}
else
{
ppLast = pIn;
}
Debug.Assert( ( ppLast ).pRight == null );
}
/*
** Convert a sorted list of elements (connected by pRight) into a binary
** tree with depth of iDepth. A depth of 1 means the tree contains a single
** node taken from the head of *ppList. A depth of 2 means a tree with
** three nodes. And so forth.
**
** Use as many entries from the input list as required and update the
** *ppList to point to the unused elements of the list. If the input
** list contains too few elements, then construct an incomplete tree
** and leave *ppList set to NULL.
**
** Return a pointer to the root of the constructed binary tree.
*/
static RowSetEntry rowSetNDeepTree(
ref RowSetEntry ppList,
int iDepth
)
{
RowSetEntry p; /* Root of the new tree */
RowSetEntry pLeft; /* Left subtree */
if ( ppList == null )
{
return null;
}
if ( iDepth == 1 )
{
p = ppList;
ppList = p.pRight;
p.pLeft = p.pRight = null;
return p;
}
pLeft = rowSetNDeepTree( ref ppList, iDepth - 1 );
p = ppList;
if ( p == null )
{
return pLeft;
}
p.pLeft = pLeft;
ppList = p.pRight;
p.pRight = rowSetNDeepTree( ref ppList, iDepth - 1 );
return p;
}
/*
** Convert a sorted list of elements into a binary tree. Make the tree
** as deep as it needs to be in order to contain the entire list.
*/
static RowSetEntry rowSetListToTree( RowSetEntry pList )
{
int iDepth; /* Depth of the tree so far */
RowSetEntry p; /* Current tree root */
RowSetEntry pLeft; /* Left subtree */
Debug.Assert( pList != null );
p = pList;
pList = p.pRight;
p.pLeft = p.pRight = null;
for ( iDepth = 1; pList != null; iDepth++ )
{
pLeft = p;
p = pList;
pList = p.pRight;
p.pLeft = pLeft;
p.pRight = rowSetNDeepTree( ref pList, iDepth );
}
return p;
}
/*
** Convert the list in p.pEntry into a sorted list if it is not
** sorted already. If there is a binary tree on p.pTree, then
** convert it into a list too and merge it into the p.pEntry list.
*/
static void rowSetToList( RowSet p )
{
if ( !p.isSorted )
{
rowSetSort( p );
}
if ( p.pTree != null )
{
RowSetEntry pHead = new RowSetEntry();
RowSetEntry pTail = new RowSetEntry();
rowSetTreeToList( p.pTree, ref pHead, ref pTail );
p.pTree = null;
p.pEntry = rowSetMerge( p.pEntry, pHead );
}
}
/*
** Extract the smallest element from the RowSet.
** Write the element into *pRowid. Return 1 on success. Return
** 0 if the RowSet is already empty.
**
** After this routine has been called, the sqlite3RowSetInsert()
** routine may not be called again.
*/
static int sqlite3RowSetNext( RowSet p, ref i64 pRowid )
{
rowSetToList( p );
if ( p.pEntry != null )
{
pRowid = p.pEntry.v;
p.pEntry = p.pEntry.pRight;
if ( p.pEntry == null )
{
sqlite3RowSetClear( p );
}
return 1;
}
else
{
return 0;
}
}
/*
** Check to see if element iRowid was inserted into the the rowset as
** part of any insert batch prior to iBatch. Return 1 or 0.
*/
static int sqlite3RowSetTest( RowSet pRowSet, u8 iBatch, sqlite3_int64 iRowid )
{
RowSetEntry p;
if ( iBatch != pRowSet.iBatch )
{
if ( pRowSet.pEntry != null )
{
rowSetToList( pRowSet );
pRowSet.pTree = rowSetListToTree( pRowSet.pEntry );
pRowSet.pEntry = null;
pRowSet.pLast = null;
}
pRowSet.iBatch = iBatch;
}
p = pRowSet.pTree;
while ( p != null )
{
if ( p.v < iRowid )
{
p = p.pRight;
}
else if ( p.v > iRowid )
{
p = p.pLeft;
}
else
{
return 1;
}
}
return 0;
}
}
}
| |
/*
* Copyright (c) 2006-2008, openmetaverse.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.
* - Neither the name of the openmetaverse.org 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 OpenMetaverse.Packets;
using OpenMetaverse.Interfaces;
using OpenMetaverse.Messages.Linden;
using System.Collections.Generic;
namespace OpenMetaverse
{
/// <summary>Describes tasks returned in LandStatReply</summary>
public class EstateTask
{
public Vector3 Position;
public float Score;
public float MonoScore;
public UUID TaskID;
public uint TaskLocalID;
public string TaskName;
public string OwnerName;
}
/// <summary>
/// Estate level administration and utilities
/// </summary>
public class EstateTools
{
private GridClient Client;
/// <summary>Textures for each of the four terrain height levels</summary>
public GroundTextureSettings GroundTextures;
/// <summary>Upper/lower texture boundaries for each corner of the sim</summary>
public GroundTextureHeightSettings GroundTextureLimits;
/// <summary>
/// Constructor for EstateTools class
/// </summary>
/// <param name="client"></param>
public EstateTools(GridClient client)
{
GroundTextures = new GroundTextureSettings();
GroundTextureLimits = new GroundTextureHeightSettings();
Client = client;
Client.Network.RegisterCallback(PacketType.LandStatReply, LandStatReplyHandler);
Client.Network.RegisterCallback(PacketType.EstateOwnerMessage, EstateOwnerMessageHandler);
Client.Network.RegisterCallback(PacketType.EstateCovenantReply, EstateCovenantReplyHandler);
Client.Network.RegisterEventCallback("LandStatReply", new Caps.EventQueueCallback(LandStatCapsReplyHandler));
}
#region Enums
/// <summary>Used in the ReportType field of a LandStatRequest</summary>
public enum LandStatReportType
{
TopScripts = 0,
TopColliders = 1
}
/// <summary>Used by EstateOwnerMessage packets</summary>
public enum EstateAccessDelta : uint
{
BanUser = 64,
BanUserAllEstates = 66,
UnbanUser = 128,
UnbanUserAllEstates = 130,
AddManager = 256,
AddManagerAllEstates = 257,
RemoveManager = 512,
RemoveManagerAllEstates = 513,
AddUserAsAllowed = 4,
AddAllowedAllEstates = 6,
RemoveUserAsAllowed = 8,
RemoveUserAllowedAllEstates = 10,
AddGroupAsAllowed = 16,
AddGroupAllowedAllEstates = 18,
RemoveGroupAsAllowed = 32,
RemoveGroupAllowedAllEstates = 34
}
/// <summary>Used by EstateOwnerMessage packets</summary>
public enum EstateAccessReplyDelta : uint
{
AllowedUsers = 17,
AllowedGroups = 18,
EstateBans = 20,
EstateManagers = 24
}
/// <summary>
///
/// </summary>
[Flags]
public enum EstateReturnFlags : uint
{
/// <summary>No flags set</summary>
None = 2,
/// <summary>Only return targets scripted objects</summary>
ReturnScripted = 6,
/// <summary>Only return targets objects if on others land</summary>
ReturnOnOthersLand = 3,
/// <summary>Returns target's scripted objects and objects on other parcels</summary>
ReturnScriptedAndOnOthers = 7
}
#endregion
#region Structs
/// <summary>Ground texture settings for each corner of the region</summary>
// TODO: maybe move this class to the Simulator object and implement it there too
public struct GroundTextureSettings
{
public UUID Low;
public UUID MidLow;
public UUID MidHigh;
public UUID High;
}
/// <summary>Used by GroundTextureHeightSettings</summary>
public struct GroundTextureHeight
{
public float Low;
public float High;
}
/// <summary>The high and low texture thresholds for each corner of the sim</summary>
public struct GroundTextureHeightSettings
{
public GroundTextureHeight SW;
public GroundTextureHeight NW;
public GroundTextureHeight SE;
public GroundTextureHeight NE;
}
#endregion
#region Event delegates, Raise Events
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<TopCollidersReplyEventArgs> m_TopCollidersReply;
/// <summary>Raises the TopCollidersReply event</summary>
/// <param name="e">A TopCollidersReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnTopCollidersReply(TopCollidersReplyEventArgs e)
{
EventHandler<TopCollidersReplyEventArgs> handler = m_TopCollidersReply;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_TopCollidersReply_Lock = new object();
/// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary>
public event EventHandler<TopCollidersReplyEventArgs> TopCollidersReply
{
add { lock (m_TopCollidersReply_Lock) { m_TopCollidersReply += value; } }
remove { lock (m_TopCollidersReply_Lock) { m_TopCollidersReply -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<TopScriptsReplyEventArgs> m_TopScriptsReply;
/// <summary>Raises the TopScriptsReply event</summary>
/// <param name="e">A TopScriptsReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnTopScriptsReply(TopScriptsReplyEventArgs e)
{
EventHandler<TopScriptsReplyEventArgs> handler = m_TopScriptsReply;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_TopScriptsReply_Lock = new object();
/// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary>
public event EventHandler<TopScriptsReplyEventArgs> TopScriptsReply
{
add { lock (m_TopScriptsReply_Lock) { m_TopScriptsReply += value; } }
remove { lock (m_TopScriptsReply_Lock) { m_TopScriptsReply -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<EstateUsersReplyEventArgs> m_EstateUsersReply;
/// <summary>Raises the EstateUsersReply event</summary>
/// <param name="e">A EstateUsersReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnEstateUsersReply(EstateUsersReplyEventArgs e)
{
EventHandler<EstateUsersReplyEventArgs> handler = m_EstateUsersReply;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_EstateUsersReply_Lock = new object();
/// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary>
public event EventHandler<EstateUsersReplyEventArgs> EstateUsersReply
{
add { lock (m_EstateUsersReply_Lock) { m_EstateUsersReply += value; } }
remove { lock (m_EstateUsersReply_Lock) { m_EstateUsersReply -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<EstateGroupsReplyEventArgs> m_EstateGroupsReply;
/// <summary>Raises the EstateGroupsReply event</summary>
/// <param name="e">A EstateGroupsReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnEstateGroupsReply(EstateGroupsReplyEventArgs e)
{
EventHandler<EstateGroupsReplyEventArgs> handler = m_EstateGroupsReply;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_EstateGroupsReply_Lock = new object();
/// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary>
public event EventHandler<EstateGroupsReplyEventArgs> EstateGroupsReply
{
add { lock (m_EstateGroupsReply_Lock) { m_EstateGroupsReply += value; } }
remove { lock (m_EstateGroupsReply_Lock) { m_EstateGroupsReply -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<EstateManagersReplyEventArgs> m_EstateManagersReply;
/// <summary>Raises the EstateManagersReply event</summary>
/// <param name="e">A EstateManagersReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnEstateManagersReply(EstateManagersReplyEventArgs e)
{
EventHandler<EstateManagersReplyEventArgs> handler = m_EstateManagersReply;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_EstateManagersReply_Lock = new object();
/// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary>
public event EventHandler<EstateManagersReplyEventArgs> EstateManagersReply
{
add { lock (m_EstateManagersReply_Lock) { m_EstateManagersReply += value; } }
remove { lock (m_EstateManagersReply_Lock) { m_EstateManagersReply -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<EstateBansReplyEventArgs> m_EstateBansReply;
/// <summary>Raises the EstateBansReply event</summary>
/// <param name="e">A EstateBansReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnEstateBansReply(EstateBansReplyEventArgs e)
{
EventHandler<EstateBansReplyEventArgs> handler = m_EstateBansReply;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_EstateBansReply_Lock = new object();
/// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary>
public event EventHandler<EstateBansReplyEventArgs> EstateBansReply
{
add { lock (m_EstateBansReply_Lock) { m_EstateBansReply += value; } }
remove { lock (m_EstateBansReply_Lock) { m_EstateBansReply -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<EstateCovenantReplyEventArgs> m_EstateCovenantReply;
/// <summary>Raises the EstateCovenantReply event</summary>
/// <param name="e">A EstateCovenantReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnEstateCovenantReply(EstateCovenantReplyEventArgs e)
{
EventHandler<EstateCovenantReplyEventArgs> handler = m_EstateCovenantReply;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_EstateCovenantReply_Lock = new object();
/// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary>
public event EventHandler<EstateCovenantReplyEventArgs> EstateCovenantReply
{
add { lock (m_EstateCovenantReply_Lock) { m_EstateCovenantReply += value; } }
remove { lock (m_EstateCovenantReply_Lock) { m_EstateCovenantReply -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<EstateUpdateInfoReplyEventArgs> m_EstateUpdateInfoReply;
/// <summary>Raises the EstateUpdateInfoReply event</summary>
/// <param name="e">A EstateUpdateInfoReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnEstateUpdateInfoReply(EstateUpdateInfoReplyEventArgs e)
{
EventHandler<EstateUpdateInfoReplyEventArgs> handler = m_EstateUpdateInfoReply;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_EstateUpdateInfoReply_Lock = new object();
/// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary>
public event EventHandler<EstateUpdateInfoReplyEventArgs> EstateUpdateInfoReply
{
add { lock (m_EstateUpdateInfoReply_Lock) { m_EstateUpdateInfoReply += value; } }
remove { lock (m_EstateUpdateInfoReply_Lock) { m_EstateUpdateInfoReply -= value; } }
}
#endregion
#region Public Methods
/// <summary>
/// Requests estate information such as top scripts and colliders
/// </summary>
/// <param name="parcelLocalID"></param>
/// <param name="reportType"></param>
/// <param name="requestFlags"></param>
/// <param name="filter"></param>
public void LandStatRequest(int parcelLocalID, LandStatReportType reportType, uint requestFlags, string filter)
{
LandStatRequestPacket p = new LandStatRequestPacket();
p.AgentData.AgentID = Client.Self.AgentID;
p.AgentData.SessionID = Client.Self.SessionID;
p.RequestData.Filter = Utils.StringToBytes(filter);
p.RequestData.ParcelLocalID = parcelLocalID;
p.RequestData.ReportType = (uint)reportType;
p.RequestData.RequestFlags = requestFlags;
Client.Network.SendPacket(p);
}
/// <summary>Requests estate settings, including estate manager and access/ban lists</summary>
public void RequestInfo()
{
EstateOwnerMessage("getinfo", "");
}
/// <summary>Requests the "Top Scripts" list for the current region</summary>
public void RequestTopScripts()
{
//EstateOwnerMessage("scripts", "");
LandStatRequest(0, LandStatReportType.TopScripts, 0, "");
}
/// <summary>Requests the "Top Colliders" list for the current region</summary>
public void RequestTopColliders()
{
//EstateOwnerMessage("colliders", "");
LandStatRequest(0, LandStatReportType.TopColliders, 0, "");
}
/// <summary>
/// Set several estate specific configuration variables
/// </summary>
/// <param name="WaterHeight">The Height of the waterlevel over the entire estate. Defaults to 20</param>
/// <param name="TerrainRaiseLimit">The maximum height change allowed above the baked terrain. Defaults to 4</param>
/// <param name="TerrainLowerLimit">The minimum height change allowed below the baked terrain. Defaults to -4</param>
/// <param name="UseEstateSun">true to use</param>
/// <param name="FixedSun">if True forces the sun position to the position in SunPosition</param>
/// <param name="SunPosition">The current position of the sun on the estate, or when FixedSun is true the static position
/// the sun will remain. <remarks>6.0 = Sunrise, 30.0 = Sunset</remarks></param>
public void SetTerrainVariables(float WaterHeight, float TerrainRaiseLimit,
float TerrainLowerLimit, bool UseEstateSun, bool FixedSun, float SunPosition)
{
List<string> simVariables = new List<string>();
simVariables.Add(WaterHeight.ToString(Utils.EnUsCulture));
simVariables.Add(TerrainRaiseLimit.ToString(Utils.EnUsCulture));
simVariables.Add(TerrainLowerLimit.ToString(Utils.EnUsCulture));
simVariables.Add(UseEstateSun ? "Y" : "N");
simVariables.Add(FixedSun ? "Y" : "N");
simVariables.Add(SunPosition.ToString(Utils.EnUsCulture));
simVariables.Add("Y"); //Not used?
simVariables.Add("N"); //Not used?
simVariables.Add("0.00"); //Also not used?
EstateOwnerMessage("setregionterrain", simVariables);
}
/// <summary>
/// Request return of objects owned by specified avatar
/// </summary>
/// <param name="Target">The Agents <see cref="UUID"/> owning the primitives to return</param>
/// <param name="flag">specify the coverage and type of objects to be included in the return</param>
/// <param name="EstateWide">true to perform return on entire estate</param>
public void SimWideReturn(UUID Target, EstateReturnFlags flag, bool EstateWide)
{
if (EstateWide)
{
List<string> param = new List<string>();
param.Add(flag.ToString());
param.Add(Target.ToString());
EstateOwnerMessage("estateobjectreturn", param);
}
else
{
SimWideDeletesPacket simDelete = new SimWideDeletesPacket();
simDelete.AgentData.AgentID = Client.Self.AgentID;
simDelete.AgentData.SessionID = Client.Self.SessionID;
simDelete.DataBlock.TargetID = Target;
simDelete.DataBlock.Flags = (uint)flag;
Client.Network.SendPacket(simDelete);
}
}
/// <summary></summary>
/// <param name="method"></param>
/// <param name="param"></param>
public void EstateOwnerMessage(string method, string param)
{
List<string> listParams = new List<string>();
listParams.Add(param);
EstateOwnerMessage(method, listParams);
}
/// <summary>
/// Used for setting and retrieving various estate panel settings
/// </summary>
/// <param name="method">EstateOwnerMessage Method field</param>
/// <param name="listParams">List of parameters to include</param>
public void EstateOwnerMessage(string method, List<string> listParams)
{
EstateOwnerMessagePacket estate = new EstateOwnerMessagePacket();
estate.AgentData.AgentID = Client.Self.AgentID;
estate.AgentData.SessionID = Client.Self.SessionID;
estate.AgentData.TransactionID = UUID.Zero;
estate.MethodData.Invoice = UUID.Random();
estate.MethodData.Method = Utils.StringToBytes(method);
estate.ParamList = new EstateOwnerMessagePacket.ParamListBlock[listParams.Count];
for (int i = 0; i < listParams.Count; i++)
{
estate.ParamList[i] = new EstateOwnerMessagePacket.ParamListBlock();
estate.ParamList[i].Parameter = Utils.StringToBytes(listParams[i]);
}
Client.Network.SendPacket((Packet)estate);
}
/// <summary>
/// Kick an avatar from an estate
/// </summary>
/// <param name="userID">Key of Agent to remove</param>
public void KickUser(UUID userID)
{
EstateOwnerMessage("kickestate", userID.ToString());
}
/// <summary>
/// Ban an avatar from an estate</summary>
/// <param name="userID">Key of Agent to remove</param>
/// <param name="allEstates">Ban user from this estate and all others owned by the estate owner</param>
public void BanUser(UUID userID, bool allEstates)
{
List<string> listParams = new List<string>();
uint flag = allEstates ? (uint)EstateAccessDelta.BanUserAllEstates : (uint)EstateAccessDelta.BanUser;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(userID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
/// <summary>Unban an avatar from an estate</summary>
/// <param name="userID">Key of Agent to remove</param>
/// /// <param name="allEstates">Unban user from this estate and all others owned by the estate owner</param>
public void UnbanUser(UUID userID, bool allEstates)
{
List<string> listParams = new List<string>();
uint flag = allEstates ? (uint)EstateAccessDelta.UnbanUserAllEstates : (uint)EstateAccessDelta.UnbanUser;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(userID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
/// <summary>
/// Send a message dialog to everyone in an entire estate
/// </summary>
/// <param name="message">Message to send all users in the estate</param>
public void EstateMessage(string message)
{
List<string> listParams = new List<string>();
listParams.Add(Client.Self.FirstName + " " + Client.Self.LastName);
listParams.Add(message);
EstateOwnerMessage("instantmessage", listParams);
}
/// <summary>
/// Send a message dialog to everyone in a simulator
/// </summary>
/// <param name="message">Message to send all users in the simulator</param>
public void SimulatorMessage(string message)
{
List<string> listParams = new List<string>();
listParams.Add("-1");
listParams.Add("-1");
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(Client.Self.FirstName + " " + Client.Self.LastName);
listParams.Add(message);
EstateOwnerMessage("simulatormessage", listParams);
}
/// <summary>
/// Send an avatar back to their home location
/// </summary>
/// <param name="pest">Key of avatar to send home</param>
public void TeleportHomeUser(UUID pest)
{
List<string> listParams = new List<string>();
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(pest.ToString());
EstateOwnerMessage("teleporthomeuser", listParams);
}
/// <summary>
/// Begin the region restart process
/// </summary>
public void RestartRegion()
{
EstateOwnerMessage("restart", "120");
}
/// <summary>
/// Cancels a region restart
/// </summary>
public void CancelRestart()
{
EstateOwnerMessage("restart", "-1");
}
/// <summary>Estate panel "Region" tab settings</summary>
public void SetRegionInfo(bool blockTerraform, bool blockFly, bool allowDamage, bool allowLandResell, bool restrictPushing, bool allowParcelJoinDivide, float agentLimit, float objectBonus, bool mature)
{
List<string> listParams = new List<string>();
if (blockTerraform) listParams.Add("Y"); else listParams.Add("N");
if (blockFly) listParams.Add("Y"); else listParams.Add("N");
if (allowDamage) listParams.Add("Y"); else listParams.Add("N");
if (allowLandResell) listParams.Add("Y"); else listParams.Add("N");
listParams.Add(agentLimit.ToString());
listParams.Add(objectBonus.ToString());
if (mature) listParams.Add("21"); else listParams.Add("13"); //FIXME - enumerate these settings
if (restrictPushing) listParams.Add("Y"); else listParams.Add("N");
if (allowParcelJoinDivide) listParams.Add("Y"); else listParams.Add("N");
EstateOwnerMessage("setregioninfo", listParams);
}
/// <summary>Estate panel "Debug" tab settings</summary>
public void SetRegionDebug(bool disableScripts, bool disableCollisions, bool disablePhysics)
{
List<string> listParams = new List<string>();
if (disableScripts) listParams.Add("Y"); else listParams.Add("N");
if (disableCollisions) listParams.Add("Y"); else listParams.Add("N");
if (disablePhysics) listParams.Add("Y"); else listParams.Add("N");
EstateOwnerMessage("setregiondebug", listParams);
}
/// <summary>Used for setting the region's terrain textures for its four height levels</summary>
/// <param name="low"></param>
/// <param name="midLow"></param>
/// <param name="midHigh"></param>
/// <param name="high"></param>
public void SetRegionTerrain(UUID low, UUID midLow, UUID midHigh, UUID high)
{
List<string> listParams = new List<string>();
listParams.Add("0 " + low.ToString());
listParams.Add("1 " + midLow.ToString());
listParams.Add("2 " + midHigh.ToString());
listParams.Add("3 " + high.ToString());
EstateOwnerMessage("texturedetail", listParams);
EstateOwnerMessage("texturecommit", "");
}
/// <summary>Used for setting sim terrain texture heights</summary>
public void SetRegionTerrainHeights(float lowSW, float highSW, float lowNW, float highNW, float lowSE, float highSE, float lowNE, float highNE)
{
List<string> listParams = new List<string>();
listParams.Add("0 " + lowSW.ToString(Utils.EnUsCulture) + " " + highSW.ToString(Utils.EnUsCulture)); //SW low-high
listParams.Add("1 " + lowNW.ToString(Utils.EnUsCulture) + " " + highNW.ToString(Utils.EnUsCulture)); //NW low-high
listParams.Add("2 " + lowSE.ToString(Utils.EnUsCulture) + " " + highSE.ToString(Utils.EnUsCulture)); //SE low-high
listParams.Add("3 " + lowNE.ToString(Utils.EnUsCulture) + " " + highNE.ToString(Utils.EnUsCulture)); //NE low-high
EstateOwnerMessage("textureheights", listParams);
EstateOwnerMessage("texturecommit", "");
}
/// <summary>Requests the estate covenant</summary>
public void RequestCovenant()
{
EstateCovenantRequestPacket req = new EstateCovenantRequestPacket();
req.AgentData.AgentID = Client.Self.AgentID;
req.AgentData.SessionID = Client.Self.SessionID;
Client.Network.SendPacket(req);
}
/// <summary>
/// Upload a terrain RAW file
/// </summary>
/// <param name="fileData">A byte array containing the encoded terrain data</param>
/// <param name="fileName">The name of the file being uploaded</param>
/// <returns>The Id of the transfer request</returns>
public UUID UploadTerrain(byte[] fileData, string fileName)
{
AssetUpload upload = new AssetUpload();
upload.AssetData = fileData;
upload.AssetType = AssetType.Unknown;
upload.Size = fileData.Length;
upload.ID = UUID.Random();
// Tell the library we have a pending file to upload
Client.Assets.SetPendingAssetUploadData(upload);
// Create and populate a list with commands specific to uploading a raw terrain file
List<String> paramList = new List<string>();
paramList.Add("upload filename");
paramList.Add(fileName);
// Tell the simulator we have a new raw file to upload
Client.Estate.EstateOwnerMessage("terrain", paramList);
return upload.ID;
}
/// <summary>
/// Teleports all users home in current Estate
/// </summary>
public void TeleportHomeAllUsers()
{
List<string> Params = new List<string>();
Params.Add(Client.Self.AgentID.ToString());
EstateOwnerMessage("teleporthomeallusers", Params);
}
/// <summary>
/// Remove estate manager</summary>
/// <param name="userID">Key of Agent to Remove</param>
/// <param name="allEstates">removes manager to this estate and all others owned by the estate owner</param>
public void RemoveEstateManager(UUID userID, bool allEstates)
{
List<string> listParams = new List<string>();
uint flag = allEstates ? (uint)EstateAccessDelta.RemoveManagerAllEstates : (uint)EstateAccessDelta.RemoveManager;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(userID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
/// <summary>
/// Add estate manager</summary>
/// <param name="userID">Key of Agent to Add</param>
/// <param name="allEstates">Add agent as manager to this estate and all others owned by the estate owner</param>
public void AddEstateManager(UUID userID, bool allEstates)
{
List<string> listParams = new List<string>();
uint flag = allEstates ? (uint)EstateAccessDelta.AddManagerAllEstates : (uint)EstateAccessDelta.AddManager;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(userID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
/// <summary>
/// Add's an agent to the estate Allowed list</summary>
/// <param name="userID">Key of Agent to Add</param>
/// <param name="allEstates">Add agent as an allowed reisdent to All estates if true</param>
public void AddAllowedUser(UUID userID, bool allEstates)
{
List<string> listParams = new List<string>();
uint flag = allEstates ? (uint)EstateAccessDelta.AddAllowedAllEstates : (uint)EstateAccessDelta.AddUserAsAllowed;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(userID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
/// <summary>
/// Removes an agent from the estate Allowed list</summary>
/// <param name="userID">Key of Agent to Remove</param>
/// <param name="allEstates">Removes agent as an allowed reisdent from All estates if true</param>
public void RemoveAllowedUser(UUID userID, bool allEstates)
{
List<string> listParams = new List<string>();
uint flag = allEstates ? (uint)EstateAccessDelta.RemoveUserAllowedAllEstates : (uint)EstateAccessDelta.RemoveUserAsAllowed;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(userID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
///
/// <summary>
/// Add's a group to the estate Allowed list</summary>
/// <param name="groupID">Key of Group to Add</param>
/// <param name="allEstates">Add Group as an allowed group to All estates if true</param>
public void AddAllowedGroup(UUID groupID, bool allEstates)
{
List<string> listParams = new List<string>();
uint flag = allEstates ? (uint)EstateAccessDelta.AddGroupAllowedAllEstates : (uint)EstateAccessDelta.AddAllowedAllEstates;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(groupID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
///
/// <summary>
/// Removes a group from the estate Allowed list</summary>
/// <param name="groupID">Key of Group to Remove</param>
/// <param name="allEstates">Removes Group as an allowed Group from All estates if true</param>
public void RemoveAllowedGroup(UUID groupID, bool allEstates)
{
List<string> listParams = new List<string>();
uint flag = allEstates ? (uint)EstateAccessDelta.RemoveGroupAllowedAllEstates : (uint)EstateAccessDelta.RemoveGroupAsAllowed;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(groupID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
#endregion
#region Packet Handlers
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void EstateCovenantReplyHandler(object sender, PacketReceivedEventArgs e)
{
EstateCovenantReplyPacket reply = (EstateCovenantReplyPacket)e.Packet;
OnEstateCovenantReply(new EstateCovenantReplyEventArgs(
reply.Data.CovenantID,
reply.Data.CovenantTimestamp,
Utils.BytesToString(reply.Data.EstateName),
reply.Data.EstateOwnerID));
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void EstateOwnerMessageHandler(object sender, PacketReceivedEventArgs e)
{
EstateOwnerMessagePacket message = (EstateOwnerMessagePacket)e.Packet;
uint estateID;
string method = Utils.BytesToString(message.MethodData.Method);
//List<string> parameters = new List<string>();
if (method == "estateupdateinfo")
{
string estateName = Utils.BytesToString(message.ParamList[0].Parameter);
UUID estateOwner = new UUID(Utils.BytesToString(message.ParamList[1].Parameter));
estateID = Utils.BytesToUInt(message.ParamList[2].Parameter);
/*
foreach (EstateOwnerMessagePacket.ParamListBlock param in message.ParamList)
{
parameters.Add(Utils.BytesToString(param.Parameter));
}
*/
bool denyNoPaymentInfo;
if (Utils.BytesToUInt(message.ParamList[8].Parameter) == 0) denyNoPaymentInfo = true;
else denyNoPaymentInfo = false;
OnEstateUpdateInfoReply(new EstateUpdateInfoReplyEventArgs(estateName, estateOwner, estateID, denyNoPaymentInfo));
}
else if (method == "setaccess")
{
int count;
estateID = Utils.BytesToUInt(message.ParamList[0].Parameter);
if (message.ParamList.Length > 1)
{
//param comes in as a string for some reason
uint param;
if (!uint.TryParse(Utils.BytesToString(message.ParamList[1].Parameter), out param)) return;
EstateAccessReplyDelta accessType = (EstateAccessReplyDelta)param;
switch (accessType)
{
case EstateAccessReplyDelta.EstateManagers:
//if (OnGetEstateManagers != null)
{
if (message.ParamList.Length > 5)
{
if (!int.TryParse(Utils.BytesToString(message.ParamList[5].Parameter), out count)) return;
List<UUID> managers = new List<UUID>();
for (int i = 6; i < message.ParamList.Length; i++)
{
try
{
UUID managerID = new UUID(message.ParamList[i].Parameter, 0);
managers.Add(managerID);
}
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }
}
OnEstateManagersReply(new EstateManagersReplyEventArgs(estateID, count, managers));
}
}
break;
case EstateAccessReplyDelta.EstateBans:
//if (OnGetEstateBans != null)
{
if (message.ParamList.Length > 6)
{
if (!int.TryParse(Utils.BytesToString(message.ParamList[4].Parameter), out count)) return;
List<UUID> bannedUsers = new List<UUID>();
for (int i = 7; i < message.ParamList.Length; i++)
{
try
{
UUID bannedID = new UUID(message.ParamList[i].Parameter, 0);
bannedUsers.Add(bannedID);
}
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }
}
OnEstateBansReply(new EstateBansReplyEventArgs(estateID, count, bannedUsers));
}
}
break;
case EstateAccessReplyDelta.AllowedUsers:
//if (OnGetAllowedUsers != null)
{
if (message.ParamList.Length > 5)
{
if (!int.TryParse(Utils.BytesToString(message.ParamList[2].Parameter), out count)) return;
List<UUID> allowedUsers = new List<UUID>();
for (int i = 6; i < message.ParamList.Length; i++)
{
try
{
UUID allowedID = new UUID(message.ParamList[i].Parameter, 0);
allowedUsers.Add(allowedID);
}
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }
}
OnEstateUsersReply(new EstateUsersReplyEventArgs(estateID, count, allowedUsers));
}
}
break;
case EstateAccessReplyDelta.AllowedGroups:
//if (OnGetAllowedGroups != null)
{
if (message.ParamList.Length > 5)
{
if (!int.TryParse(Utils.BytesToString(message.ParamList[3].Parameter), out count)) return;
List<UUID> allowedGroups = new List<UUID>();
for (int i = 5; i < message.ParamList.Length; i++)
{
try
{
UUID groupID = new UUID(message.ParamList[i].Parameter, 0);
allowedGroups.Add(groupID);
}
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }
}
OnEstateGroupsReply(new EstateGroupsReplyEventArgs(estateID, count, allowedGroups));
}
}
break;
}
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void LandStatReplyHandler(object sender, PacketReceivedEventArgs e)
{
//if (OnLandStatReply != null || OnGetTopScripts != null || OnGetTopColliders != null)
//if (OnGetTopScripts != null || OnGetTopColliders != null)
{
LandStatReplyPacket p = (LandStatReplyPacket)e.Packet;
Dictionary<UUID, EstateTask> Tasks = new Dictionary<UUID, EstateTask>();
foreach (LandStatReplyPacket.ReportDataBlock rep in p.ReportData)
{
EstateTask task = new EstateTask();
task.Position = new Vector3(rep.LocationX, rep.LocationY, rep.LocationZ);
task.Score = rep.Score;
task.TaskID = rep.TaskID;
task.TaskLocalID = rep.TaskLocalID;
task.TaskName = Utils.BytesToString(rep.TaskName);
task.OwnerName = Utils.BytesToString(rep.OwnerName);
Tasks.Add(task.TaskID, task);
}
LandStatReportType type = (LandStatReportType)p.RequestData.ReportType;
if (type == LandStatReportType.TopScripts)
{
OnTopScriptsReply(new TopScriptsReplyEventArgs((int)p.RequestData.TotalObjectCount, Tasks));
}
else if (type == LandStatReportType.TopColliders)
{
OnTopCollidersReply(new TopCollidersReplyEventArgs((int) p.RequestData.TotalObjectCount, Tasks));
}
/*
if (OnGetTopColliders != null)
{
//FIXME - System.UnhandledExceptionEventArgs
OnLandStatReply(
type,
p.RequestData.RequestFlags,
(int)p.RequestData.TotalObjectCount,
Tasks
);
}
*/
}
}
private void LandStatCapsReplyHandler(string capsKey, IMessage message, Simulator simulator)
{
LandStatReplyMessage m = (LandStatReplyMessage)message;
Dictionary<UUID, EstateTask> Tasks = new Dictionary<UUID, EstateTask>();
foreach (LandStatReplyMessage.ReportDataBlock rep in m.ReportDataBlocks)
{
EstateTask task = new EstateTask();
task.Position = rep.Location;
task.Score = rep.Score;
task.MonoScore = rep.MonoScore;
task.TaskID = rep.TaskID;
task.TaskLocalID = rep.TaskLocalID;
task.TaskName = rep.TaskName;
task.OwnerName = rep.OwnerName;
Tasks.Add(task.TaskID, task);
}
LandStatReportType type = (LandStatReportType)m.ReportType;
if (type == LandStatReportType.TopScripts)
{
OnTopScriptsReply(new TopScriptsReplyEventArgs((int)m.TotalObjectCount, Tasks));
}
else if (type == LandStatReportType.TopColliders)
{
OnTopCollidersReply(new TopCollidersReplyEventArgs((int)m.TotalObjectCount, Tasks));
}
}
#endregion
}
#region EstateTools EventArgs Classes
/// <summary>Raised on LandStatReply when the report type is for "top colliders"</summary>
public class TopCollidersReplyEventArgs : EventArgs
{
private readonly int m_objectCount;
private readonly Dictionary<UUID, EstateTask> m_Tasks;
/// <summary>
/// The number of returned items in LandStatReply
/// </summary>
public int ObjectCount { get { return m_objectCount; } }
/// <summary>
/// A Dictionary of Object UUIDs to tasks returned in LandStatReply
/// </summary>
public Dictionary<UUID, EstateTask> Tasks { get { return m_Tasks; } }
/// <summary>Construct a new instance of the TopCollidersReplyEventArgs class</summary>
/// <param name="objectCount">The number of returned items in LandStatReply</param>
/// <param name="tasks">Dictionary of Object UUIDs to tasks returned in LandStatReply</param>
public TopCollidersReplyEventArgs(int objectCount, Dictionary<UUID, EstateTask> tasks)
{
this.m_objectCount = objectCount;
this.m_Tasks = tasks;
}
}
/// <summary>Raised on LandStatReply when the report type is for "top Scripts"</summary>
public class TopScriptsReplyEventArgs : EventArgs
{
private readonly int m_objectCount;
private readonly Dictionary<UUID, EstateTask> m_Tasks;
/// <summary>
/// The number of scripts returned in LandStatReply
/// </summary>
public int ObjectCount { get { return m_objectCount; } }
/// <summary>
/// A Dictionary of Object UUIDs to tasks returned in LandStatReply
/// </summary>
public Dictionary<UUID, EstateTask> Tasks { get { return m_Tasks; } }
/// <summary>Construct a new instance of the TopScriptsReplyEventArgs class</summary>
/// <param name="objectCount">The number of returned items in LandStatReply</param>
/// <param name="tasks">Dictionary of Object UUIDs to tasks returned in LandStatReply</param>
public TopScriptsReplyEventArgs(int objectCount, Dictionary<UUID, EstateTask> tasks)
{
this.m_objectCount = objectCount;
this.m_Tasks = tasks;
}
}
/// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary>
public class EstateBansReplyEventArgs : EventArgs
{
private readonly uint m_estateID;
private readonly int m_count;
private readonly List<UUID> m_banned;
/// <summary>
/// The identifier of the estate
/// </summary>
public uint EstateID { get { return m_estateID; } }
/// <summary>
/// The number of returned itmes
/// </summary>
public int Count { get { return m_count; } }
/// <summary>
/// List of UUIDs of Banned Users
/// </summary>
public List<UUID> Banned { get { return m_banned; } }
/// <summary>Construct a new instance of the EstateBansReplyEventArgs class</summary>
/// <param name="estateID">The estate's identifier on the grid</param>
/// <param name="count">The number of returned items in LandStatReply</param>
/// <param name="banned">User UUIDs banned</param>
public EstateBansReplyEventArgs(uint estateID, int count, List<UUID> banned)
{
this.m_estateID = estateID;
this.m_count = count;
this.m_banned = banned;
}
}
/// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary>
public class EstateUsersReplyEventArgs : EventArgs
{
private readonly uint m_estateID;
private readonly int m_count;
private readonly List<UUID> m_allowedUsers;
/// <summary>
/// The identifier of the estate
/// </summary>
public uint EstateID { get { return m_estateID; } }
/// <summary>
/// The number of returned items
/// </summary>
public int Count { get { return m_count; } }
/// <summary>
/// List of UUIDs of Allowed Users
/// </summary>
public List<UUID> AllowedUsers { get { return m_allowedUsers; } }
/// <summary>Construct a new instance of the EstateUsersReplyEventArgs class</summary>
/// <param name="estateID">The estate's identifier on the grid</param>
/// <param name="count">The number of users</param>
/// <param name="allowedUsers">Allowed users UUIDs</param>
public EstateUsersReplyEventArgs(uint estateID, int count, List<UUID> allowedUsers)
{
this.m_estateID = estateID;
this.m_count = count;
this.m_allowedUsers = allowedUsers;
}
}
/// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary>
public class EstateGroupsReplyEventArgs : EventArgs
{
private readonly uint m_estateID;
private readonly int m_count;
private readonly List<UUID> m_allowedGroups;
/// <summary>
/// The identifier of the estate
/// </summary>
public uint EstateID { get { return m_estateID; } }
/// <summary>
/// The number of returned items
/// </summary>
public int Count { get { return m_count; } }
/// <summary>
/// List of UUIDs of Allowed Groups
/// </summary>
public List<UUID> AllowedGroups { get { return m_allowedGroups; } }
/// <summary>Construct a new instance of the EstateGroupsReplyEventArgs class</summary>
/// <param name="estateID">The estate's identifier on the grid</param>
/// <param name="count">The number of Groups</param>
/// <param name="allowedGroups">Allowed Groups UUIDs</param>
public EstateGroupsReplyEventArgs(uint estateID, int count, List<UUID> allowedGroups)
{
this.m_estateID = estateID;
this.m_count = count;
this.m_allowedGroups = allowedGroups;
}
}
/// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary>
public class EstateManagersReplyEventArgs : EventArgs
{
private readonly uint m_estateID;
private readonly int m_count;
private readonly List<UUID> m_Managers;
/// <summary>
/// The identifier of the estate
/// </summary>
public uint EstateID { get { return m_estateID; } }
/// <summary>
/// The number of returned items
/// </summary>
public int Count { get { return m_count; } }
/// <summary>
/// List of UUIDs of the Estate's Managers
/// </summary>
public List<UUID> Managers { get { return m_Managers; } }
/// <summary>Construct a new instance of the EstateManagersReplyEventArgs class</summary>
/// <param name="estateID">The estate's identifier on the grid</param>
/// <param name="count">The number of Managers</param>
/// <param name="managers"> Managers UUIDs</param>
public EstateManagersReplyEventArgs(uint estateID, int count, List<UUID> managers)
{
this.m_estateID = estateID;
this.m_count = count;
this.m_Managers = managers;
}
}
/// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary>
public class EstateCovenantReplyEventArgs : EventArgs
{
private readonly UUID m_covenantID;
private readonly long m_timestamp;
private readonly string m_estateName;
private readonly UUID m_estateOwnerID;
/// <summary>
/// The Covenant
/// </summary>
public UUID CovenantID { get { return m_covenantID; } }
/// <summary>
/// The timestamp
/// </summary>
public long Timestamp { get { return m_timestamp; } }
/// <summary>
/// The Estate name
/// </summary>
public String EstateName { get { return m_estateName; } }
/// <summary>
/// The Estate Owner's ID (can be a GroupID)
/// </summary>
public UUID EstateOwnerID { get { return m_estateOwnerID; } }
/// <summary>Construct a new instance of the EstateCovenantReplyEventArgs class</summary>
/// <param name="covenantID">The Covenant ID</param>
/// <param name="timestamp">The timestamp</param>
/// <param name="estateName">The estate's name</param>
/// <param name="estateOwnerID">The Estate Owner's ID (can be a GroupID)</param>
public EstateCovenantReplyEventArgs(UUID covenantID, long timestamp, string estateName, UUID estateOwnerID)
{
this.m_covenantID = covenantID;
this.m_timestamp = timestamp;
this.m_estateName = estateName;
this.m_estateOwnerID = estateOwnerID;
}
}
/// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary>
public class EstateUpdateInfoReplyEventArgs : EventArgs
{
private readonly uint m_estateID;
private readonly bool m_denyNoPaymentInfo;
private readonly string m_estateName;
private readonly UUID m_estateOwner;
/// <summary>
/// The estate's name
/// </summary>
public String EstateName { get { return m_estateName; } }
/// <summary>
/// The Estate Owner's ID (can be a GroupID)
/// </summary>
public UUID EstateOwner { get { return m_estateOwner; } }
/// <summary>
/// The identifier of the estate on the grid
/// </summary>
public uint EstateID { get { return m_estateID; } }
/// <summary></summary>
public bool DenyNoPaymentInfo { get { return m_denyNoPaymentInfo; } }
/// <summary>Construct a new instance of the EstateUpdateInfoReplyEventArgs class</summary>
/// <param name="estateName">The estate's name</param>
/// <param name="estateOwner">The Estate Owners ID (can be a GroupID)</param>
/// <param name="estateID">The estate's identifier on the grid</param>
/// <param name="denyNoPaymentInfo"></param>
public EstateUpdateInfoReplyEventArgs(string estateName, UUID estateOwner, uint estateID, bool denyNoPaymentInfo)
{
this.m_estateName = estateName;
this.m_estateOwner = estateOwner;
this.m_estateID = estateID;
this.m_denyNoPaymentInfo = denyNoPaymentInfo;
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using OnlineWallet.ExportImport;
using OnlineWallet.Web.Core;
using OnlineWallet.Web.DataLayer;
using OnlineWallet.Web.Modules.TransactionModule;
using OnlineWallet.Web.Modules.TransactionModule.Models;
using OnlineWallet.Web.TestHelpers.Builders;
using TestStack.Dossier.Lists;
namespace OnlineWallet.Web.TestHelpers
{
public class TestServices : IDisposable
{
#region Fields
private readonly SqliteConnection _connection;
private readonly IServiceProvider _rootServices;
private IWalletDbContext _dbContext;
private IServiceScope _services;
private Wallet _walletBankAccount;
private Wallet _walletCash;
#endregion
#region Constructors
public TestServices(Action<ServiceCollection> setup, IMapper map)
{
Map = map;
_connection = new SqliteConnection("DataSource=:memory:");
var services = new ServiceCollection();
services.AddWalletServices();
AddControllers(services);
CreateDatabase(services);
setup?.Invoke(services);
var containerBuilder = new ContainerBuilder();
containerBuilder.Populate(services);
var container = containerBuilder.Build();
_rootServices = new AutofacServiceProvider(container);
}
#endregion
#region Properties
public IWalletDbContext DbContext
{
get
{
EnsureInitialized();
return _dbContext;
}
}
public IMapper Map { get; }
public Wallet WalletBankAccount
{
get
{
EnsureInitialized();
return _walletBankAccount;
}
}
public Wallet WalletCash
{
get
{
EnsureInitialized();
return _walletCash;
}
}
#endregion
#region Public Methods
public IList<Article> BuildArticles(Func<ArticleBuilder, ArticleBuilder> rules, int size = 100)
{
var transactions = rules(ArticleBuilder.CreateListOfSize(size).All())
.BuildList();
return transactions;
}
public IList<Transaction> BuildTransactions(Func<TransactionBuilder, TransactionBuilder> rules, int size = 100)
{
var transactions = rules(TransactionBuilder.CreateListOfSize(size)
.All().WithName("Nothing").WithCategory(null))
.BuildList();
return transactions;
}
public void Cleanup()
{
Dispose();
}
public TEntity Clone<TEntity>(TEntity original)
{
return Map.Map<TEntity>(original);
}
public List<Article> CreateArticlesFromTransactions(IList<Transaction> trans)
{
var articles = trans.Select(e => new Article
{
Name = e.Name,
LastWallet = WalletCash,
Category = String.Empty
}).ToList();
DbContext.Article.AddRange(articles);
return articles;
}
public void Dispose()
{
_services.Dispose();
_services = null;
_dbContext = null;
_connection.Close();
}
public T GetService<T>()
{
if (_services == null)
{
_services = _rootServices.CreateScope();
}
return (T)_services.ServiceProvider.GetRequiredService(typeof(T));
}
public Task PrepareArticlesWith(Func<ArticleBuilder, ArticleBuilder> rules, int size = 100)
{
var transactions = BuildArticles(rules, size);
DbContext.Article.AddRange(transactions);
return DbContext.SaveChangesAsync(CancellationToken.None);
}
public Task PrepareDataWith(Func<TransactionBuilder, TransactionBuilder> rules, int size = 100)
{
var transactions = BuildTransactions(rules, size);
var controller = GetService<TransactionController>();
return controller.BatchSave(TransactionOperationBatch.SaveBatch(transactions)
, CancellationToken.None);
}
#endregion
#region Nonpublic Methods
private static void AddControllers(ServiceCollection services)
{
foreach (var controller in typeof(Startup).Assembly.GetTypes()
.Where(e => typeof(ControllerBase).IsAssignableFrom(e)))
{
services.AddScoped(controller);
}
}
private void CreateDatabase(ServiceCollection services)
{
var optionsBuilder = new DbContextOptionsBuilder<WalletDbContext>();
optionsBuilder.UseSqlite(_connection);
optionsBuilder.EnableSensitiveDataLogging();
optionsBuilder.LogTo(log => Console.WriteLine(log));
services.AddScoped<IWalletDbContext>(provider =>
{
_connection.Open();
var dbContext = new WalletDbContext(optionsBuilder.Options);
dbContext.Database.EnsureCreated();
_walletCash = new Wallet { Name = MoneySource.Cash.ToString() };
_walletBankAccount = new Wallet { Name = MoneySource.BankAccount.ToString() };
dbContext.Wallets.AddRange(
_walletCash,
_walletBankAccount);
dbContext.SaveChanges();
return dbContext;
});
}
private void EnsureInitialized()
{
if (_dbContext != null)
return;
_dbContext = GetService<IWalletDbContext>();
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/reservations/reservation_room_assignment_schedule.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Booking.Reservations {
/// <summary>Holder for reflection information generated from booking/reservations/reservation_room_assignment_schedule.proto</summary>
public static partial class ReservationRoomAssignmentScheduleReflection {
#region Descriptor
/// <summary>File descriptor for booking/reservations/reservation_room_assignment_schedule.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ReservationRoomAssignmentScheduleReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cj9ib29raW5nL3Jlc2VydmF0aW9ucy9yZXNlcnZhdGlvbl9yb29tX2Fzc2ln",
"bm1lbnRfc2NoZWR1bGUucHJvdG8SIGhvbG1zLnR5cGVzLmJvb2tpbmcucmVz",
"ZXJ2YXRpb25zGh1wcmltaXRpdmUvcGJfbG9jYWxfZGF0ZS5wcm90bxobb3Bl",
"cmF0aW9ucy9yb29tcy9yb29tLnByb3RvInoKFFJlc2VydmF0aW9uUm9vbU5p",
"Z2h0EjAKBHJvb20YASABKAsyIi5ob2xtcy50eXBlcy5vcGVyYXRpb25zLnJv",
"b21zLlJvb20SMAoEZGF0ZRgCIAEoCzIiLmhvbG1zLnR5cGVzLnByaW1pdGl2",
"ZS5QYkxvY2FsRGF0ZSJwCiFSZXNlcnZhdGlvblJvb21Bc3NpZ25tZW50U2No",
"ZWR1bGUSSwoLYXNzaWdubWVudHMYASADKAsyNi5ob2xtcy50eXBlcy5ib29r",
"aW5nLnJlc2VydmF0aW9ucy5SZXNlcnZhdGlvblJvb21OaWdodEI5WhRib29r",
"aW5nL3Jlc2VydmF0aW9uc6oCIEhPTE1TLlR5cGVzLkJvb2tpbmcuUmVzZXJ2",
"YXRpb25zYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Reservations.ReservationRoomNight), global::HOLMS.Types.Booking.Reservations.ReservationRoomNight.Parser, new[]{ "Room", "Date" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Reservations.ReservationRoomAssignmentSchedule), global::HOLMS.Types.Booking.Reservations.ReservationRoomAssignmentSchedule.Parser, new[]{ "Assignments" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ReservationRoomNight : pb::IMessage<ReservationRoomNight> {
private static readonly pb::MessageParser<ReservationRoomNight> _parser = new pb::MessageParser<ReservationRoomNight>(() => new ReservationRoomNight());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReservationRoomNight> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Reservations.ReservationRoomAssignmentScheduleReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationRoomNight() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationRoomNight(ReservationRoomNight other) : this() {
Room = other.room_ != null ? other.Room.Clone() : null;
Date = other.date_ != null ? other.Date.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationRoomNight Clone() {
return new ReservationRoomNight(this);
}
/// <summary>Field number for the "room" field.</summary>
public const int RoomFieldNumber = 1;
private global::HOLMS.Types.Operations.Rooms.Room room_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.Rooms.Room Room {
get { return room_; }
set {
room_ = value;
}
}
/// <summary>Field number for the "date" field.</summary>
public const int DateFieldNumber = 2;
private global::HOLMS.Types.Primitive.PbLocalDate date_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate Date {
get { return date_; }
set {
date_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReservationRoomNight);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReservationRoomNight other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Room, other.Room)) return false;
if (!object.Equals(Date, other.Date)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (room_ != null) hash ^= Room.GetHashCode();
if (date_ != null) hash ^= Date.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (room_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Room);
}
if (date_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Date);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (room_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Room);
}
if (date_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Date);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReservationRoomNight other) {
if (other == null) {
return;
}
if (other.room_ != null) {
if (room_ == null) {
room_ = new global::HOLMS.Types.Operations.Rooms.Room();
}
Room.MergeFrom(other.Room);
}
if (other.date_ != null) {
if (date_ == null) {
date_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
Date.MergeFrom(other.Date);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (room_ == null) {
room_ = new global::HOLMS.Types.Operations.Rooms.Room();
}
input.ReadMessage(room_);
break;
}
case 18: {
if (date_ == null) {
date_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(date_);
break;
}
}
}
}
}
public sealed partial class ReservationRoomAssignmentSchedule : pb::IMessage<ReservationRoomAssignmentSchedule> {
private static readonly pb::MessageParser<ReservationRoomAssignmentSchedule> _parser = new pb::MessageParser<ReservationRoomAssignmentSchedule>(() => new ReservationRoomAssignmentSchedule());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReservationRoomAssignmentSchedule> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Reservations.ReservationRoomAssignmentScheduleReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationRoomAssignmentSchedule() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationRoomAssignmentSchedule(ReservationRoomAssignmentSchedule other) : this() {
assignments_ = other.assignments_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationRoomAssignmentSchedule Clone() {
return new ReservationRoomAssignmentSchedule(this);
}
/// <summary>Field number for the "assignments" field.</summary>
public const int AssignmentsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Reservations.ReservationRoomNight> _repeated_assignments_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Booking.Reservations.ReservationRoomNight.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationRoomNight> assignments_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationRoomNight>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationRoomNight> Assignments {
get { return assignments_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReservationRoomAssignmentSchedule);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReservationRoomAssignmentSchedule other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!assignments_.Equals(other.assignments_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= assignments_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
assignments_.WriteTo(output, _repeated_assignments_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += assignments_.CalculateSize(_repeated_assignments_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReservationRoomAssignmentSchedule other) {
if (other == null) {
return;
}
assignments_.Add(other.assignments_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
assignments_.AddEntriesFrom(input, _repeated_assignments_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.
*********************************************************************/
#region license
/*
DirectShowLib - Provide access to DirectShow interfaces via .NET
Copyright (C) 2006
http://sourceforge.net/projects/directshownet/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace DirectShowLib
{
#region Declarations
#if ALLOW_UNTESTED_INTERFACES
/// <summary>
/// From AM_WST_STYLE
/// </summary>
public enum WSTStyle
{
None = 0,
Invers
}
/// <summary>
/// From AMVABUFFERINFO
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct AMVABufferInfo
{
public int dwTypeIndex;
public int dwBufferIndex;
public int dwDataOffset;
public int dwDataSize;
}
/// <summary>
/// From AMVAUncompDataInfo
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct AMVAUncompDataInfo
{
public int dwUncompWidth;
public int dwUncompHeight;
public DDPixelFormat ddUncompPixelFormat;
}
/// <summary>
/// From AMVAUncompBufferInfo
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct AMVAUncompBufferInfo
{
public int dwMinNumSurfaces;
public int dwMaxNumSurfaces;
public DDPixelFormat ddUncompPixelFormat;
}
/// <summary>
/// From AMVAInternalMemInfo
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct AMVAInternalMemInfo
{
public int dwScratchMemAlloc;
}
/// <summary>
/// From DDSCAPS2
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DDSCaps2
{
public int dwCaps;
public int dwCaps2;
public int dwCaps3;
public int dwCaps4;
}
/// <summary>
/// From AMVACompBufferInfo
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct AMVACompBufferInfo
{
public int dwNumCompBuffers;
public int dwWidthToCreate;
public int dwHeightToCreate;
public int dwBytesToAllocate;
public DDSCaps2 ddCompCaps;
public DDPixelFormat ddPixelFormat;
}
/// <summary>
/// From AMVABeginFrameInfo
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct AMVABeginFrameInfo
{
public int dwDestSurfaceIndex;
public IntPtr pInputData; // LPVOID
public int dwSizeInputData;
public IntPtr pOutputData; // LPVOID
public int dwSizeOutputData;
}
/// <summary>
/// From AMVAEndFrameInfo
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct AMVAEndFrameInfo
{
public int dwSizeMiscData;
public IntPtr pMiscData; // LPVOID
}
#endif
/// <summary>
/// From AM_WST_LEVEL
/// </summary>
public enum WSTLevel
{
Level1_5 = 0
}
/// <summary>
/// From AM_WST_SERVICE
/// </summary>
public enum WSTService
{
None = 0,
Text,
IDS,
Invalid
}
/// <summary>
/// From AM_WST_STATE
/// </summary>
public enum WSTState
{
Off = 0,
On
}
/// <summary>
/// From AM_WST_DRAWBGMODE
/// </summary>
public enum WSTDrawBGMode
{
Opaque,
Transparent
}
/// <summary>
/// Not from DirectShow
/// </summary>
public enum MPEGAudioDivider
{
CDAudio = 1,
FMRadio = 2,
AMRadio = 4
}
/// <summary>
/// From AM_MPEG_AUDIO_DUAL_* defines
/// </summary>
public enum MPEGAudioDual
{
Merge,
Left,
Right
}
/// <summary>
/// Not from DirectShow
/// </summary>
public enum MPEGAudioAccuracy
{
Best = 0x0000,
High = 0x4000,
Full = 0x8000
}
/// <summary>
/// Not from DirectShow
/// </summary>
public enum MPEGAudioChannels
{
Mono = 1,
Stereo = 2
}
/// <summary>
/// From AM_WST_PAGE
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct WSTPage
{
public int dwPageNr ;
public int dwSubPageNr ;
public IntPtr pucPageData; // BYTE *
}
/// <summary>
/// From ACM_MPEG_LAYER* defines
/// </summary>
public enum AcmMpegHeadLayer : short
{
Layer1 = 1,
Layer2,
Layer3
}
/// <summary>
/// From ACM_MPEG_* defines
/// </summary>
public enum AcmMpegHeadMode : short
{
Stereo = 1,
JointStereo,
DualChannel,
SingleChannel
}
/// <summary>
/// From ACM_MPEG_* defines
/// </summary>
[Flags]
public enum AcmMpegHeadFlags : short
{
None = 0x0,
PrivateBit = 0x1,
Copyright = 0x2,
OriginalHome = 0x4,
ProtectionBit = 0x8,
IDMpeg1 = 0x10
}
/// <summary>
/// From MPEG1WAVEFORMAT
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=2)]
public class MPEG1WaveFormat
{
public WaveFormatEx wfx;
public AcmMpegHeadLayer fwHeadLayer;
public int dwHeadBitrate;
public AcmMpegHeadMode fwHeadMode;
public short fwHeadModeExt;
public short wHeadEmphasis;
public AcmMpegHeadFlags fwHeadFlags;
public int dwPTSLow;
public int dwPTSHigh;
}
#endregion
#region Interfaces
#if ALLOW_UNTESTED_INTERFACES
[ComImport,
Guid("c47a3420-005c-11d2-9038-00a0c9697298"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAMParse
{
[PreserveSig]
int GetParseTime(out long prtCurrent);
[PreserveSig]
int SetParseTime(long rtCurrent);
[PreserveSig]
int Flush();
}
[ComImport,
Guid("a8809222-07bb-48ea-951c-33158100625b"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IGetCapabilitiesKey
{
[PreserveSig]
int GetCapabilitiesKey( [Out] out IntPtr pHKey ); // HKEY
}
[ComImport,
Guid("256A6A21-FBAD-11d1-82BF-00A0C9696C8F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAMVideoAcceleratorNotify
{
[PreserveSig]
int GetUncompSurfacesInfo([In, MarshalAs(UnmanagedType.LPStruct)] Guid pGuid,
[Out] out AMVAUncompBufferInfo pUncompBufferInfo);
[PreserveSig]
int SetUncompSurfacesInfo([In] int dwActualUncompSurfacesAllocated);
[PreserveSig]
int GetCreateVideoAcceleratorData([In, MarshalAs(UnmanagedType.LPStruct)] Guid pGuid,
[Out] out int pdwSizeMiscData,
[Out] IntPtr ppMiscData); // LPVOID
}
[ComImport,
Guid("256A6A22-FBAD-11d1-82BF-00A0C9696C8F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAMVideoAccelerator
{
[PreserveSig]
int GetVideoAcceleratorGUIDs([Out] out int pdwNumGuidsSupported,
[In, Out] Guid [] pGuidsSupported);
[PreserveSig]
int GetUncompFormatsSupported( [In, MarshalAs(UnmanagedType.LPStruct)] Guid pGuid,
[Out] out int pdwNumFormatsSupported,
[Out] out DDPixelFormat pFormatsSupported);
[PreserveSig]
int GetInternalMemInfo([In, MarshalAs(UnmanagedType.LPStruct)] Guid pGuid,
[In] AMVAUncompDataInfo pamvaUncompDataInfo,
[Out] out AMVAInternalMemInfo pamvaInternalMemInfo);
[PreserveSig]
int GetCompBufferInfo([In, MarshalAs(UnmanagedType.LPStruct)] Guid pGuid,
[In] AMVAUncompDataInfo pamvaUncompDataInfo,
[In, Out] int pdwNumTypesCompBuffers,
[Out] out AMVACompBufferInfo pamvaCompBufferInfo);
[PreserveSig]
int GetInternalCompBufferInfo([Out] out int pdwNumTypesCompBuffers,
[Out] out AMVACompBufferInfo pamvaCompBufferInfo);
[PreserveSig]
int BeginFrame([In] AMVABeginFrameInfo amvaBeginFrameInfo);
[PreserveSig]
int EndFrame([In] AMVAEndFrameInfo pEndFrameInfo);
[PreserveSig]
int GetBuffer(
[In] int dwTypeIndex,
[In] int dwBufferIndex,
[In, MarshalAs(UnmanagedType.Bool)] bool bReadOnly,
[Out] IntPtr ppBuffer, // LPVOID
[Out] out int lpStride);
[PreserveSig]
int ReleaseBuffer([In] int dwTypeIndex,
[In] int dwBufferIndex);
[PreserveSig]
int Execute(
[In] int dwFunction,
[In] IntPtr lpPrivateInputData, // LPVOID
[In] int cbPrivateInputData,
[In] IntPtr lpPrivateOutputDat, // LPVOID
[In] int cbPrivateOutputData,
[In] int dwNumBuffers,
[In] AMVABufferInfo pamvaBufferInfo);
[PreserveSig]
int QueryRenderStatus([In] int dwTypeIndex,
[In] int dwBufferIndex,
[In] int dwFlags);
[PreserveSig]
int DisplayFrame([In] int dwFlipToIndex,
[In] IMediaSample pMediaSample);
}
[ComImport,
Guid("56a868fd-0ad4-11ce-b0a3-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAMFilterGraphCallback
{
[PreserveSig]
int UnableToRender(IPin pPin);
}
[ComImport,
Guid("AB6B4AFE-F6E4-11d0-900D-00C04FD9189D"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDirectDrawMediaSample
{
[PreserveSig]
int GetSurfaceAndReleaseLock(
[MarshalAs(UnmanagedType.IUnknown)] out object ppDirectDrawSurface, // IDirectDrawSurface
out Rectangle pRect);
[PreserveSig]
int LockMediaSamplePointer();
}
[ComImport,
Guid("AB6B4AFC-F6E4-11d0-900D-00C04FD9189D"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDirectDrawMediaSampleAllocator
{
[PreserveSig]
int GetDirectDraw(
[MarshalAs(UnmanagedType.IUnknown)] out object ppDirectDraw); // IDirectDraw
}
#endif
[ComImport,
Guid("45086030-F7E4-486a-B504-826BB5792A3B"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IConfigAsfWriter
{
[PreserveSig,
Obsolete("This method is now obsolete because it assumes version 4.0 Windows Media Format SDK profiles. Use GetCurrentProfile or GetCurrentProfileGuid instead to correctly identify a profile.", false)]
int ConfigureFilterUsingProfileId([In] int dwProfileId);
[PreserveSig,
Obsolete("This method is now obsolete because it assumes version 4.0 Windows Media Format SDK profiles. Use GetCurrentProfile or GetCurrentProfileGuid instead to correctly identify a profile.", false)]
int GetCurrentProfileId([Out] out int pdwProfileId);
[PreserveSig,
Obsolete("Using Guids is considered obsolete by MS. The preferred approach is using an IWMProfile. See ConfigureFilterUsingProfile", false)]
int ConfigureFilterUsingProfileGuid([In, MarshalAs(UnmanagedType.LPStruct)] Guid guidProfile);
[PreserveSig,
Obsolete("Using Guids is considered obsolete by MS. The preferred approach is using an IWMProfile. See GetCurrentProfile", false)]
int GetCurrentProfileGuid([Out] out Guid pProfileGuid);
[PreserveSig,
Obsolete("This method requires IWMProfile, which in turn requires several other interfaces. Rather than duplicate all those interfaces here, it is recommended that you use the WindowsMediaLib from http://DirectShowNet.SourceForge.net", false)]
int ConfigureFilterUsingProfile([In] IntPtr pProfile);
[PreserveSig,
Obsolete("This method requires IWMProfile, which in turn requires several other interfaces. Rather than duplicate all those interfaces here, it is recommended that you use the WindowsMediaLib from http://DirectShowNet.SourceForge.net", false)]
int GetCurrentProfile([Out] out IntPtr ppProfile);
[PreserveSig]
int SetIndexMode([In, MarshalAs(UnmanagedType.Bool)] bool bIndexFile);
[PreserveSig]
int GetIndexMode([Out, MarshalAs(UnmanagedType.Bool)] out bool pbIndexFile);
}
[ComImport,
Guid("546F4260-D53E-11cf-B3F0-00AA003761C5"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAMDirectSound
{
[PreserveSig]
int GetDirectSoundInterface([MarshalAs(UnmanagedType.IUnknown)] out object lplpds); // IDirectSound
[PreserveSig]
int GetPrimaryBufferInterface([MarshalAs(UnmanagedType.IUnknown)] out object lplpdsb); // IDirectSoundBuffer
[PreserveSig]
int GetSecondaryBufferInterface([MarshalAs(UnmanagedType.IUnknown)] out object lplpdsb); // IDirectSoundBuffer
[PreserveSig]
int ReleaseDirectSoundInterface([MarshalAs(UnmanagedType.IUnknown)] object lpds); // IDirectSound
[PreserveSig]
int ReleasePrimaryBufferInterface([MarshalAs(UnmanagedType.IUnknown)] object lpdsb); // IDirectSoundBuffer
[PreserveSig]
int ReleaseSecondaryBufferInterface([MarshalAs(UnmanagedType.IUnknown)] object lpdsb); // IDirectSoundBuffer
[PreserveSig]
int SetFocusWindow(IntPtr hWnd, [In, MarshalAs(UnmanagedType.Bool)] bool bSet);
[PreserveSig]
int GetFocusWindow(out IntPtr hWnd, [Out, MarshalAs(UnmanagedType.Bool)] out bool bSet);
}
[ComImport,
Guid("C056DE21-75C2-11d3-A184-00105AEF9F33"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAMWstDecoder
{
[PreserveSig]
int GetDecoderLevel(out WSTLevel lpLevel);
[PreserveSig]
int GetCurrentService(out WSTService lpService);
[PreserveSig]
int GetServiceState(out WSTState lpState);
[PreserveSig]
int SetServiceState(WSTState State);
[PreserveSig]
int GetOutputFormat([MarshalAs(UnmanagedType.LPStruct)] BitmapInfoHeader lpbmih);
[PreserveSig]
int SetOutputFormat(BitmapInfoHeader lpbmi);
[PreserveSig]
int GetBackgroundColor(out int pdwPhysColor);
[PreserveSig]
int SetBackgroundColor(int dwPhysColor);
[PreserveSig]
int GetRedrawAlways([MarshalAs(UnmanagedType.Bool)] out bool lpbOption);
[PreserveSig]
int SetRedrawAlways([MarshalAs(UnmanagedType.Bool)] bool bOption);
[PreserveSig]
int GetDrawBackgroundMode(out WSTDrawBGMode lpMode);
[PreserveSig]
int SetDrawBackgroundMode(WSTDrawBGMode Mode);
[PreserveSig]
int SetAnswerMode([MarshalAs(UnmanagedType.Bool)] bool bAnswer);
[PreserveSig]
int GetAnswerMode([MarshalAs(UnmanagedType.Bool)] out bool pbAnswer);
[PreserveSig]
int SetHoldPage([MarshalAs(UnmanagedType.Bool)] bool bHoldPage);
[PreserveSig]
int GetHoldPage([MarshalAs(UnmanagedType.Bool)] out bool pbHoldPage);
[PreserveSig]
int GetCurrentPage([In, Out] WSTPage pWstPage);
[PreserveSig]
int SetCurrentPage([In] WSTPage WstPage);
}
[ComImport,
Guid("b45dd570-3c77-11d1-abe1-00a0c905f375"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMpegAudioDecoder
{
[PreserveSig]
int get_FrequencyDivider(
out MPEGAudioDivider pDivider
);
[PreserveSig]
int put_FrequencyDivider(
MPEGAudioDivider Divider
);
[PreserveSig]
int get_DecoderAccuracy(
out MPEGAudioAccuracy pAccuracy
);
[PreserveSig]
int put_DecoderAccuracy(
MPEGAudioAccuracy Accuracy
);
[PreserveSig]
int get_Stereo(
out MPEGAudioChannels pStereo
);
[PreserveSig]
int put_Stereo(
MPEGAudioChannels Stereo
);
[PreserveSig]
int get_DecoderWordSize(
out int pWordSize
);
[PreserveSig]
int put_DecoderWordSize(
int WordSize
);
[PreserveSig]
int get_IntegerDecode(
out int pIntDecode
);
[PreserveSig]
int put_IntegerDecode(
int IntDecode
);
[PreserveSig]
int get_DualMode(
out MPEGAudioDual pIntDecode
);
[PreserveSig]
int put_DualMode(
MPEGAudioDual IntDecode
);
[PreserveSig]
int get_AudioFormat(
out MPEG1WaveFormat lpFmt
);
}
[ComImport,
Guid("6d5140c1-7436-11ce-8034-00aa006009fa"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IServiceProvider
{
int QueryService(
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid guidService,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid riid,
[MarshalAs(UnmanagedType.IUnknown)] out object ppvObject
);
}
[ComImport,
Guid("FC4801A3-2BA9-11CF-A229-00AA003D7352"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IObjectWithSite
{
[PreserveSig]
int SetSite(
[In, MarshalAs(UnmanagedType.IUnknown)] object pUnkSite
);
[PreserveSig]
int GetSite(
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid riid,
[MarshalAs(UnmanagedType.IUnknown)] out object ppvSite
);
}
#endregion
}
| |
// ***********************************************************************
// Copyright (c) 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.Generic;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
namespace NUnit.TestData.TestContextData
{
[TestFixture]
public class TestStateRecordingFixture
{
public string StateList;
public bool TestFailure;
public bool TestInconclusive;
public bool SetUpFailure;
public bool SetUpIgnore;
[SetUp]
public void SetUp()
{
StateList = TestContext.CurrentContext.Result.Outcome + "=>";
if (SetUpFailure)
Assert.Fail("Failure in SetUp");
if (SetUpIgnore)
Assert.Ignore("Ignored in SetUp");
}
[Test]
public void TheTest()
{
StateList += TestContext.CurrentContext.Result.Outcome;
if (TestFailure)
Assert.Fail("Deliberate failure");
if (TestInconclusive)
Assert.Inconclusive("Inconclusive test");
}
[TearDown]
public void TearDown()
{
StateList += "=>" + TestContext.CurrentContext.Result.Outcome;
}
}
public class AssertionResultFixture
{
public IEnumerable<AssertionResult> Assertions;
public void ThreeAsserts_TwoFailed()
{
Assert.Multiple(() =>
{
Assert.That(2 + 2, Is.EqualTo(5));
Assert.That(2 + 2, Is.EqualTo(4));
Assert.That(2 + 2, Is.EqualTo(5));
Assertions = TestContext.CurrentContext.Result.Assertions;
});
}
public void WarningPlusFailedAssert()
{
Warn.Unless(2 + 2, Is.EqualTo(5));
Assert.Multiple(() =>
{
Assert.That(2 + 2, Is.EqualTo(5));
Assertions = TestContext.CurrentContext.Result.Assertions;
});
}
}
[TestFixture]
public class TestTestContextInTearDown
{
public int FailCount { get; private set; }
public string Message { get; private set; }
public string StackTrace { get; private set; }
[Test]
public void FailingTest()
{
Assert.Fail("Deliberate failure");
}
[TearDown]
public void TearDown()
{
FailCount = TestContext.CurrentContext.Result.FailCount;
Message = TestContext.CurrentContext.Result.Message;
StackTrace = TestContext.CurrentContext.Result.StackTrace;
}
}
[TestFixture]
public class TestTestContextInOneTimeTearDown
{
public int PassCount { get; private set; }
public int FailCount { get; private set; }
public int WarningCount { get; private set; }
public int SkipCount { get; private set; }
public int InconclusiveCount { get; private set; }
public string Message { get; private set; }
public string StackTrace { get; private set; }
[Test]
public void FailingTest()
{
Assert.Fail("Deliberate failure");
}
[Test]
public void PassingTest()
{
Assert.Pass();
}
[Test]
public void AnotherPassingTest()
{
Assert.Pass();
}
[Test]
public void IgnoredTest()
{
Assert.Ignore("I don't want to run this test");
}
[Test]
public void IgnoredTestTwo()
{
Assert.Ignore("I don't want to run this test either");
}
[Test]
public void IgnoredTestThree()
{
Assert.Ignore("Nor do I want to run this test");
}
[Test]
public void AssumeSomething()
{
Assume.That( false );
}
[Test]
public void AssumeSomethingElse()
{
Assume.That(false);
}
[Test]
public void NeverAssume()
{
Assume.That(false);
}
[Test]
public void AssumeTheWorldIsFlat()
{
Assume.That(false);
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
PassCount = TestContext.CurrentContext.Result.PassCount;
FailCount = TestContext.CurrentContext.Result.FailCount;
WarningCount = TestContext.CurrentContext.Result.WarningCount;
SkipCount = TestContext.CurrentContext.Result.SkipCount;
InconclusiveCount = TestContext.CurrentContext.Result.InconclusiveCount;
Message = TestContext.CurrentContext.Result.Message;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT license.
#if UNITY_WSA_10_0 && !UNITY_EDITOR
using Microsoft.AppCenter.Unity.Internal.Utils;
using Microsoft.AppCenter.Utils;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System;
namespace Microsoft.AppCenter.Unity.Internal
{
using UWPAppCenter = Microsoft.AppCenter.AppCenter;
class AppCenterInternal
{
private static bool _prepared = false;
private static object _lockObject = new object();
public static void Configure(string appSecret)
{
Prepare();
UWPAppCenter.Configure(appSecret);
}
public static void Start(string appSecret, Type[] services)
{
var nativeServiceTypes = ServicesToNativeTypes(services);
Prepare();
UWPAppCenter.Start(appSecret, nativeServiceTypes);
}
public static void Start(Type[] services)
{
var nativeServiceTypes = ServicesToNativeTypes(services);
Prepare();
UWPAppCenter.Start(nativeServiceTypes);
}
public static void Start(Type service)
{
}
public static string GetSdkVersion()
{
return "";
}
public static void StartServices(Type[] services, int numServices)
{
Prepare();
UWPAppCenter.Start(services);
}
public static void SetLogLevel(int logLevel)
{
Prepare();
UWPAppCenter.LogLevel = (Microsoft.AppCenter.LogLevel)LogLevelFromUnity(logLevel);
}
public static void SetUserId(string userId)
{
}
public static int GetLogLevel()
{
Prepare();
return (int)LogLevelFromUnity((int)UWPAppCenter.LogLevel);
}
public static bool IsConfigured()
{
Prepare();
return UWPAppCenter.Configured;
}
public static void SetLogUrl(string logUrl)
{
Prepare();
UWPAppCenter.SetLogUrl(logUrl);
}
public static AppCenterTask SetEnabledAsync(bool isEnabled)
{
Prepare();
return new AppCenterTask(UWPAppCenter.SetEnabledAsync(isEnabled));
}
public static AppCenterTask<bool> IsEnabledAsync()
{
Prepare();
return new AppCenterTask<bool>(UWPAppCenter.IsEnabledAsync());
}
public static AppCenterTask<string> GetInstallIdAsync()
{
Prepare();
var installIdTask = UWPAppCenter.GetInstallIdAsync();
var stringTask = new AppCenterTask<string>();
installIdTask.ContinueWith(t =>
{
var installId = t.Result?.ToString();
stringTask.SetResult(installId);
});
return stringTask;
}
public static void SetCustomProperties(object properties)
{
Prepare();
var uwpProperties = properties as Microsoft.AppCenter.CustomProperties;
UWPAppCenter.SetCustomProperties(uwpProperties);
}
public static void SetWrapperSdk(string wrapperSdkVersion,
string wrapperSdkName,
string wrapperRuntimeVersion,
string liveUpdateReleaseLabel,
string liveUpdateDeploymentKey,
string liveUpdatePackageHash)
{
//TODO once wrapper sdk exists for uwp, set it here
}
private static int LogLevelToUnity(int logLevel)
{
switch ((Microsoft.AppCenter.LogLevel)logLevel)
{
case Microsoft.AppCenter.LogLevel.Verbose:
return (int)Microsoft.AppCenter.Unity.LogLevel.Verbose;
case Microsoft.AppCenter.LogLevel.Debug:
return (int)Microsoft.AppCenter.Unity.LogLevel.Debug;
case Microsoft.AppCenter.LogLevel.Info:
return (int)Microsoft.AppCenter.Unity.LogLevel.Info;
case Microsoft.AppCenter.LogLevel.Warn:
return (int)Microsoft.AppCenter.Unity.LogLevel.Warn;
case Microsoft.AppCenter.LogLevel.Error:
return (int)Microsoft.AppCenter.Unity.LogLevel.Error;
case Microsoft.AppCenter.LogLevel.Assert:
return (int)Microsoft.AppCenter.Unity.LogLevel.Assert;
case Microsoft.AppCenter.LogLevel.None:
return (int)Microsoft.AppCenter.Unity.LogLevel.None;
default:
return logLevel;
}
}
private static Microsoft.AppCenter.LogLevel LogLevelFromUnity(int logLevel)
{
switch ((Microsoft.AppCenter.Unity.LogLevel)logLevel)
{
case Microsoft.AppCenter.Unity.LogLevel.Verbose:
return Microsoft.AppCenter.LogLevel.Verbose;
case Microsoft.AppCenter.Unity.LogLevel.Debug:
return Microsoft.AppCenter.LogLevel.Debug;
case Microsoft.AppCenter.Unity.LogLevel.Info:
return Microsoft.AppCenter.LogLevel.Info;
case Microsoft.AppCenter.Unity.LogLevel.Warn:
return Microsoft.AppCenter.LogLevel.Warn;
case Microsoft.AppCenter.Unity.LogLevel.Error:
return Microsoft.AppCenter.LogLevel.Error;
case Microsoft.AppCenter.Unity.LogLevel.Assert:
return Microsoft.AppCenter.LogLevel.Assert;
case Microsoft.AppCenter.Unity.LogLevel.None:
return Microsoft.AppCenter.LogLevel.None;
default:
return (Microsoft.AppCenter.LogLevel)logLevel;
}
}
public static void StartFromLibrary(Type[] services)
{
}
public static Type[] ServicesToNativeTypes(Type[] services)
{
var nativeTypes = new List<Type>();
foreach (var service in services)
{
service.GetMethod("AddNativeType").Invoke(null, new object[] { nativeTypes });
}
return nativeTypes.ToArray();
}
public static void SetMaxStorageSize(long size)
{
}
private static void Prepare()
{
lock (_lockObject)
{
if (!_prepared)
{
UnityScreenSizeProvider.Initialize();
DeviceInformationHelper.SetScreenSizeProviderFactory(new UnityScreenSizeProviderFactory());
#if ENABLE_IL2CPP
#pragma warning disable 612
/**
* Workaround for known IL2CPP issue.
* See https://issuetracker.unity3d.com/issues/il2cpp-use-of-windows-dot-foundation-dot-collections-dot-propertyset-throws-a-notsupportedexception-on-uwp
*
* NotSupportedException: Cannot call method
* 'System.Boolean System.Runtime.InteropServices.WindowsRuntime.IMapToIDictionaryAdapter`2::System.Collections.Generic.IDictionary`2.TryGetValue(TKey,TValue&)'.
* IL2CPP does not yet support calling this projected method.
*/
UnityApplicationSettings.Initialize();
UWPAppCenter.SetApplicationSettingsFactory(new UnityApplicationSettingsFactory());
/**
* Workaround for another IL2CPP issue.
* System.Net.Http.HttpClient doesn't work properly so, replace to unity specific implementation.
*/
UWPAppCenter.SetChannelGroupFactory(new UnityChannelGroupFactory());
#pragma warning restore 612
#endif
_prepared = true;
}
}
}
}
}
#endif
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 10/11/2009 11:43:53 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using DotSpatial.Data;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
[Serializable]
public class ColorScheme : Scheme, IColorScheme
{
#region Private Variables
private ColorCategoryCollection _categories;
private float _opacity;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of ColorScheme
/// </summary>
public ColorScheme()
{
Configure();
}
/// <summary>
/// Creates a new instance of a color scheme using a predefined color scheme and the minimum and maximum specified
/// from the raster itself
/// </summary>
/// <param name="schemeType">The predefined scheme to use</param>
/// <param name="raster">The raster to obtain the minimum and maximum settings from</param>
public ColorScheme(ColorSchemeType schemeType, IRaster raster)
{
Configure();
ApplyScheme(schemeType, raster);
}
/// <summary>
/// This creates a new scheme, applying the specified color scheme, and using the minimum and maximum values indicated.
/// </summary>
/// <param name="schemeType">The predefined color scheme</param>
/// <param name="min">The minimum</param>
/// <param name="max">The maximum</param>
public ColorScheme(ColorSchemeType schemeType, double min, double max)
{
Configure();
ApplyScheme(schemeType, min, max);
}
private void Configure()
{
_categories = new ColorCategoryCollection(this);
_opacity = 1;
EditorSettings = new RasterEditorSettings();
}
#endregion
#region Methods
/// <summary>
/// Applies the specified color scheme and uses the specified raster to define the
/// minimum and maximum to use for the scheme.
/// </summary>
/// <param name="schemeType"></param>
/// <param name="raster"></param>
public void ApplyScheme(ColorSchemeType schemeType, IRaster raster)
{
double min, max;
if (!raster.IsInRam)
{
GetValues(raster);
min = Statistics.Minimum;
max = Statistics.Maximum;
}
else
{
min = raster.Minimum;
max = raster.Maximum;
}
ApplyScheme(schemeType, min, max);
}
/// <summary>
/// Creates the category using a random fill color
/// </summary>
/// <param name="fillColor">The base color to use for creating the category</param>
/// <param name="size">For points this is the larger dimension, for lines this is the largest width</param>
/// <returns>A new IFeatureCategory that matches the type of this scheme</returns>
public override ICategory CreateNewCategory(Color fillColor, double size)
{
return new ColorCategory(null, null, fillColor, fillColor);
}
/// <summary>
/// Creates the categories for this scheme based on statistics and values
/// sampled from the specified raster.
/// </summary>
/// <param name="raster">The raster to use when creating categories</param>
public void CreateCategories(IRaster raster)
{
GetValues(raster);
CreateBreakCategories();
OnItemChanged(this);
}
/// <summary>
/// Gets the values from the raster. If MaxSampleCount is less than the
/// number of cells, then it randomly samples the raster with MaxSampleCount
/// values. Otherwise it gets all the values in the raster.
/// </summary>
/// <param name="raster">The raster to sample</param>
public void GetValues(IRaster raster)
{
Values = raster.GetRandomValues(EditorSettings.MaxSampleCount);
var keepers = Values.Where(val => val != raster.NoDataValue).ToList();
Values = keepers;
Statistics.Calculate(Values, raster.Minimum, raster.Maximum);
}
/// <summary>
/// Applies the specified color scheme and uses the specified raster to define the
/// minimum and maximum to use for the scheme.
/// </summary>
/// <param name="schemeType">ColorSchemeType</param>
/// <param name="min">THe minimum value to use for the scheme</param>
/// <param name="max">THe maximum value to use for the scheme</param>
public void ApplyScheme(ColorSchemeType schemeType, double min, double max)
{
if (Categories == null)
{
Categories = new ColorCategoryCollection(this);
}
else
{
Categories.Clear();
}
IColorCategory eqCat = null, low = null, high = null;
if (min == max)
{
// Create one category
eqCat = new ColorCategory(min, max) {Range = {MaxIsInclusive = true, MinIsInclusive = true}};
eqCat.ApplyMinMax(EditorSettings);
Categories.Add(eqCat);
}
else
{
// Create two categories
low = new ColorCategory(min, (min + max) / 2) {Range = {MaxIsInclusive = true}};
high = new ColorCategory((min + max) / 2, max) {Range = {MaxIsInclusive = true}};
low.ApplyMinMax(EditorSettings);
high.ApplyMinMax(EditorSettings);
Categories.Add(low);
Categories.Add(high);
}
Color lowColor, midColor, highColor;
int alpha = ByteRange(Convert.ToInt32(_opacity * 255F));
switch (schemeType)
{
case ColorSchemeType.Summer_Mountains:
lowColor = Color.FromArgb(alpha, 10, 100, 10);
midColor = Color.FromArgb(alpha, 153, 125, 25);
highColor = Color.FromArgb(alpha, 255, 255, 255);
break;
case ColorSchemeType.FallLeaves:
lowColor = Color.FromArgb(alpha, 10, 100, 10);
midColor = Color.FromArgb(alpha, 199, 130, 61);
highColor = Color.FromArgb(alpha, 241, 220, 133);
break;
case ColorSchemeType.Desert:
lowColor = Color.FromArgb(alpha, 211, 206, 97);
midColor = Color.FromArgb(alpha, 139, 120, 112);
highColor = Color.FromArgb(alpha, 255, 255, 255);
break;
case ColorSchemeType.Glaciers:
lowColor = Color.FromArgb(alpha, 105, 171, 224);
midColor = Color.FromArgb(alpha, 162, 234, 240);
highColor = Color.FromArgb(alpha, 255, 255, 255);
break;
case ColorSchemeType.Meadow:
lowColor = Color.FromArgb(alpha, 68, 128, 71);
midColor = Color.FromArgb(alpha, 43, 91, 30);
highColor = Color.FromArgb(alpha, 167, 220, 168);
break;
case ColorSchemeType.Valley_Fires:
lowColor = Color.FromArgb(alpha, 164, 0, 0);
midColor = Color.FromArgb(alpha, 255, 128, 64);
highColor = Color.FromArgb(alpha, 255, 255, 191);
break;
case ColorSchemeType.DeadSea:
lowColor = Color.FromArgb(alpha, 51, 137, 208);
midColor = Color.FromArgb(alpha, 226, 227, 166);
highColor = Color.FromArgb(alpha, 151, 146, 117);
break;
case ColorSchemeType.Highway:
lowColor = Color.FromArgb(alpha, 51, 137, 208);
midColor = Color.FromArgb(alpha, 214, 207, 124);
highColor = Color.FromArgb(alpha, 54, 152, 69);
break;
default:
lowColor = midColor = highColor = Color.Transparent;
break;
}
if (eqCat != null)
{
eqCat.LowColor = eqCat.HighColor = lowColor;
}
else
{
Debug.Assert(low != null);
Debug.Assert(high != null);
low.LowColor = lowColor;
low.HighColor = midColor;
high.LowColor = midColor;
high.HighColor = highColor;
}
OnItemChanged(this);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the floating point value for the opacity
/// </summary>
[Serialize("Opacity")]
public float Opacity
{
get { return _opacity; }
set { _opacity = value; }
}
/// <summary>
/// Gets or sets the raster categories
/// </summary>
[Serialize("Categories")]
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ColorCategoryCollection Categories
{
get { return _categories; }
set
{
if (_categories != null) _categories.Scheme = null;
_categories = value;
if (_categories != null) _categories.Scheme = this;
}
}
/// <summary>
/// Gets or sets the raster editor settings associated with this scheme.
/// </summary>
[Serialize("EditorSettings")]
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new RasterEditorSettings EditorSettings
{
get { return base.EditorSettings as RasterEditorSettings; }
set { base.EditorSettings = value; }
}
/// <summary>
/// Uses the settings on this scheme to create a random category.
/// </summary>
/// <returns>A new IFeatureCategory</returns>
public override ICategory CreateRandomCategory()
{
Random rnd = new Random(DateTime.Now.Millisecond);
return CreateNewCategory(CreateRandomColor(rnd), 20);
}
/// <summary>
/// Occurs when setting the parent item and updates the parent item pointers
/// </summary>
/// <param name="value"></param>
protected override void OnSetParentItem(ILegendItem value)
{
base.OnSetParentItem(value);
_categories.UpdateItemParentPointers();
}
#endregion
#region IColorScheme Members
/// <summary>
/// Draws the category in the specified location.
/// </summary>
/// <param name="index"></param>
/// <param name="g"></param>
/// <param name="bounds"></param>
public override void DrawCategory(int index, Graphics g, Rectangle bounds)
{
_categories[index].LegendSymbol_Painted(g, bounds);
}
/// <summary>
/// Adds the specified category
/// </summary>
/// <param name="category"></param>
public override void AddCategory(ICategory category)
{
IColorCategory cc = category as IColorCategory;
if (cc != null) _categories.Add(cc);
}
/// <summary>
/// Attempts to decrease the index value of the specified category, and returns
/// true if the move was successful.
/// </summary>
/// <param name="category">The category to decrease the index of</param>
/// <returns></returns>
public override bool DecreaseCategoryIndex(ICategory category)
{
IColorCategory cc = category as IColorCategory;
return cc != null && _categories.DecreaseIndex(cc);
}
/// <summary>
/// Removes the specified category
/// </summary>
/// <param name="category"></param>
public override void RemoveCategory(ICategory category)
{
IColorCategory cc = category as IColorCategory;
if (cc != null) _categories.Remove(cc);
}
/// <summary>
/// Inserts the item at the specified index
/// </summary>
/// <param name="index"></param>
/// <param name="category"></param>
public override void InsertCategory(int index, ICategory category)
{
IColorCategory cc = category as IColorCategory;
if (cc != null) _categories.Insert(index, cc);
}
/// <summary>
/// Attempts to increase the position of the specified category, and returns true
/// if the index increase was successful.
/// </summary>
/// <param name="category">The category to increase the position of</param>
/// <returns>Boolean, true if the item's position was increased</returns>
public override bool IncreaseCategoryIndex(ICategory category)
{
IColorCategory cc = category as IColorCategory;
return cc != null && _categories.IncreaseIndex(cc);
}
/// <summary>
/// Suspends the change item event from firing as the list is being changed
/// </summary>
public override void SuspendEvents()
{
_categories.SuspendEvents();
}
/// <summary>
/// Allows the ChangeItem event to get passed on when changes are made
/// </summary>
public override void ResumeEvents()
{
_categories.ResumeEvents();
}
/// <summary>
/// Clears the categories
/// </summary>
public override void ClearCategories()
{
_categories.Clear();
}
#endregion
}
}
| |
namespace Flower
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Flower.Workers;
using Flower.Works;
public sealed class WorkRegistry : IWorkRegistry, IActivatable, ISuspendable
{
private readonly IList<IWork> works = new List<IWork>();
public WorkRegistry(WorkOptions options = null)
{
Options = options ?? WorkOptions.Default;
}
public IEnumerable<IWork> Works => works;
public WorkOptions Options { get; }
public IActionWork RegisterMethod<TInput>(
IObservable<TInput> trigger,
Func<Task> worker,
WorkOptions options = null)
{
return RegisterFactory(trigger, () => WorkerScope.FromInstance(new Worker(worker)), options);
}
public IActionWork<TInput> RegisterMethod<TInput>(
IObservable<TInput> trigger,
Func<TInput, Task> worker,
WorkOptions options = null)
{
return RegisterFactory(trigger, WorkerScope.FromInstance(new Worker<TInput>(worker)), options);
}
public IFuncWork<TInput, TOutput> RegisterMethod<TInput, TOutput>(
IObservable<TInput> trigger,
Func<TInput, Task<TOutput>> worker,
WorkOptions options = null)
{
return RegisterFactory(trigger, WorkerScope.FromInstance(new Worker<TInput, TOutput>(worker)), options);
}
public IActionWork RegisterWorker<TInput>(
IObservable<TInput> trigger,
IWorker worker,
WorkOptions options = null)
{
return RegisterFactory(trigger, () => WorkerScope.FromInstance(worker), options);
}
public IActionWork<TInput> RegisterWorker<TInput>(
IObservable<TInput> trigger,
IWorker<TInput> worker,
WorkOptions options = null)
{
return RegisterFactory(trigger, WorkerScope.FromInstance(worker), options);
}
public IFuncWork<TInput, TOutput> RegisterWorker<TInput, TOutput>(
IObservable<TInput> trigger,
IWorker<TInput, TOutput> worker,
WorkOptions options = null)
{
return RegisterFactory(trigger, WorkerScope.FromInstance(worker), options);
}
public IActionWork RegisterResolver<TInput>(
IObservable<TInput> trigger,
IWorkerResolver resolver,
WorkOptions options = null)
{
return RegisterFactory(trigger, () => WorkerScope.FromResolver(resolver), options);
}
public IActionWork<TInput> RegisterResolver<TInput>(
IObservable<TInput> trigger,
IWorkerResolver<TInput> resolver,
WorkOptions options = null)
{
return RegisterFactory(trigger, () => WorkerScope.FromResolver(resolver), options);
}
public IFuncWork<TInput, TOutput> RegisterResolver<TInput, TOutput>(
IObservable<TInput> trigger,
IWorkerResolver<TInput, TOutput> resolver,
WorkOptions options = null)
{
return RegisterFactory(trigger, () => WorkerScope.FromResolver(resolver), options);
}
public void Activate()
{
foreach (var work in works.Reverse())
{
work.Activate();
}
}
public void Suspend()
{
foreach (var work in works)
{
work.Suspend();
}
}
public void Complete(IWork work)
{
if (work == null) throw new ArgumentNullException(nameof(work));
if (!works.Contains(work))
{
throw new InvalidOperationException(
"Cannot complete work that is not contained in this work registry.");
}
work.Suspend();
Remove(work);
work.Complete();
}
public void CompleteAll()
{
foreach (var work in works.Reverse().ToList())
{
Complete(work);
}
}
public IActionWork RegisterFactory<TInput>(
IObservable<TInput> trigger,
Func<IScope<IWorker>> factory,
WorkOptions options = null)
{
options = CreateRegisterOptions(options);
var registration = CreateRegistration(trigger, factory, options);
var work = new ActionWork(registration);
Register(work);
return work;
}
public IActionWork<TInput> RegisterFactory<TInput>(
IObservable<TInput> trigger,
Func<IScope<IWorker<TInput>>> factory,
WorkOptions options = null)
{
options = CreateRegisterOptions(options);
var registration = CreateRegistration(trigger, factory, options);
var work = new ActionWork<TInput>(registration);
Register(work);
return work;
}
public IFuncWork<TInput, TOutput> RegisterFactory<TInput, TOutput>(
IObservable<TInput> trigger,
Func<IScope<IWorker<TInput, TOutput>>> factory,
WorkOptions options = null)
{
options = CreateRegisterOptions(options);
var registration = CreateRegistration(trigger, factory, options);
var work = new FuncWork<TInput, TOutput>(registration);
Register(work);
return work;
}
private WorkOptions CreateRegisterOptions(WorkOptions options)
{
return options ?? new WorkOptions(Options);
}
private ActionWorkRegistration CreateRegistration<TInput>(
IObservable<TInput> trigger,
Func<IScope<IWorker>> createWorkerScope,
WorkOptions options)
{
return new ActionWorkRegistration(
this,
trigger.Select(input => (object) input),
createWorkerScope,
options);
}
private ActionWorkRegistration<TInput> CreateRegistration<TInput>(
IObservable<TInput> trigger,
Func<IScope<IWorker<TInput>>> createWorkerScope,
WorkOptions options)
{
return new ActionWorkRegistration<TInput>(this, trigger, createWorkerScope, options);
}
private FuncWorkRegistration<TInput, TOutput> CreateRegistration<TInput, TOutput>(
IObservable<TInput> trigger,
Func<IScope<IWorker<TInput, TOutput>>> createWorkerScope,
WorkOptions options)
{
return new FuncWorkRegistration<TInput, TOutput>(this, trigger, createWorkerScope, options);
}
private void Register(IWork work)
{
Add(work);
if (Options.WorkRegisterMode == WorkRegisterMode.Activated)
{
work.Activate();
}
}
private void Add<TWork>(TWork work) where TWork : IWork
{
works.Add(work);
}
private void Remove(IWork work)
{
works.Remove(work);
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System.Collections.Generic;
namespace DotSpatial.Data
{
/// <summary>
/// A named list preserves a 1:1 mapping between names and items. It can be used to
/// reference information in either direction. It essentially provides a string
/// handle for working with generic typed ILists. This cannot instantiate new
/// items. (Creating a default T would not work, for instance, for an interface).
/// </summary>
/// <typeparam name="T">Type of the contained items.</typeparam>
public class NamedList<T> : INamedList
{
#region Fields
private readonly Dictionary<string, T> _items; // search by name
private readonly Dictionary<T, string> _names; // search by item
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="NamedList{T}"/> class.
/// </summary>
public NamedList()
{
Items = new List<T>(); // default setting
_items = new Dictionary<string, T>();
_names = new Dictionary<T, string>();
}
/// <summary>
/// Initializes a new instance of the <see cref="NamedList{T}"/> class.
/// </summary>
/// <param name="values">The values to use for the content.</param>
public NamedList(IList<T> values)
{
Items = values;
_items = new Dictionary<string, T>();
_names = new Dictionary<T, string>();
RefreshNames();
}
/// <summary>
/// Initializes a new instance of the <see cref="NamedList{T}"/> class.
/// </summary>
/// <param name="values">The values to use for the content.</param>
/// <param name="baseName">The string that should precede the numbering to describe the individual items.</param>
public NamedList(IList<T> values, string baseName)
{
Items = values;
_items = new Dictionary<string, T>();
_names = new Dictionary<T, string>();
BaseName = baseName;
RefreshNames();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the base name to use for naming items.
/// </summary>
public string BaseName { get; set; }
/// <summary>
/// Gets the count of the items in the list.
/// </summary>
public int Count => _items.Count;
/// <summary>
/// Gets or sets the list of actual items. This is basically a reference copy of
/// the actual collection of items to be contained in this named list.
/// </summary>
public IList<T> Items { get; set; }
#endregion
#region Indexers
/// <summary>
/// Gets or sets the item corresponding to the specified name. Setting this
/// will re-use the same name and position in the list, but set a new object.
/// </summary>
/// <param name="name">The string name of the item to obtain.</param>
/// <returns>The item of type T corresponding to the specified name.</returns>
public T this[string name]
{
get
{
return _items.ContainsKey(name) ? _items[name] : default(T);
}
set
{
T oldItem = _items[name];
_names.Remove(oldItem);
int index = Items.IndexOf(oldItem);
Items.RemoveAt(index);
Items.Insert(index, value);
_items[name] = value;
_names.Add(value, name);
}
}
#endregion
#region Methods
/// <summary>
/// Re-orders the list so that the index of the specifeid item is lower,
/// and threfore will be drawn earlier, and therefore should appear
/// in a lower position on the list.
/// </summary>
/// <param name="name">name of the item that gets demoted.</param>
public void Demote(string name)
{
Demote(_items[name]);
}
/// <summary>
/// Re-orders the list so that this item appears closer to the 0 index.
/// </summary>
/// <param name="item">Item that gets demoted.</param>
public void Demote(T item)
{
int index = Items.IndexOf(item);
if (index == -1 || index == 0) return;
Items.RemoveAt(index);
Items.Insert(index - 1, item);
}
/// <summary>
/// Gets the item with the specified name as an object.
/// This enables the INamedList to work with items even
/// if it doesn't know the strong type.
/// </summary>
/// <param name="name">The string name of the item to retrieve.</param>
/// <returns>The actual item cast as an object.</returns>
public object GetItem(string name)
{
return this[name];
}
/// <summary>
/// Gets the string name for the specified item.
/// </summary>
/// <param name="item">The item of type T to find the name for.</param>
/// <returns>The string name corresponding to the specified item.</returns>
public string GetName(T item)
{
return _names.ContainsKey(item) ? _names[item] : null;
}
/// <summary>
/// Gets the name of the item corresponding.
/// </summary>
/// <param name="value">The item cast as an object.</param>
/// <returns>The string name of the specified object, or null if the cast fails.</returns>
public string GetNameOfObject(object value)
{
T item = Global.SafeCastTo<T>(value);
return item == null ? null : GetName(item);
}
/// <summary>
/// Gets the list of names for the items currently stored in the list,
/// in the sequence defined by the list of items.
/// </summary>
/// <returns>The list of names.</returns>
public string[] GetNames()
{
List<string> result = new List<string>();
foreach (T item in Items)
{
if (!_names.ContainsKey(item))
{
RefreshNames();
break;
}
}
foreach (T item in Items)
{
result.Add(_names[item]);
}
return result.ToArray();
}
/// <summary>
/// Re-orders the list so that the index of the specified item is higher,
/// and therefore will be drawn later, and therefore should appear
/// in a higher position on the list.
/// </summary>
/// <param name="name">Name of the item that gets promoted.</param>
public void Promote(string name)
{
Promote(_items[name]);
}
/// <summary>
/// Re-orders the list so that the index of the specified item is higher,
/// and therefore will be drawn later, and therefore should appear
/// in a higher position on the list.
/// </summary>
/// <param name="item">Item that gets promoted.</param>
public void Promote(T item)
{
int index = Items.IndexOf(item);
if (index == -1) return;
if (index == Items.Count - 1) return;
Items.RemoveAt(index);
Items.Insert(index + 1, item);
}
/// <summary>
/// Updates the names to match the current set of actual items.
/// </summary>
public void RefreshNames()
{
// When re-ordering, we want to keep the name like category 0 the same,
// so we can't just clear the values. Instead, to see the item move,
// the name has to stay with the item.
List<T> deleteItems = new List<T>();
foreach (T item in _names.Keys)
{
if (Items.Contains(item) == false)
{
deleteItems.Add(item);
}
}
foreach (T item in deleteItems)
{
_names.Remove(item);
}
List<string> deleteNames = new List<string>();
foreach (string name in _items.Keys)
{
if (_names.ContainsValue(name) == false)
{
deleteNames.Add(name);
}
}
foreach (string name in deleteNames)
{
_items.Remove(name);
}
foreach (T item in Items)
{
if (!_names.ContainsKey(item))
{
string name = BaseName + 0;
int i = 1;
while (_items.ContainsKey(name))
{
name = BaseName + i;
i++;
}
_names.Add(item, name);
_items.Add(name, item);
}
}
}
/// <summary>
/// Removes the item with the specified name from the list.
/// </summary>
/// <param name="name">The string name of the item to remove.</param>
public void Remove(string name)
{
Remove(_items[name]);
}
/// <summary>
/// Removes the specified item.
/// </summary>
/// <param name="item">The item to remove.</param>
public void Remove(T item)
{
Items.Remove(item);
RefreshNames();
}
#endregion
}
}
| |
namespace Schema.NET;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A single or list of values which can be any of the specified types.
/// </summary>
/// <typeparam name="T1">The first type the values can take.</typeparam>
/// <typeparam name="T2">The second type the values can take.</typeparam>
/// <typeparam name="T3">The third type the values can take.</typeparam>
public readonly struct Values<T1, T2, T3>
: IReadOnlyCollection<object?>, IEnumerable<object?>, IValues, IEquatable<Values<T1, T2, T3>>
{
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3}"/> struct.
/// </summary>
/// <param name="value">The value of type <typeparamref name="T1"/>.</param>
public Values(OneOrMany<T1> value)
{
this.Value1 = value;
this.Value2 = default;
this.Value3 = default;
this.HasValue1 = value.Count > 0;
this.HasValue2 = false;
this.HasValue3 = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3}"/> struct.
/// </summary>
/// <param name="value">The value of type <typeparamref name="T2"/>.</param>
public Values(OneOrMany<T2> value)
{
this.Value1 = default;
this.Value2 = value;
this.Value3 = default;
this.HasValue1 = false;
this.HasValue2 = value.Count > 0;
this.HasValue3 = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3}"/> struct.
/// </summary>
/// <param name="value">The value of type <typeparamref name="T3"/>.</param>
public Values(OneOrMany<T3> value)
{
this.Value1 = default;
this.Value2 = default;
this.Value3 = value;
this.HasValue1 = false;
this.HasValue2 = false;
this.HasValue3 = value.Count > 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3}"/> struct.
/// </summary>
/// <param name="items">The items.</param>
public Values(params object[] items)
: this(items.AsEnumerable())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3}"/> struct.
/// </summary>
/// <param name="items">The items.</param>
public Values(IEnumerable<object> items)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(items);
#else
if (items is null)
{
throw new ArgumentNullException(nameof(items));
}
#endif
List<T1>? items1 = null;
List<T2>? items2 = null;
List<T3>? items3 = null;
foreach (var item in items)
{
if (item is T3 itemT3)
{
if (items3 == null)
{
items3 = new List<T3>();
}
items3.Add(itemT3);
}
else if (item is T2 itemT2)
{
if (items2 == null)
{
items2 = new List<T2>();
}
items2.Add(itemT2);
}
else if (item is T1 itemT1)
{
if (items1 == null)
{
items1 = new List<T1>();
}
items1.Add(itemT1);
}
}
this.HasValue1 = items1?.Count > 0;
this.HasValue2 = items2?.Count > 0;
this.HasValue3 = items3?.Count > 0;
this.Value1 = items1 == null ? default : (OneOrMany<T1>)items1;
this.Value2 = items2 == null ? default : (OneOrMany<T2>)items2;
this.Value3 = items3 == null ? default : (OneOrMany<T3>)items3;
}
/// <summary>
/// Gets the number of elements contained in the <see cref="Values{T1,T2,T3}"/>.
/// </summary>
public int Count => this.Value1.Count + this.Value2.Count + this.Value3.Count;
/// <summary>
/// Gets a value indicating whether this instance has a value.
/// </summary>
public bool HasValue => this.HasValue1 || this.HasValue2 || this.HasValue3;
/// <summary>
/// Gets a value indicating whether the value of type <typeparamref name="T1" /> has a value.
/// </summary>
public bool HasValue1 { get; }
/// <summary>
/// Gets a value indicating whether the value of type <typeparamref name="T2" /> has a value.
/// </summary>
public bool HasValue2 { get; }
/// <summary>
/// Gets a value indicating whether the value of type <typeparamref name="T3" /> has a value.
/// </summary>
public bool HasValue3 { get; }
/// <summary>
/// Gets the value of type <typeparamref name="T1" />.
/// </summary>
public OneOrMany<T1> Value1 { get; }
/// <summary>
/// Gets the value of type <typeparamref name="T2" />.
/// </summary>
public OneOrMany<T2> Value2 { get; }
/// <summary>
/// Gets the value of type <typeparamref name="T3" />.
/// </summary>
public OneOrMany<T3> Value3 { get; }
#pragma warning disable CA1002 // Do not expose generic lists
#pragma warning disable CA2225 // Operator overloads have named alternates
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T1"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="item">The single item value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(T1 item) => new(item);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T2"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="item">The single item value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(T2 item) => new(item);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T3"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="item">The single item value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(T3 item) => new(item);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T1[]"/> to <see cref="Values{T1,T2,T3}"/>.
/// </summary>
/// <param name="array">The array of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(T1[] array) => new(array);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T2[]"/> to <see cref="Values{T1,T2,T3}"/>.
/// </summary>
/// <param name="array">The array of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(T2[] array) => new(array);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T3[]"/> to <see cref="Values{T1,T2,T3}"/>.
/// </summary>
/// <param name="array">The array of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(T3[] array) => new(array);
/// <summary>
/// Performs an implicit conversion from <see cref="List{T1}"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="list">The list of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(List<T1> list) => new(list);
/// <summary>
/// Performs an implicit conversion from <see cref="List{T2}"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="list">The list of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(List<T2> list) => new(list);
/// <summary>
/// Performs an implicit conversion from <see cref="List{T3}"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="list">The list of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(List<T3> list) => new(list);
/// <summary>
/// Performs an implicit conversion from <see cref="object"/> array to <see cref="Values{T1,T2,T3}"/>.
/// </summary>
/// <param name="array">The array of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(object[] array) => new(array);
/// <summary>
/// Performs an implicit conversion from <see cref="List{Object}"/> to <see cref="Values{T1,T2,T3}"/>.
/// </summary>
/// <param name="list">The list of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3>(List<object> list) => new(list);
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3}"/> to the first item of type <typeparamref name="T1"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T1?(Values<T1, T2, T3> values) => values.Value1.FirstOrDefault();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3}"/> to the first item of type <typeparamref name="T2"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T2?(Values<T1, T2, T3> values) => values.Value2.FirstOrDefault();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3}"/> to the first item of type <typeparamref name="T3"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T3?(Values<T1, T2, T3> values) => values.Value3.FirstOrDefault();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3}"/> to an array of <typeparamref name="T1"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T1[](Values<T1, T2, T3> values) => values.Value1.ToArray();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3}"/> to <see cref="List{T1}"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator List<T1>(Values<T1, T2, T3> values) => values.Value1.ToList();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3}"/> to an array of <typeparamref name="T2"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T2[](Values<T1, T2, T3> values) => values.Value2.ToArray();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3}"/> to <see cref="List{T2}"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator List<T2>(Values<T1, T2, T3> values) => values.Value2.ToList();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3}"/> to an array of <typeparamref name="T3"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T3[](Values<T1, T2, T3> values) => values.Value3.ToArray();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3}"/> to <see cref="List{T3}"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator List<T3>(Values<T1, T2, T3> values) => values.Value3.ToList();
#pragma warning restore CA2225 // Operator overloads have named alternates
#pragma warning restore CA1002 // Do not expose generic lists
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator ==(Values<T1, T2, T3> left, Values<T1, T2, T3> right) => left.Equals(right);
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator !=(Values<T1, T2, T3> left, Values<T1, T2, T3> right) => !(left == right);
/// <summary>Deconstructs the specified items.</summary>
/// <param name="items1">The items from value 1.</param>
/// <param name="items2">The items from value 2.</param>
/// <param name="items3">The items from value 3.</param>
public void Deconstruct(out IEnumerable<T1> items1, out IEnumerable<T2> items2, out IEnumerable<T3> items3)
{
items1 = this.Value1;
items2 = this.Value2;
items3 = this.Value3;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<object?> GetEnumerator()
{
if (this.HasValue1)
{
foreach (var item1 in this.Value1)
{
yield return item1;
}
}
if (this.HasValue2)
{
foreach (var item2 in this.Value2)
{
yield return item2;
}
}
if (this.HasValue3)
{
foreach (var item3 in this.Value3)
{
yield return item3;
}
}
}
/// <summary>Returns an enumerator that iterates through a collection.</summary>
/// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.
/// </returns>
public bool Equals(Values<T1, T2, T3> other)
{
if (!other.HasValue && !this.HasValue)
{
return true;
}
return this.Value1.Equals(other.Value1) &&
this.Value2.Equals(other.Value2) &&
this.Value3.Equals(other.Value3);
}
/// <summary>
/// Determines whether the specified <see cref="object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object? obj) => obj is Values<T1, T2, T3> values && this.Equals(values);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode() => HashCode.Of(this.Value1).And(this.Value2).And(this.Value3);
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.IO;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
///<summary>
/// This is the object used by Runspace,pipeline,host to send data
/// to remote end. Transport layer owns breaking this into fragments
/// and sending to other end
///</summary>
internal class RemoteDataObject<T>
{
#region Private Members
private const int destinationOffset = 0;
private const int dataTypeOffset = 4;
private const int rsPoolIdOffset = 8;
private const int psIdOffset = 24;
private const int headerLength = 4 + 4 + 16 + 16;
private const int SessionMask = 0x00010000;
private const int RunspacePoolMask = 0x00021000;
private const int PowerShellMask = 0x00041000;
#endregion Private Members
#region Constructors
/// <summary>
/// Constructs a RemoteDataObject from its
/// individual components.
/// </summary>
/// <param name="destination">
/// Destination this object is going to.
/// </param>
/// <param name="dataType">
/// Payload type this object represents.
/// </param>
/// <param name="runspacePoolId">
/// Runspace id this object belongs to.
/// </param>
/// <param name="powerShellId">
/// PowerShell (pipeline) id this object belongs to.
/// This may be null if the payload belongs to runspace.
/// </param>
/// <param name="data">
/// Actual payload.
/// </param>
protected RemoteDataObject(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
T data)
{
Destination = destination;
DataType = dataType;
RunspacePoolId = runspacePoolId;
PowerShellId = powerShellId;
Data = data;
}
#endregion Constructors
#region Properties
internal RemotingDestination Destination { get; }
/// <summary>
/// Gets the target (Runspace / Pipeline / Powershell / Host)
/// the payload belongs to.
/// </summary>
internal RemotingTargetInterface TargetInterface
{
get
{
int dt = (int)DataType;
// get the most used ones in the top.
if ((dt & PowerShellMask) == PowerShellMask)
{
return RemotingTargetInterface.PowerShell;
}
if ((dt & RunspacePoolMask) == RunspacePoolMask)
{
return RemotingTargetInterface.RunspacePool;
}
if ((dt & SessionMask) == SessionMask)
{
return RemotingTargetInterface.Session;
}
return RemotingTargetInterface.InvalidTargetInterface;
}
}
internal RemotingDataType DataType { get; }
internal Guid RunspacePoolId { get; }
internal Guid PowerShellId { get; }
internal T Data { get; }
#endregion Properties
/// <summary>
///
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
/// <returns></returns>
internal static RemoteDataObject<T> CreateFrom(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
T data)
{
return new RemoteDataObject<T>(destination, dataType, runspacePoolId, powerShellId, data);
}
/// <summary>
/// Creates a RemoteDataObject by deserialzing <paramref name="data"/>.
/// </summary>
/// <param name="serializedDataStream"></param>
/// <param name="defragmentor">
/// Defragmetor used to deserialize an object.
/// </param>
/// <returns></returns>
internal static RemoteDataObject<T> CreateFrom(Stream serializedDataStream, Fragmentor defragmentor)
{
Dbg.Assert(null != serializedDataStream, "cannot construct a RemoteDataObject from null data");
Dbg.Assert(null != defragmentor, "defragmentor cannot be null.");
if ((serializedDataStream.Length - serializedDataStream.Position) < headerLength)
{
PSRemotingTransportException e =
new PSRemotingTransportException(PSRemotingErrorId.NotEnoughHeaderForRemoteDataObject,
RemotingErrorIdStrings.NotEnoughHeaderForRemoteDataObject,
headerLength + FragmentedRemoteObject.HeaderLength);
throw e;
}
RemotingDestination destination = (RemotingDestination)DeserializeUInt(serializedDataStream);
RemotingDataType dataType = (RemotingDataType)DeserializeUInt(serializedDataStream);
Guid runspacePoolId = DeserializeGuid(serializedDataStream);
Guid powerShellId = DeserializeGuid(serializedDataStream);
object actualData = null;
if ((serializedDataStream.Length - headerLength) > 0)
{
actualData = defragmentor.DeserializeToPSObject(serializedDataStream);
}
T deserializedObject = (T)LanguagePrimitives.ConvertTo(actualData, typeof(T),
System.Globalization.CultureInfo.CurrentCulture);
return new RemoteDataObject<T>(destination, dataType, runspacePoolId, powerShellId, deserializedObject);
}
#region Serialize / Deserialize
/// <summary>
/// Seriliazes the object into the stream specified. The serialization mechanism uses
/// UTF8 encoding to encode data.
/// </summary>
/// <param name="streamToWriteTo"></param>
/// <param name="fragmentor">
/// fragmentor used to serialize and fragment the object.
/// </param>
internal virtual void Serialize(Stream streamToWriteTo, Fragmentor fragmentor)
{
Dbg.Assert(null != streamToWriteTo, "Stream to write to cannot be null.");
Dbg.Assert(null != fragmentor, "Fragmentor cannot be null.");
SerializeHeader(streamToWriteTo);
if (null != Data)
{
fragmentor.SerializeToBytes(Data, streamToWriteTo);
}
return;
}
/// <summary>
/// Serializes only the header portion of the object. ie., runspaceId,
/// powerShellId, destinaion and dataType.
/// </summary>
/// <param name="streamToWriteTo">
/// place where the serialized data is stored into.
/// </param>
/// <returns></returns>
private void SerializeHeader(Stream streamToWriteTo)
{
Dbg.Assert(null != streamToWriteTo, "stream to write to cannot be null");
// Serialize destination
SerializeUInt((uint)Destination, streamToWriteTo);
// Serialize data type
SerializeUInt((uint)DataType, streamToWriteTo);
// Serialize runspace guid
SerializeGuid(RunspacePoolId, streamToWriteTo);
// Serialize powershell guid
SerializeGuid(PowerShellId, streamToWriteTo);
return;
}
private void SerializeUInt(uint data, Stream streamToWriteTo)
{
Dbg.Assert(null != streamToWriteTo, "stream to write to cannot be null");
byte[] result = new byte[4]; // size of int
int idx = 0;
result[idx++] = (byte)(data & 0xFF);
result[idx++] = (byte)((data >> 8) & 0xFF);
result[idx++] = (byte)((data >> (2 * 8)) & 0xFF);
result[idx++] = (byte)((data >> (3 * 8)) & 0xFF);
streamToWriteTo.Write(result, 0, 4);
}
private static uint DeserializeUInt(Stream serializedDataStream)
{
Dbg.Assert(serializedDataStream.Length >= 4, "Not enough data to get Int.");
uint result = 0;
result |= (((uint)(serializedDataStream.ReadByte())) & 0xFF);
result |= (((uint)(serializedDataStream.ReadByte() << 8)) & 0xFF00);
result |= (((uint)(serializedDataStream.ReadByte() << (2 * 8))) & 0xFF0000);
result |= (((uint)(serializedDataStream.ReadByte() << (3 * 8))) & 0xFF000000);
return result;
}
private void SerializeGuid(Guid guid, Stream streamToWriteTo)
{
Dbg.Assert(null != streamToWriteTo, "stream to write to cannot be null");
byte[] guidArray = guid.ToByteArray();
streamToWriteTo.Write(guidArray, 0, guidArray.Length);
}
private static Guid DeserializeGuid(Stream serializedDataStream)
{
Dbg.Assert(serializedDataStream.Length >= 16, "Not enough data to get Guid.");
byte[] guidarray = new byte[16]; // Size of GUID.
for (int idx = 0; idx < 16; idx++)
{
guidarray[idx] = (byte)serializedDataStream.ReadByte();
}
return new Guid(guidarray);
}
#endregion
}
internal class RemoteDataObject : RemoteDataObject<object>
{
#region Constructors / Factory
/// <summary>
///
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
private RemoteDataObject(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
object data) : base(destination, dataType, runspacePoolId, powerShellId, data)
{
}
/// <summary>
///
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
/// <returns></returns>
internal new static RemoteDataObject CreateFrom(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
object data)
{
return new RemoteDataObject(destination, dataType, runspacePoolId,
powerShellId, data);
}
#endregion Constructors
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SelectManyQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// SelectMany is effectively a nested loops join. It is given two data sources, an
/// outer and an inner -- actually, the inner is sometimes calculated by invoking a
/// function for each outer element -- and we walk the outer, walking the entire
/// inner enumerator for each outer element. There is an optional result selector
/// function which can transform the output before yielding it as a result element.
///
/// Notes:
/// Although select many takes two enumerable objects as input, it appears to the
/// query analysis infrastructure as a unary operator. That's because it works a
/// little differently than the other binary operators: it has to re-open the right
/// child every time an outer element is walked. The right child is NOT partitioned.
/// </summary>
/// <typeparam name="TLeftInput"></typeparam>
/// <typeparam name="TRightInput"></typeparam>
/// <typeparam name="TOutput"></typeparam>
internal sealed class SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> : UnaryQueryOperator<TLeftInput, TOutput>
{
private readonly Func<TLeftInput, IEnumerable<TRightInput>>? _rightChildSelector; // To select a new child each iteration.
private readonly Func<TLeftInput, int, IEnumerable<TRightInput>>? _indexedRightChildSelector; // To select a new child each iteration.
private readonly Func<TLeftInput, TRightInput, TOutput>? _resultSelector; // An optional result selection function.
private bool _prematureMerge = false; // Whether to prematurely merge the input of this operator.
private bool _limitsParallelism = false; // Whether to prematurely merge the input of this operator.
//---------------------------------------------------------------------------------------
// Initializes a new select-many operator.
//
// Arguments:
// leftChild - the left data source from which to pull data.
// rightChild - the right data source from which to pull data.
// rightChildSelector - if no right data source was supplied, the selector function
// will generate a new right child for every unique left element.
// resultSelector - a selection function for creating output elements.
//
internal SelectManyQueryOperator(IEnumerable<TLeftInput> leftChild,
Func<TLeftInput, IEnumerable<TRightInput>>? rightChildSelector,
Func<TLeftInput, int, IEnumerable<TRightInput>>? indexedRightChildSelector,
Func<TLeftInput, TRightInput, TOutput>? resultSelector)
: base(leftChild)
{
Debug.Assert(leftChild != null, "left child data source cannot be null");
Debug.Assert(rightChildSelector != null || indexedRightChildSelector != null,
"either right child data or selector must be supplied");
Debug.Assert(rightChildSelector == null || indexedRightChildSelector == null,
"either indexed- or non-indexed child selector must be supplied (not both)");
Debug.Assert(typeof(TRightInput) == typeof(TOutput) || resultSelector != null,
"right input and output must be the same types, otherwise the result selector may not be null");
_rightChildSelector = rightChildSelector;
_indexedRightChildSelector = indexedRightChildSelector;
_resultSelector = resultSelector;
// If the SelectMany is indexed, elements must be returned in the order in which
// indices were assigned.
_outputOrdered = Child.OutputOrdered || indexedRightChildSelector != null;
InitOrderIndex();
}
private void InitOrderIndex()
{
OrdinalIndexState childIndexState = Child.OrdinalIndexState;
if (_indexedRightChildSelector != null)
{
// If this is an indexed SelectMany, we need the order keys to be Correct, so that we can pass them
// into the user delegate.
_prematureMerge = ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct);
_limitsParallelism = _prematureMerge && childIndexState != OrdinalIndexState.Shuffled;
}
else
{
if (OutputOrdered)
{
// If the output of this SelectMany is ordered, the input keys must be at least increasing. The
// SelectMany algorithm assumes that there will be no duplicate order keys, so if the order keys
// are Shuffled, we need to merge prematurely.
_prematureMerge = ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Increasing);
}
}
SetOrdinalIndexState(OrdinalIndexState.Increasing);
}
internal override void WrapPartitionedStream<TLeftKey>(
PartitionedStream<TLeftInput, TLeftKey> inputStream, IPartitionedStreamRecipient<TOutput> recipient, bool preferStriping, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
if (_indexedRightChildSelector != null)
{
PartitionedStream<TLeftInput, int> inputStreamInt;
// If the index is not correct, we need to reindex.
if (_prematureMerge)
{
ListQueryResults<TLeftInput> listResults =
QueryOperator<TLeftInput>.ExecuteAndCollectResults(inputStream, partitionCount, OutputOrdered, preferStriping, settings);
inputStreamInt = listResults.GetPartitionedStream();
}
else
{
inputStreamInt = (PartitionedStream<TLeftInput, int>)(object)inputStream;
}
WrapPartitionedStreamIndexed(inputStreamInt, recipient, settings);
return;
}
//
//
if (_prematureMerge)
{
PartitionedStream<TLeftInput, int> inputStreamInt =
QueryOperator<TLeftInput>.ExecuteAndCollectResults(inputStream, partitionCount, OutputOrdered, preferStriping, settings)
.GetPartitionedStream();
WrapPartitionedStreamNotIndexed(inputStreamInt, recipient, settings);
}
else
{
WrapPartitionedStreamNotIndexed(inputStream, recipient, settings);
}
}
/// <summary>
/// A helper method for WrapPartitionedStream. We use the helper to reuse a block of code twice, but with
/// a different order key type. (If premature merge occurred, the order key type will be "int". Otherwise,
/// it will be the same type as "TLeftKey" in WrapPartitionedStream.)
/// </summary>
private void WrapPartitionedStreamNotIndexed<TLeftKey>(
PartitionedStream<TLeftInput, TLeftKey> inputStream, IPartitionedStreamRecipient<TOutput> recipient, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
var keyComparer = new PairComparer<TLeftKey, int>(inputStream.KeyComparer, Util.GetDefaultComparer<int>());
var outputStream = new PartitionedStream<TOutput, Pair<TLeftKey, int>>(partitionCount, keyComparer, OrdinalIndexState);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new SelectManyQueryOperatorEnumerator<TLeftKey>(inputStream[i], this, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
/// <summary>
/// Similar helper method to WrapPartitionedStreamNotIndexed, except that this one is for the indexed variant
/// of SelectMany (i.e., the SelectMany that passes indices into the user sequence-generating delegate)
/// </summary>
private void WrapPartitionedStreamIndexed(
PartitionedStream<TLeftInput, int> inputStream, IPartitionedStreamRecipient<TOutput> recipient, QuerySettings settings)
{
var keyComparer = new PairComparer<int, int>(inputStream.KeyComparer, Util.GetDefaultComparer<int>());
var outputStream = new PartitionedStream<TOutput, Pair<int, int>>(inputStream.PartitionCount, keyComparer, OrdinalIndexState);
for (int i = 0; i < inputStream.PartitionCount; i++)
{
outputStream[i] = new IndexedSelectManyQueryOperatorEnumerator(inputStream[i], this, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the left child and wrapping with a
// partition if needed. The right child is not opened yet -- this is always done on demand
// as the outer elements are enumerated.
//
internal override QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping)
{
QueryResults<TLeftInput> childQueryResults = Child.Open(settings, preferStriping);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TOutput> AsSequentialQuery(CancellationToken token)
{
if (_rightChildSelector != null)
{
if (_resultSelector != null)
{
return CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_rightChildSelector, _resultSelector);
}
return (IEnumerable<TOutput>)CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_rightChildSelector);
}
else
{
Debug.Assert(_indexedRightChildSelector != null);
if (_resultSelector != null)
{
return CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_indexedRightChildSelector, _resultSelector);
}
return (IEnumerable<TOutput>)CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_indexedRightChildSelector);
}
}
//---------------------------------------------------------------------------------------
// 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 _limitsParallelism; }
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for executing the SelectMany logic.
//
private class IndexedSelectManyQueryOperatorEnumerator : QueryOperatorEnumerator<TOutput, Pair<int, int>>
{
private readonly QueryOperatorEnumerator<TLeftInput, int> _leftSource; // The left data source to enumerate.
private readonly SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> _selectManyOperator; // The select many operator to use.
private IEnumerator<TRightInput>? _currentRightSource; // The current enumerator we're using.
private IEnumerator<TOutput>? _currentRightSourceAsOutput; // If we need to access the enumerator for output directly (no result selector).
private Mutables? _mutables; // bag of frequently mutated value types [allocate in moveNext to avoid false-sharing]
private readonly CancellationToken _cancellationToken;
private class Mutables
{
internal int _currentRightSourceIndex = -1; // The index for the right data source.
internal TLeftInput _currentLeftElement = default!; // The current element in the left data source.
internal int _currentLeftSourceIndex; // The current key in the left data source.
internal int _lhsCount; //counts the number of lhs elements enumerated. used for cancellation testing.
}
//---------------------------------------------------------------------------------------
// Instantiates a new select-many enumerator. Notice that the right data source is an
// enumera*BLE* not an enumera*TOR*. It is re-opened for every single element in the left
// data source.
//
internal IndexedSelectManyQueryOperatorEnumerator(QueryOperatorEnumerator<TLeftInput, int> leftSource,
SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> selectManyOperator,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(selectManyOperator != null);
_leftSource = leftSource;
_selectManyOperator = selectManyOperator;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Straightforward IEnumerator<T> methods.
//
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TOutput currentElement, ref Pair<int, int> currentKey)
{
while (true)
{
if (_currentRightSource == null)
{
_mutables = new Mutables();
// Check cancellation every few lhs-enumerations in case none of them are producing
// any outputs. Otherwise, we rely on the consumer of this operator to be performing the checks.
if ((_mutables._lhsCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We don't have a "current" right enumerator to use. We have to fetch the next
// one. If the left has run out of elements, however, we're done and just return
// false right away.
if (!_leftSource.MoveNext(ref _mutables._currentLeftElement!, ref _mutables._currentLeftSourceIndex))
{
return false;
}
Debug.Assert(_selectManyOperator._indexedRightChildSelector != null);
// Use the source selection routine to create a right child.
IEnumerable<TRightInput> rightChild =
_selectManyOperator._indexedRightChildSelector(_mutables._currentLeftElement, _mutables._currentLeftSourceIndex);
Debug.Assert(rightChild != null);
_currentRightSource = rightChild.GetEnumerator();
Debug.Assert(_currentRightSource != null);
// If we have no result selector, we will need to access the Current element of the right
// data source as though it is a TOutput. Unfortunately, we know that TRightInput must
// equal TOutput (we check it during operator construction), but the type system doesn't.
// Thus we would have to cast the result of invoking Current from type TRightInput to
// TOutput. This is no good, since the results could be value types. Instead, we save the
// enumerator object as an IEnumerator<TOutput> and access that later on.
if (_selectManyOperator._resultSelector == null)
{
_currentRightSourceAsOutput = (IEnumerator<TOutput>)_currentRightSource;
Debug.Assert(_currentRightSourceAsOutput == _currentRightSource,
"these must be equal, otherwise the surrounding logic will be broken");
}
}
if (_currentRightSource.MoveNext())
{
Debug.Assert(_mutables != null);
_mutables._currentRightSourceIndex++;
// If the inner data source has an element, we can yield it.
if (_selectManyOperator._resultSelector != null)
{
// In the case of a selection function, use that to yield the next element.
currentElement = _selectManyOperator._resultSelector(_mutables._currentLeftElement, _currentRightSource.Current);
}
else
{
// Otherwise, the right input and output types must be the same. We use the
// casted copy of the current right source and just return its current element.
Debug.Assert(_currentRightSourceAsOutput != null);
currentElement = _currentRightSourceAsOutput.Current;
}
currentKey = new Pair<int, int>(_mutables._currentLeftSourceIndex, _mutables._currentRightSourceIndex);
return true;
}
else
{
// Otherwise, we have exhausted the right data source. Loop back around and try
// to get the next left element, then its right, and so on.
_currentRightSource.Dispose();
_currentRightSource = null;
_currentRightSourceAsOutput = null;
}
}
}
protected override void Dispose(bool disposing)
{
_leftSource.Dispose();
if (_currentRightSource != null)
{
_currentRightSource.Dispose();
}
}
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for executing the SelectMany logic.
//
private class SelectManyQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TOutput, Pair<TLeftKey, int>>
{
private readonly QueryOperatorEnumerator<TLeftInput, TLeftKey> _leftSource; // The left data source to enumerate.
private readonly SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> _selectManyOperator; // The select many operator to use.
private IEnumerator<TRightInput>? _currentRightSource; // The current enumerator we're using.
private IEnumerator<TOutput>? _currentRightSourceAsOutput; // If we need to access the enumerator for output directly (no result selector).
private Mutables? _mutables; // bag of frequently mutated value types [allocate in moveNext to avoid false-sharing]
private readonly CancellationToken _cancellationToken;
private class Mutables
{
internal int _currentRightSourceIndex = -1; // The index for the right data source.
internal TLeftInput _currentLeftElement = default!; // The current element in the left data source.
internal TLeftKey _currentLeftKey = default!; // The current key in the left data source.
internal int _lhsCount; // Counts the number of lhs elements enumerated. used for cancellation testing.
}
//---------------------------------------------------------------------------------------
// Instantiates a new select-many enumerator. Notice that the right data source is an
// enumera*BLE* not an enumera*TOR*. It is re-opened for every single element in the left
// data source.
//
internal SelectManyQueryOperatorEnumerator(QueryOperatorEnumerator<TLeftInput, TLeftKey> leftSource,
SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> selectManyOperator,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(selectManyOperator != null);
_leftSource = leftSource;
_selectManyOperator = selectManyOperator;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Straightforward IEnumerator<T> methods.
//
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TOutput currentElement, ref Pair<TLeftKey, int> currentKey)
{
while (true)
{
if (_currentRightSource == null)
{
_mutables = new Mutables();
// Check cancellation every few lhs-enumerations in case none of them are producing
// any outputs. Otherwise, we rely on the consumer of this operator to be performing the checks.
if ((_mutables._lhsCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We don't have a "current" right enumerator to use. We have to fetch the next
// one. If the left has run out of elements, however, we're done and just return
// false right away.
if (!_leftSource.MoveNext(ref _mutables._currentLeftElement!, ref _mutables._currentLeftKey))
{
return false;
}
Debug.Assert(_selectManyOperator._rightChildSelector != null);
// Use the source selection routine to create a right child.
IEnumerable<TRightInput> rightChild = _selectManyOperator._rightChildSelector(_mutables._currentLeftElement);
Debug.Assert(rightChild != null);
_currentRightSource = rightChild.GetEnumerator();
Debug.Assert(_currentRightSource != null);
// If we have no result selector, we will need to access the Current element of the right
// data source as though it is a TOutput. Unfortunately, we know that TRightInput must
// equal TOutput (we check it during operator construction), but the type system doesn't.
// Thus we would have to cast the result of invoking Current from type TRightInput to
// TOutput. This is no good, since the results could be value types. Instead, we save the
// enumerator object as an IEnumerator<TOutput> and access that later on.
if (_selectManyOperator._resultSelector == null)
{
_currentRightSourceAsOutput = (IEnumerator<TOutput>)_currentRightSource;
Debug.Assert(_currentRightSourceAsOutput == _currentRightSource,
"these must be equal, otherwise the surrounding logic will be broken");
}
}
if (_currentRightSource.MoveNext())
{
Debug.Assert(_mutables != null);
_mutables._currentRightSourceIndex++;
// If the inner data source has an element, we can yield it.
if (_selectManyOperator._resultSelector != null)
{
// In the case of a selection function, use that to yield the next element.
currentElement = _selectManyOperator._resultSelector(_mutables._currentLeftElement, _currentRightSource.Current);
}
else
{
// Otherwise, the right input and output types must be the same. We use the
// casted copy of the current right source and just return its current element.
Debug.Assert(_currentRightSourceAsOutput != null);
currentElement = _currentRightSourceAsOutput.Current;
}
currentKey = new Pair<TLeftKey, int>(_mutables._currentLeftKey, _mutables._currentRightSourceIndex);
return true;
}
else
{
// Otherwise, we have exhausted the right data source. Loop back around and try
// to get the next left element, then its right, and so on.
_currentRightSource.Dispose();
_currentRightSource = null;
_currentRightSourceAsOutput = null;
}
}
}
protected override void Dispose(bool disposing)
{
_leftSource.Dispose();
if (_currentRightSource != null)
{
_currentRightSource.Dispose();
}
}
}
}
}
| |
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 ProjectWithSecurity.Areas.HelpPage.ModelDescriptions;
using ProjectWithSecurity.Areas.HelpPage.Models;
namespace ProjectWithSecurity.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 .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.Globalization;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Collections;
using System.Text;
using System.Diagnostics;
using System.Security.Authentication;
using System.Runtime.CompilerServices;
namespace System.DirectoryServices.Protocols
{
public delegate LdapConnection QueryForConnectionCallback(LdapConnection primaryConnection, LdapConnection referralFromConnection, string newDistinguishedName, LdapDirectoryIdentifier identifier, NetworkCredential credential, long currentUserToken);
public delegate bool NotifyOfNewConnectionCallback(LdapConnection primaryConnection, LdapConnection referralFromConnection, string newDistinguishedName, LdapDirectoryIdentifier identifier, LdapConnection newConnection, NetworkCredential credential, long currentUserToken, int errorCodeFromBind);
public delegate void DereferenceConnectionCallback(LdapConnection primaryConnection, LdapConnection connectionToDereference);
public delegate X509Certificate QueryClientCertificateCallback(LdapConnection connection, byte[][] trustedCAs);
public delegate bool VerifyServerCertificateCallback(LdapConnection connection, X509Certificate certificate);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int QUERYFORCONNECTIONInternal(IntPtr Connection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUserToken, ref IntPtr ConnectionToUse);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate bool NOTIFYOFNEWCONNECTIONInternal(IntPtr Connection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, IntPtr NewConnection, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUser, int ErrorCodeFromBind);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int DEREFERENCECONNECTIONInternal(IntPtr Connection, IntPtr ConnectionToDereference);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate bool VERIFYSERVERCERT(IntPtr Connection, IntPtr pServerCert);
[Flags]
public enum LocatorFlags : long
{
None = 0,
ForceRediscovery = 0x00000001,
DirectoryServicesRequired = 0x00000010,
DirectoryServicesPreferred = 0x00000020,
GCRequired = 0x00000040,
PdcRequired = 0x00000080,
IPRequired = 0x00000200,
KdcRequired = 0x00000400,
TimeServerRequired = 0x00000800,
WriteableRequired = 0x00001000,
GoodTimeServerPreferred = 0x00002000,
AvoidSelf = 0x00004000,
OnlyLdapNeeded = 0x00008000,
IsFlatName = 0x00010000,
IsDnsName = 0x00020000,
ReturnDnsName = 0x40000000,
ReturnFlatName = 0x80000000,
}
public enum SecurityProtocol
{
Pct1Server = 0x1,
Pct1Client = 0x2,
Ssl2Server = 0x4,
Ssl2Client = 0x8,
Ssl3Server = 0x10,
Ssl3Client = 0x20,
Tls1Server = 0x40,
Tls1Client = 0x80
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class SecurityPackageContextConnectionInformation
{
private readonly SecurityProtocol _securityProtocol;
private readonly CipherAlgorithmType _identifier;
private readonly int _strength;
private readonly HashAlgorithmType _hashAlgorithm;
private readonly int _hashStrength;
private readonly int _keyExchangeAlgorithm;
private readonly int _exchangeStrength;
internal SecurityPackageContextConnectionInformation()
{
}
public SecurityProtocol Protocol => _securityProtocol;
public CipherAlgorithmType AlgorithmIdentifier => _identifier;
public int CipherStrength => _strength;
public HashAlgorithmType Hash => _hashAlgorithm;
public int HashStrength => _hashStrength;
public int KeyExchangeAlgorithm => _keyExchangeAlgorithm;
public int ExchangeStrength => _exchangeStrength;
}
public sealed class ReferralCallback
{
public ReferralCallback()
{
}
public QueryForConnectionCallback QueryForConnection { get; set; }
public NotifyOfNewConnectionCallback NotifyNewConnection { get; set; }
public DereferenceConnectionCallback DereferenceConnection { get; set; }
}
internal struct SecurityHandle
{
public IntPtr Lower;
public IntPtr Upper;
}
public class LdapSessionOptions
{
private readonly LdapConnection _connection = null;
private ReferralCallback _callbackRoutine = new ReferralCallback();
internal QueryClientCertificateCallback _clientCertificateDelegate = null;
private VerifyServerCertificateCallback _serverCertificateDelegate = null;
private readonly QUERYFORCONNECTIONInternal _queryDelegate = null;
private readonly NOTIFYOFNEWCONNECTIONInternal _notifiyDelegate = null;
private readonly DEREFERENCECONNECTIONInternal _dereferenceDelegate = null;
private readonly VERIFYSERVERCERT _serverCertificateRoutine = null;
internal LdapSessionOptions(LdapConnection connection)
{
_connection = connection;
_queryDelegate = new QUERYFORCONNECTIONInternal(ProcessQueryConnection);
_notifiyDelegate = new NOTIFYOFNEWCONNECTIONInternal(ProcessNotifyConnection);
_dereferenceDelegate = new DEREFERENCECONNECTIONInternal(ProcessDereferenceConnection);
_serverCertificateRoutine = new VERIFYSERVERCERT(ProcessServerCertificate);
}
public ReferralChasingOptions ReferralChasing
{
get
{
int result = GetIntValueHelper(LdapOption.LDAP_OPT_REFERRALS);
return result == 1 ? ReferralChasingOptions.All : (ReferralChasingOptions)result;
}
set
{
if (((value) & (~ReferralChasingOptions.All)) != 0)
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ReferralChasingOptions));
}
SetIntValueHelper(LdapOption.LDAP_OPT_REFERRALS, (int)value);
}
}
public bool SecureSocketLayer
{
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_SSL);
return outValue == 1;
}
set
{
int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_SSL, temp);
}
}
public int ReferralHopLimit
{
get => GetIntValueHelper(LdapOption.LDAP_OPT_REFERRAL_HOP_LIMIT);
set
{
if (value < 0)
{
throw new ArgumentException(SR.ValidValue, nameof(value));
}
SetIntValueHelper(LdapOption.LDAP_OPT_REFERRAL_HOP_LIMIT, value);
}
}
public int ProtocolVersion
{
get => GetIntValueHelper(LdapOption.LDAP_OPT_VERSION);
set => SetIntValueHelper(LdapOption.LDAP_OPT_VERSION, value);
}
public string HostName
{
get => GetStringValueHelper(LdapOption.LDAP_OPT_HOST_NAME, false);
set => SetStringValueHelper(LdapOption.LDAP_OPT_HOST_NAME, value);
}
public string DomainName
{
get => GetStringValueHelper(LdapOption.LDAP_OPT_DNSDOMAIN_NAME, true);
set => SetStringValueHelper(LdapOption.LDAP_OPT_DNSDOMAIN_NAME, value);
}
public LocatorFlags LocatorFlag
{
get
{
int result = GetIntValueHelper(LdapOption.LDAP_OPT_GETDSNAME_FLAGS);
return (LocatorFlags)result;
}
set
{
// We don't do validation to the dirsync flag here as underneath API does not check for it and we don't want to put
// unnecessary limitation on it.
SetIntValueHelper(LdapOption.LDAP_OPT_GETDSNAME_FLAGS, (int)value);
}
}
public bool HostReachable
{
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_HOST_REACHABLE);
return outValue == 1;
}
}
public TimeSpan PingKeepAliveTimeout
{
get
{
int result = GetIntValueHelper(LdapOption.LDAP_OPT_PING_KEEP_ALIVE);
return new TimeSpan(result * TimeSpan.TicksPerSecond);
}
set
{
if (value < TimeSpan.Zero)
{
throw new ArgumentException(SR.NoNegativeTimeLimit, nameof(value));
}
// Prevent integer overflow.
if (value.TotalSeconds > int.MaxValue)
{
throw new ArgumentException(SR.TimespanExceedMax, nameof(value));
}
int seconds = (int)(value.Ticks / TimeSpan.TicksPerSecond);
SetIntValueHelper(LdapOption.LDAP_OPT_PING_KEEP_ALIVE, seconds);
}
}
public int PingLimit
{
get => GetIntValueHelper(LdapOption.LDAP_OPT_PING_LIMIT);
set
{
if (value < 0)
{
throw new ArgumentException(SR.ValidValue, nameof(value));
}
SetIntValueHelper(LdapOption.LDAP_OPT_PING_LIMIT, value);
}
}
public TimeSpan PingWaitTimeout
{
get
{
int result = GetIntValueHelper(LdapOption.LDAP_OPT_PING_WAIT_TIME);
return new TimeSpan(result * TimeSpan.TicksPerMillisecond);
}
set
{
if (value < TimeSpan.Zero)
{
throw new ArgumentException(SR.NoNegativeTimeLimit, nameof(value));
}
// Prevent integer overflow.
if (value.TotalMilliseconds > int.MaxValue)
{
throw new ArgumentException(SR.TimespanExceedMax, nameof(value));
}
int milliseconds = (int)(value.Ticks / TimeSpan.TicksPerMillisecond);
SetIntValueHelper(LdapOption.LDAP_OPT_PING_WAIT_TIME, milliseconds);
}
}
public bool AutoReconnect
{
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_AUTO_RECONNECT);
return outValue == 1;
}
set
{
int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_AUTO_RECONNECT, temp);
}
}
public int SspiFlag
{
get => GetIntValueHelper(LdapOption.LDAP_OPT_SSPI_FLAGS);
set => SetIntValueHelper(LdapOption.LDAP_OPT_SSPI_FLAGS, value);
}
public SecurityPackageContextConnectionInformation SslInformation
{
get
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
var secInfo = new SecurityPackageContextConnectionInformation();
int error = Wldap32.ldap_get_option_secInfo(_connection._ldapHandle, LdapOption.LDAP_OPT_SSL_INFO, secInfo);
ErrorChecking.CheckAndSetLdapError(error);
return secInfo;
}
}
public object SecurityContext
{
get
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
var tempHandle = new SecurityHandle();
int error = Wldap32.ldap_get_option_sechandle(_connection._ldapHandle, LdapOption.LDAP_OPT_SECURITY_CONTEXT, ref tempHandle);
ErrorChecking.CheckAndSetLdapError(error);
return tempHandle;
}
}
public bool Signing
{
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_SIGN);
return outValue == 1;
}
set
{
int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_SIGN, temp);
}
}
public bool Sealing
{
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_ENCRYPT);
return outValue == 1;
}
set
{
int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_ENCRYPT, temp);
}
}
public string SaslMethod
{
get => GetStringValueHelper(LdapOption.LDAP_OPT_SASL_METHOD, true);
set => SetStringValueHelper(LdapOption.LDAP_OPT_SASL_METHOD, value);
}
public bool RootDseCache
{
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_ROOTDSE_CACHE);
return outValue == 1;
}
set
{
int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_ROOTDSE_CACHE, temp);
}
}
public bool TcpKeepAlive
{
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_TCP_KEEPALIVE);
return outValue == 1;
}
set
{
int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_TCP_KEEPALIVE, temp);
}
}
public TimeSpan SendTimeout
{
get
{
int result = GetIntValueHelper(LdapOption.LDAP_OPT_SEND_TIMEOUT);
return new TimeSpan(result * TimeSpan.TicksPerSecond);
}
set
{
if (value < TimeSpan.Zero)
{
throw new ArgumentException(SR.NoNegativeTimeLimit, nameof(value));
}
// Prevent integer overflow.
if (value.TotalSeconds > int.MaxValue)
{
throw new ArgumentException(SR.TimespanExceedMax, nameof(value));
}
int seconds = (int)(value.Ticks / TimeSpan.TicksPerSecond);
SetIntValueHelper(LdapOption.LDAP_OPT_SEND_TIMEOUT, seconds);
}
}
public ReferralCallback ReferralCallback
{
get
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return _callbackRoutine;
}
set
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
var tempCallback = new ReferralCallback();
if (value != null)
{
tempCallback.QueryForConnection = value.QueryForConnection;
tempCallback.NotifyNewConnection = value.NotifyNewConnection;
tempCallback.DereferenceConnection = value.DereferenceConnection;
}
else
{
tempCallback.QueryForConnection = null;
tempCallback.NotifyNewConnection = null;
tempCallback.DereferenceConnection = null;
}
ProcessCallBackRoutine(tempCallback);
_callbackRoutine = value;
}
}
public QueryClientCertificateCallback QueryClientCertificate
{
get
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return _clientCertificateDelegate;
}
set
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (value != null)
{
int certError = Wldap32.ldap_set_option_clientcert(_connection._ldapHandle, LdapOption.LDAP_OPT_CLIENT_CERTIFICATE, _connection._clientCertificateRoutine);
if (certError != (int)ResultCode.Success)
{
if (Utility.IsLdapError((LdapError)certError))
{
string certerrorMessage = LdapErrorMappings.MapResultCode(certError);
throw new LdapException(certError, certerrorMessage);
}
else
{
throw new LdapException(certError);
}
}
// A certificate callback is specified so automatic bind is disabled.
_connection.AutoBind = false;
}
_clientCertificateDelegate = value;
}
}
public VerifyServerCertificateCallback VerifyServerCertificate
{
get
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return _serverCertificateDelegate;
}
set
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (value != null)
{
int error = Wldap32.ldap_set_option_servercert(_connection._ldapHandle, LdapOption.LDAP_OPT_SERVER_CERTIFICATE, _serverCertificateRoutine);
ErrorChecking.CheckAndSetLdapError(error);
}
_serverCertificateDelegate = value;
}
}
internal string ServerErrorMessage => GetStringValueHelper(LdapOption.LDAP_OPT_SERVER_ERROR, true);
internal DereferenceAlias DerefAlias
{
get => (DereferenceAlias)GetIntValueHelper(LdapOption.LDAP_OPT_DEREF);
set => SetIntValueHelper(LdapOption.LDAP_OPT_DEREF, (int)value);
}
internal bool FQDN
{
set
{
// set the value to true
SetIntValueHelper(LdapOption.LDAP_OPT_AREC_EXCLUSIVE, 1);
}
}
public void FastConcurrentBind()
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
// Bump up the protocol version
ProtocolVersion = 3;
// Do the fast concurrent bind.
int inValue = 1;
int error = Wldap32.ldap_set_option_int(_connection._ldapHandle, LdapOption.LDAP_OPT_FAST_CONCURRENT_BIND, ref inValue);
ErrorChecking.CheckAndSetLdapError(error);
}
public unsafe void StartTransportLayerSecurity(DirectoryControlCollection controls)
{
IntPtr serverControlArray = IntPtr.Zero;
LdapControl[] managedServerControls = null;
IntPtr clientControlArray = IntPtr.Zero;
LdapControl[] managedClientControls = null;
IntPtr ldapResult = IntPtr.Zero;
IntPtr referral = IntPtr.Zero;
int serverError = 0;
Uri[] responseReferral = null;
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
try
{
IntPtr tempPtr = IntPtr.Zero;
// build server control
managedServerControls = _connection.BuildControlArray(controls, true);
int structSize = Marshal.SizeOf(typeof(LdapControl));
if (managedServerControls != null)
{
serverControlArray = Utility.AllocHGlobalIntPtrArray(managedServerControls.Length + 1);
for (int i = 0; i < managedServerControls.Length; i++)
{
IntPtr controlPtr = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(managedServerControls[i], controlPtr, false);
tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, controlPtr);
}
tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * managedServerControls.Length);
Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
}
// Build client control.
managedClientControls = _connection.BuildControlArray(controls, false);
if (managedClientControls != null)
{
clientControlArray = Utility.AllocHGlobalIntPtrArray(managedClientControls.Length + 1);
for (int i = 0; i < managedClientControls.Length; i++)
{
IntPtr controlPtr = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(managedClientControls[i], controlPtr, false);
tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, controlPtr);
}
tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * managedClientControls.Length);
Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
}
int error = Wldap32.ldap_start_tls(_connection._ldapHandle, ref serverError, ref ldapResult, serverControlArray, clientControlArray);
if (ldapResult != IntPtr.Zero)
{
// Parse the referral.
int resultError = Wldap32.ldap_parse_result_referral(_connection._ldapHandle, ldapResult, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref referral, IntPtr.Zero, 0 /* not free it */);
if (resultError == 0 && referral != IntPtr.Zero)
{
char** referralPtr = (char**)referral;
char* singleReferral = referralPtr[0];
int i = 0;
ArrayList referralList = new ArrayList();
while (singleReferral != null)
{
string s = Marshal.PtrToStringUni((IntPtr)singleReferral);
referralList.Add(s);
i++;
singleReferral = referralPtr[i];
}
// Free heap memory.
if (referral != IntPtr.Zero)
{
Wldap32.ldap_value_free(referral);
referral = IntPtr.Zero;
}
if (referralList.Count > 0)
{
responseReferral = new Uri[referralList.Count];
for (int j = 0; j < referralList.Count; j++)
{
responseReferral[j] = new Uri((string)referralList[j]);
}
}
}
}
if (error != (int)ResultCode.Success)
{
if (Utility.IsResultCode((ResultCode)error))
{
// If the server failed request for whatever reason, the ldap_start_tls returns LDAP_OTHER
// and the ServerReturnValue will contain the error code from the server.
if (error == (int)ResultCode.Other)
{
error = serverError;
}
string errorMessage = OperationErrorMappings.MapResultCode(error);
ExtendedResponse response = new ExtendedResponse(null, null, (ResultCode)error, errorMessage, responseReferral);
response.ResponseName = "1.3.6.1.4.1.1466.20037";
throw new TlsOperationException(response);
}
else if (Utility.IsLdapError((LdapError)error))
{
string errorMessage = LdapErrorMappings.MapResultCode(error);
throw new LdapException(error, errorMessage);
}
}
}
finally
{
if (serverControlArray != IntPtr.Zero)
{
// Release the memory from the heap.
for (int i = 0; i < managedServerControls.Length; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(serverControlArray, IntPtr.Size * i);
if (tempPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(tempPtr);
}
}
Marshal.FreeHGlobal(serverControlArray);
}
if (managedServerControls != null)
{
for (int i = 0; i < managedServerControls.Length; i++)
{
if (managedServerControls[i].ldctl_oid != IntPtr.Zero)
{
Marshal.FreeHGlobal(managedServerControls[i].ldctl_oid);
}
if (managedServerControls[i].ldctl_value != null)
{
if (managedServerControls[i].ldctl_value.bv_val != IntPtr.Zero)
{
Marshal.FreeHGlobal(managedServerControls[i].ldctl_value.bv_val);
}
}
}
}
if (clientControlArray != IntPtr.Zero)
{
// Release the memor from the heap.
for (int i = 0; i < managedClientControls.Length; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(clientControlArray, IntPtr.Size * i);
if (tempPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(tempPtr);
}
}
Marshal.FreeHGlobal(clientControlArray);
}
if (managedClientControls != null)
{
for (int i = 0; i < managedClientControls.Length; i++)
{
if (managedClientControls[i].ldctl_oid != IntPtr.Zero)
{
Marshal.FreeHGlobal(managedClientControls[i].ldctl_oid);
}
if (managedClientControls[i].ldctl_value != null)
{
if (managedClientControls[i].ldctl_value.bv_val != IntPtr.Zero)
Marshal.FreeHGlobal(managedClientControls[i].ldctl_value.bv_val);
}
}
}
if (referral != IntPtr.Zero)
{
Wldap32.ldap_value_free(referral);
}
}
}
public void StopTransportLayerSecurity()
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
byte result = Wldap32.ldap_stop_tls(_connection._ldapHandle);
if (result == 0)
{
throw new TlsOperationException(null, SR.TLSStopFailure);
}
}
private int GetIntValueHelper(LdapOption option)
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
int outValue = 0;
int error = Wldap32.ldap_get_option_int(_connection._ldapHandle, option, ref outValue);
ErrorChecking.CheckAndSetLdapError(error);
return outValue;
}
private void SetIntValueHelper(LdapOption option, int value)
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
int temp = value;
int error = Wldap32.ldap_set_option_int(_connection._ldapHandle, option, ref temp);
ErrorChecking.CheckAndSetLdapError(error);
}
private string GetStringValueHelper(LdapOption option, bool releasePtr)
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
IntPtr outValue = new IntPtr(0);
int error = Wldap32.ldap_get_option_ptr(_connection._ldapHandle, option, ref outValue);
ErrorChecking.CheckAndSetLdapError(error);
string stringValue = null;
if (outValue != IntPtr.Zero)
{
stringValue = Marshal.PtrToStringUni(outValue);
}
if (releasePtr)
{
Wldap32.ldap_memfree(outValue);
}
return stringValue;
}
private void SetStringValueHelper(LdapOption option, string value)
{
if (_connection._disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
IntPtr inValue = IntPtr.Zero;
if (value != null)
{
inValue = Marshal.StringToHGlobalUni(value);
}
try
{
int error = Wldap32.ldap_set_option_ptr(_connection._ldapHandle, option, ref inValue);
ErrorChecking.CheckAndSetLdapError(error);
}
finally
{
if (inValue != IntPtr.Zero)
{
Marshal.FreeHGlobal(inValue);
}
}
}
private void ProcessCallBackRoutine(ReferralCallback tempCallback)
{
LdapReferralCallback value = new LdapReferralCallback()
{
sizeofcallback = Marshal.SizeOf(typeof(LdapReferralCallback)),
query = tempCallback.QueryForConnection == null ? null : _queryDelegate,
notify = tempCallback.NotifyNewConnection == null ? null : _notifiyDelegate,
dereference = tempCallback.DereferenceConnection == null ? null : _dereferenceDelegate
};
int error = Wldap32.ldap_set_option_referral(_connection._ldapHandle, LdapOption.LDAP_OPT_REFERRAL_CALLBACK, ref value);
ErrorChecking.CheckAndSetLdapError(error);
}
private int ProcessQueryConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUserToken, ref IntPtr ConnectionToUse)
{
ConnectionToUse = IntPtr.Zero;
string NewDN = null;
// The user must have registered callback function.
Debug.Assert(_callbackRoutine.QueryForConnection != null);
// The user registers the QUERYFORCONNECTION callback.
if (_callbackRoutine.QueryForConnection != null)
{
if (NewDNPtr != IntPtr.Zero)
{
NewDN = Marshal.PtrToStringUni(NewDNPtr);
}
var target = new StringBuilder();
target.Append(HostName);
target.Append(":");
target.Append(PortNumber);
var identifier = new LdapDirectoryIdentifier(target.ToString());
NetworkCredential cred = ProcessSecAuthIdentity(SecAuthIdentity);
LdapConnection tempReferralConnection = null;
// If ReferralFromConnection handle is valid.
if (ReferralFromConnection != IntPtr.Zero)
{
lock (LdapConnection.s_objectLock)
{
// Make sure first whether we have saved it in the handle table before
WeakReference reference = (WeakReference)(LdapConnection.s_handleTable[ReferralFromConnection]);
if (reference != null && reference.IsAlive)
{
// Save this before and object has not been garbage collected yet.
tempReferralConnection = (LdapConnection)reference.Target;
}
else
{
if (reference != null)
{
// Connection has been garbage collected, we need to remove this one.
LdapConnection.s_handleTable.Remove(ReferralFromConnection);
}
// We don't have it yet, construct a new one.
tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection);
// Save it to the handle table.
LdapConnection.s_handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection));
}
}
}
long tokenValue = (uint)CurrentUserToken.LowPart + (((long)CurrentUserToken.HighPart) << 32);
LdapConnection con = _callbackRoutine.QueryForConnection(_connection, tempReferralConnection, NewDN, identifier, cred, tokenValue);
if (con != null && con._ldapHandle != null && !con._ldapHandle.IsInvalid)
{
bool success = AddLdapHandleRef(con);
if (success)
{
ConnectionToUse = con._ldapHandle.DangerousGetHandle();
}
}
return 0;
}
// The user does not take ownership of the connection.
return 1;
}
private bool ProcessNotifyConnection(IntPtr primaryConnection, IntPtr referralFromConnection, IntPtr newDNPtr, string hostName, IntPtr newConnection, int portNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid currentUser, int errorCodeFromBind)
{
if (newConnection != IntPtr.Zero && _callbackRoutine.NotifyNewConnection != null)
{
string newDN = null;
if (newDNPtr != IntPtr.Zero)
{
newDN = Marshal.PtrToStringUni(newDNPtr);
}
var target = new StringBuilder();
target.Append(hostName);
target.Append(":");
target.Append(portNumber);
var identifier = new LdapDirectoryIdentifier(target.ToString());
NetworkCredential cred = ProcessSecAuthIdentity(SecAuthIdentity);
LdapConnection tempNewConnection = null;
LdapConnection tempReferralConnection = null;
lock (LdapConnection.s_objectLock)
{
// Check whether the referralFromConnection handle is valid.
if (referralFromConnection != IntPtr.Zero)
{
// Check whether we have save it in the handle table before.
WeakReference reference = (WeakReference)(LdapConnection.s_handleTable[referralFromConnection]);
if (reference != null && reference.Target is LdapConnection conn && conn._ldapHandle != null)
{
// Save this before and object has not been garbage collected yet.
tempReferralConnection = conn;
}
else
{
// Connection has been garbage collected, we need to remove this one.
if (reference != null)
{
LdapConnection.s_handleTable.Remove(referralFromConnection);
}
// We don't have it yet, construct a new one.
tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, referralFromConnection);
// Save it to the handle table.
LdapConnection.s_handleTable.Add(referralFromConnection, new WeakReference(tempReferralConnection));
}
}
if (newConnection != IntPtr.Zero)
{
// Check whether we have save it in the handle table before.
WeakReference reference = (WeakReference)(LdapConnection.s_handleTable[newConnection]);
if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target)._ldapHandle)
{
// Save this before and object has not been garbage collected yet.
tempNewConnection = (LdapConnection)reference.Target;
}
else
{
// Connection has been garbage collected, we need to remove this one.
if (reference != null)
{
LdapConnection.s_handleTable.Remove(newConnection);
}
// We don't have it yet, construct a new one.
tempNewConnection = new LdapConnection(identifier, cred, _connection.AuthType, newConnection);
// Save it to the handle table.
LdapConnection.s_handleTable.Add(newConnection, new WeakReference(tempNewConnection));
}
}
}
long tokenValue = (uint)currentUser.LowPart + (((long)currentUser.HighPart) << 32);
bool value = _callbackRoutine.NotifyNewConnection(_connection, tempReferralConnection, newDN, identifier, tempNewConnection, cred, tokenValue, errorCodeFromBind);
if (value)
{
value = AddLdapHandleRef(tempNewConnection);
if (value)
{
tempNewConnection.NeedDispose = true;
}
}
return value;
}
return false;
}
private int ProcessDereferenceConnection(IntPtr PrimaryConnection, IntPtr ConnectionToDereference)
{
if (ConnectionToDereference != IntPtr.Zero && _callbackRoutine.DereferenceConnection != null)
{
LdapConnection dereferenceConnection = null;
WeakReference reference = null;
// in most cases it should be in our table
lock (LdapConnection.s_objectLock)
{
reference = (WeakReference)(LdapConnection.s_handleTable[ConnectionToDereference]);
}
// not been added to the table before or it is garbage collected, we need to construct it
if (reference == null || !reference.IsAlive)
{
dereferenceConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ConnectionToDereference);
}
else
{
dereferenceConnection = (LdapConnection)reference.Target;
ReleaseLdapHandleRef(dereferenceConnection);
}
_callbackRoutine.DereferenceConnection(_connection, dereferenceConnection);
// there is no need to remove the connection object from the handle table, as it will be removed automatically when
// connection object is disposed.
}
return 1;
}
private NetworkCredential ProcessSecAuthIdentity(SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentit)
{
if (SecAuthIdentit == null)
{
return new NetworkCredential();
}
string user = SecAuthIdentit.user;
string domain = SecAuthIdentit.domain;
string password = SecAuthIdentit.password;
return new NetworkCredential(user, password, domain);
}
private bool ProcessServerCertificate(IntPtr connection, IntPtr serverCert)
{
// If callback is not specified by user, it means the server certificate is accepted.
bool value = true;
if (_serverCertificateDelegate != null)
{
IntPtr certPtr = IntPtr.Zero;
X509Certificate certificate = null;
try
{
Debug.Assert(serverCert != IntPtr.Zero);
certPtr = Marshal.ReadIntPtr(serverCert);
certificate = new X509Certificate(certPtr);
}
finally
{
Wldap32.CertFreeCRLContext(certPtr);
}
value = _serverCertificateDelegate(_connection, certificate);
}
return value;
}
private static bool AddLdapHandleRef(LdapConnection ldapConnection)
{
bool success = false;
if (ldapConnection != null && ldapConnection._ldapHandle != null && !ldapConnection._ldapHandle.IsInvalid)
{
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
ldapConnection._ldapHandle.DangerousAddRef(ref success);
}
}
return success;
}
private static void ReleaseLdapHandleRef(LdapConnection ldapConnection)
{
if (ldapConnection != null && ldapConnection._ldapHandle != null && !ldapConnection._ldapHandle.IsInvalid)
{
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
ldapConnection._ldapHandle.DangerousRelease();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using web.Areas.HelpPage.Models;
namespace 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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.AppService.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using Microsoft.Azure.Management.TrafficManager.Fluent;
using System;
using System.Linq;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
namespace ManageWebAppWithTrafficManager
{
/**
* Azure App Service sample for managing web apps.
* - Create a domain
* - Create a self-signed certificate for the domain
* - Create 3 app service plans in 3 different regions
* - Create 5 web apps under the 3 plans, bound to the domain and the certificate
* - Create a traffic manager in front of the web apps
* - Scale up the app service plans to twice the capacity
*/
public class Program
{
private static string CERT_PASSWORD = "StrongPass!12";
private static string pfxPath;
public static void RunSample(IAzure azure)
{
string resourceGroupName = SdkContext.RandomResourceName("rgNEMV_", 24);
string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
string app3Name = SdkContext.RandomResourceName("webapp3-", 20);
string app4Name = SdkContext.RandomResourceName("webapp4-", 20);
string app5Name = SdkContext.RandomResourceName("webapp5-", 20);
string plan1Name = SdkContext.RandomResourceName("jplan1_", 15);
string plan2Name = SdkContext.RandomResourceName("jplan2_", 15);
string plan3Name = SdkContext.RandomResourceName("jplan3_", 15);
string domainName = SdkContext.RandomResourceName("jsdkdemo-", 20) + ".com";
string trafficManagerName = SdkContext.RandomResourceName("jsdktm-", 20);
try
{
//============================================================
// Purchase a domain (will be canceled for a full refund)
Utilities.Log("Purchasing a domain " + domainName + "...");
azure.ResourceGroups.Define(resourceGroupName)
.WithRegion(Region.USWest)
.Create();
var domain = azure.AppServices.AppServiceDomains.Define(domainName)
.WithExistingResourceGroup(resourceGroupName)
.DefineRegistrantContact()
.WithFirstName("Jon")
.WithLastName("Doe")
.WithEmail("jondoe@contoso.com")
.WithAddressLine1("123 4th Ave")
.WithCity("Redmond")
.WithStateOrProvince("WA")
.WithCountry(CountryISOCode.UnitedStates)
.WithPostalCode("98052")
.WithPhoneCountryCode(CountryPhoneCode.UnitedStates)
.WithPhoneNumber("4258828080")
.Attach()
.WithDomainPrivacyEnabled(true)
.WithAutoRenewEnabled(false)
.Create();
Utilities.Log("Purchased domain " + domain.Name);
Utilities.Print(domain);
//============================================================
// Create a self-singed SSL certificate
pfxPath = domainName + ".pfx";
Utilities.Log("Creating a self-signed certificate " + pfxPath + "...");
Utilities.CreateCertificate(domainName, pfxPath, CERT_PASSWORD);
//============================================================
// Create 3 app service plans in 3 regions
Utilities.Log("Creating app service plan " + plan1Name + " in US West...");
var plan1 = CreateAppServicePlan(azure, resourceGroupName, plan1Name, Region.USWest);
Utilities.Log("Created app service plan " + plan1.Name);
Utilities.Print(plan1);
Utilities.Log("Creating app service plan " + plan2Name + " in Europe West...");
var plan2 = CreateAppServicePlan(azure, resourceGroupName, plan2Name, Region.EuropeWest);
Utilities.Log("Created app service plan " + plan2.Name);
Utilities.Print(plan1);
Utilities.Log("Creating app service plan " + plan3Name + " in Asia East...");
var plan3 = CreateAppServicePlan(azure, resourceGroupName, plan3Name, Region.AsiaEast);
Utilities.Log("Created app service plan " + plan2.Name);
Utilities.Print(plan1);
//============================================================
// Create 5 web apps under these 3 app service plans
Utilities.Log("Creating web app " + app1Name + "...");
var app1 = CreateWebApp(azure, domain, resourceGroupName, app1Name, plan1);
Utilities.Log("Created web app " + app1.Name);
Utilities.Print(app1);
Utilities.Log("Creating another web app " + app2Name + "...");
var app2 = CreateWebApp(azure, domain, resourceGroupName, app2Name, plan2);
Utilities.Log("Created web app " + app2.Name);
Utilities.Print(app2);
Utilities.Log("Creating another web app " + app3Name + "...");
var app3 = CreateWebApp(azure, domain, resourceGroupName, app3Name, plan3);
Utilities.Log("Created web app " + app3.Name);
Utilities.Print(app3);
Utilities.Log("Creating another web app " + app3Name + "...");
var app4 = CreateWebApp(azure, domain, resourceGroupName, app4Name, plan1);
Utilities.Log("Created web app " + app4.Name);
Utilities.Print(app4);
Utilities.Log("Creating another web app " + app3Name + "...");
var app5 = CreateWebApp(azure, domain, resourceGroupName, app5Name, plan1);
Utilities.Log("Created web app " + app5.Name);
Utilities.Print(app5);
//============================================================
// Create a traffic manager
Utilities.Log("Creating a traffic manager " + trafficManagerName + " for the web apps...");
var trafficManager = azure.TrafficManagerProfiles
.Define(trafficManagerName)
.WithExistingResourceGroup(resourceGroupName)
.WithLeafDomainLabel(trafficManagerName)
.WithTrafficRoutingMethod(TrafficRoutingMethod.Weighted)
.DefineAzureTargetEndpoint("endpoint1")
.ToResourceId(app1.Id)
.Attach()
.DefineAzureTargetEndpoint("endpoint2")
.ToResourceId(app2.Id)
.Attach()
.DefineAzureTargetEndpoint("endpoint3")
.ToResourceId(app3.Id)
.Attach()
.Create();
Utilities.Log("Created traffic manager " + trafficManager.Name);
//============================================================
// Scale up the app service plans
Utilities.Log("Scaling up app service plan " + plan1Name + "...");
plan1.Update()
.WithCapacity(plan1.Capacity * 2)
.Apply();
Utilities.Log("Scaled up app service plan " + plan1Name);
Utilities.Print(plan1);
Utilities.Log("Scaling up app service plan " + plan2Name + "...");
plan2.Update()
.WithCapacity(plan2.Capacity * 2)
.Apply();
Utilities.Log("Scaled up app service plan " + plan2Name);
Utilities.Print(plan2);
Utilities.Log("Scaling up app service plan " + plan3Name + "...");
plan3.Update()
.WithCapacity(plan3.Capacity * 2)
.Apply();
Utilities.Log("Scaled up app service plan " + plan3Name);
Utilities.Print(plan3);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + resourceGroupName);
azure.ResourceGroups.DeleteByName(resourceGroupName);
Utilities.Log("Deleted Resource Group: " + resourceGroupName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception g)
{
Utilities.Log(g);
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception e)
{
Utilities.Log(e);
}
}
private static IAppServicePlan CreateAppServicePlan(IAzure azure, string rgName, string name, Region region)
{
return azure.AppServices.AppServicePlans
.Define(name)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithPricingTier(PricingTier.BasicB1)
.WithOperatingSystem(Microsoft.Azure.Management.AppService.Fluent.OperatingSystem.Windows)
.Create();
}
private static IWebApp CreateWebApp(IAzure azure, IAppServiceDomain domain, string rgName, string name, IAppServicePlan plan)
{
return azure.WebApps.Define(name)
.WithExistingWindowsPlan(plan)
.WithExistingResourceGroup(rgName)
.WithManagedHostnameBindings(domain, name)
.DefineSslBinding()
.ForHostname(name + "." + domain.Name)
.WithPfxCertificateToUpload(Path.Combine(Utilities.ProjectPath, "Asset", pfxPath), CERT_PASSWORD)
.WithSniBasedSsl()
.Attach()
.DefineSourceControl()
.WithPublicGitRepository("https://github.Com/jianghaolu/azure-site-test")
.WithBranch("master")
.Attach()
.Create();
}
}
}
| |
using System;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Threading;
using Avalonia.Controls.Metadata;
namespace Avalonia.Controls.Primitives
{
public class ScrollEventArgs : EventArgs
{
public ScrollEventArgs(ScrollEventType eventType, double newValue)
{
ScrollEventType = eventType;
NewValue = newValue;
}
public double NewValue { get; private set; }
public ScrollEventType ScrollEventType { get; private set; }
}
/// <summary>
/// A scrollbar control.
/// </summary>
[PseudoClasses(":vertical", ":horizontal")]
public class ScrollBar : RangeBase
{
/// <summary>
/// Defines the <see cref="ViewportSize"/> property.
/// </summary>
public static readonly StyledProperty<double> ViewportSizeProperty =
AvaloniaProperty.Register<ScrollBar, double>(nameof(ViewportSize), defaultValue: double.NaN);
/// <summary>
/// Defines the <see cref="Visibility"/> property.
/// </summary>
public static readonly StyledProperty<ScrollBarVisibility> VisibilityProperty =
AvaloniaProperty.Register<ScrollBar, ScrollBarVisibility>(nameof(Visibility), ScrollBarVisibility.Visible);
/// <summary>
/// Defines the <see cref="Orientation"/> property.
/// </summary>
public static readonly StyledProperty<Orientation> OrientationProperty =
AvaloniaProperty.Register<ScrollBar, Orientation>(nameof(Orientation), Orientation.Vertical);
/// <summary>
/// Defines the <see cref="IsExpandedProperty"/> property.
/// </summary>
public static readonly DirectProperty<ScrollBar, bool> IsExpandedProperty =
AvaloniaProperty.RegisterDirect<ScrollBar, bool>(
nameof(IsExpanded),
o => o.IsExpanded);
/// <summary>
/// Defines the <see cref="AllowAutoHide"/> property.
/// </summary>
public static readonly StyledProperty<bool> AllowAutoHideProperty =
AvaloniaProperty.Register<ScrollBar, bool>(nameof(AllowAutoHide), true);
/// <summary>
/// Defines the <see cref="HideDelay"/> property.
/// </summary>
public static readonly StyledProperty<TimeSpan> HideDelayProperty =
AvaloniaProperty.Register<ScrollBar, TimeSpan>(nameof(HideDelay), TimeSpan.FromSeconds(2));
/// <summary>
/// Defines the <see cref="ShowDelay"/> property.
/// </summary>
public static readonly StyledProperty<TimeSpan> ShowDelayProperty =
AvaloniaProperty.Register<ScrollBar, TimeSpan>(nameof(ShowDelay), TimeSpan.FromSeconds(0.5));
private Button? _lineUpButton;
private Button? _lineDownButton;
private Button? _pageUpButton;
private Button? _pageDownButton;
private DispatcherTimer? _timer;
private bool _isExpanded;
/// <summary>
/// Initializes static members of the <see cref="ScrollBar"/> class.
/// </summary>
static ScrollBar()
{
Thumb.DragDeltaEvent.AddClassHandler<ScrollBar>((x, e) => x.OnThumbDragDelta(e), RoutingStrategies.Bubble);
Thumb.DragCompletedEvent.AddClassHandler<ScrollBar>((x, e) => x.OnThumbDragComplete(e), RoutingStrategies.Bubble);
}
/// <summary>
/// Initializes a new instance of the <see cref="ScrollBar"/> class.
/// </summary>
public ScrollBar()
{
UpdatePseudoClasses(Orientation);
}
/// <summary>
/// Gets or sets the amount of the scrollable content that is currently visible.
/// </summary>
public double ViewportSize
{
get { return GetValue(ViewportSizeProperty); }
set { SetValue(ViewportSizeProperty, value); }
}
/// <summary>
/// Gets or sets a value that indicates whether the scrollbar should hide itself when it
/// is not needed.
/// </summary>
public ScrollBarVisibility Visibility
{
get { return GetValue(VisibilityProperty); }
set { SetValue(VisibilityProperty, value); }
}
/// <summary>
/// Gets or sets the orientation of the scrollbar.
/// </summary>
public Orientation Orientation
{
get { return GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
/// <summary>
/// Gets a value that indicates whether the scrollbar is expanded.
/// </summary>
public bool IsExpanded
{
get => _isExpanded;
private set => SetAndRaise(IsExpandedProperty, ref _isExpanded, value);
}
/// <summary>
/// Gets a value that indicates whether the scrollbar can hide itself when user is not interacting with it.
/// </summary>
public bool AllowAutoHide
{
get => GetValue(AllowAutoHideProperty);
set => SetValue(AllowAutoHideProperty, value);
}
/// <summary>
/// Gets a value that determines how long will be the hide delay after user stops interacting with the scrollbar.
/// </summary>
public TimeSpan HideDelay
{
get => GetValue(HideDelayProperty);
set => SetValue(HideDelayProperty, value);
}
/// <summary>
/// Gets a value that determines how long will be the show delay when user starts interacting with the scrollbar.
/// </summary>
public TimeSpan ShowDelay
{
get => GetValue(ShowDelayProperty);
set => SetValue(ShowDelayProperty, value);
}
public event EventHandler<ScrollEventArgs>? Scroll;
/// <summary>
/// Calculates and updates whether the scrollbar should be visible.
/// </summary>
private void UpdateIsVisible()
{
var isVisible = Visibility switch
{
ScrollBarVisibility.Visible => true,
ScrollBarVisibility.Disabled => false,
ScrollBarVisibility.Hidden => false,
ScrollBarVisibility.Auto => (double.IsNaN(ViewportSize) || Maximum > 0),
_ => throw new InvalidOperationException("Invalid value for ScrollBar.Visibility.")
};
SetValue(IsVisibleProperty, isVisible);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Key == Key.PageUp)
{
LargeDecrement();
e.Handled = true;
}
else if (e.Key == Key.PageDown)
{
LargeIncrement();
e.Handled = true;
}
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == OrientationProperty)
{
UpdatePseudoClasses(change.NewValue.GetValueOrDefault<Orientation>());
}
else if (change.Property == AllowAutoHideProperty)
{
UpdateIsExpandedState();
}
else
{
if (change.Property == MinimumProperty ||
change.Property == MaximumProperty ||
change.Property == ViewportSizeProperty ||
change.Property == VisibilityProperty)
{
UpdateIsVisible();
}
}
}
protected override void OnPointerEnter(PointerEventArgs e)
{
base.OnPointerEnter(e);
if (AllowAutoHide)
{
ExpandAfterDelay();
}
}
protected override void OnPointerLeave(PointerEventArgs e)
{
base.OnPointerLeave(e);
if (AllowAutoHide)
{
CollapseAfterDelay();
}
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
if (_lineUpButton != null)
{
_lineUpButton.Click -= LineUpClick;
}
if (_lineDownButton != null)
{
_lineDownButton.Click -= LineDownClick;
}
if (_pageUpButton != null)
{
_pageUpButton.Click -= PageUpClick;
}
if (_pageDownButton != null)
{
_pageDownButton.Click -= PageDownClick;
}
_lineUpButton = e.NameScope.Find<Button>("PART_LineUpButton");
_lineDownButton = e.NameScope.Find<Button>("PART_LineDownButton");
_pageUpButton = e.NameScope.Find<Button>("PART_PageUpButton");
_pageDownButton = e.NameScope.Find<Button>("PART_PageDownButton");
if (_lineUpButton != null)
{
_lineUpButton.Click += LineUpClick;
}
if (_lineDownButton != null)
{
_lineDownButton.Click += LineDownClick;
}
if (_pageUpButton != null)
{
_pageUpButton.Click += PageUpClick;
}
if (_pageDownButton != null)
{
_pageDownButton.Click += PageDownClick;
}
}
private void InvokeAfterDelay(Action handler, TimeSpan delay)
{
if (_timer != null)
{
_timer.Stop();
}
else
{
_timer = new DispatcherTimer(DispatcherPriority.Normal);
_timer.Tick += (sender, args) =>
{
var senderTimer = (DispatcherTimer)sender!;
if (senderTimer.Tag is Action action)
{
action();
}
senderTimer.Stop();
};
}
_timer.Tag = handler;
_timer.Interval = delay;
_timer.Start();
}
private void UpdateIsExpandedState()
{
if (!AllowAutoHide)
{
_timer?.Stop();
IsExpanded = true;
}
else
{
IsExpanded = IsPointerOver;
}
}
private void CollapseAfterDelay()
{
InvokeAfterDelay(Collapse, HideDelay);
}
private void ExpandAfterDelay()
{
InvokeAfterDelay(Expand, ShowDelay);
}
private void Collapse()
{
IsExpanded = false;
}
private void Expand()
{
IsExpanded = true;
}
private void LineUpClick(object? sender, RoutedEventArgs e)
{
SmallDecrement();
}
private void LineDownClick(object? sender, RoutedEventArgs e)
{
SmallIncrement();
}
private void PageUpClick(object? sender, RoutedEventArgs e)
{
LargeDecrement();
}
private void PageDownClick(object? sender, RoutedEventArgs e)
{
LargeIncrement();
}
private void SmallDecrement()
{
Value = Math.Max(Value - SmallChange, Minimum);
OnScroll(ScrollEventType.SmallDecrement);
}
private void SmallIncrement()
{
Value = Math.Min(Value + SmallChange, Maximum);
OnScroll(ScrollEventType.SmallIncrement);
}
private void LargeDecrement()
{
Value = Math.Max(Value - LargeChange, Minimum);
OnScroll(ScrollEventType.LargeDecrement);
}
private void LargeIncrement()
{
Value = Math.Min(Value + LargeChange, Maximum);
OnScroll(ScrollEventType.LargeIncrement);
}
private void OnThumbDragDelta(VectorEventArgs e)
{
OnScroll(ScrollEventType.ThumbTrack);
}
private void OnThumbDragComplete(VectorEventArgs e)
{
OnScroll(ScrollEventType.EndScroll);
}
protected void OnScroll(ScrollEventType scrollEventType)
{
Scroll?.Invoke(this, new ScrollEventArgs(scrollEventType, Value));
}
private void UpdatePseudoClasses(Orientation o)
{
PseudoClasses.Set(":vertical", o == Orientation.Vertical);
PseudoClasses.Set(":horizontal", o == Orientation.Horizontal);
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Mono.Cecil {
public class AssemblyNameReference : IMetadataScope {
string name;
string culture;
Version version;
uint attributes;
byte [] public_key;
byte [] public_key_token;
AssemblyHashAlgorithm hash_algorithm;
byte [] hash;
internal MetadataToken token;
string full_name;
public string Name {
get { return name; }
set {
name = value;
full_name = null;
}
}
public string Culture {
get { return culture; }
set {
culture = value;
full_name = null;
}
}
public Version Version {
get { return version; }
set {
version = Mixin.CheckVersion (value);
full_name = null;
}
}
public AssemblyAttributes Attributes {
get { return (AssemblyAttributes) attributes; }
set { attributes = (uint) value; }
}
public bool HasPublicKey {
get { return attributes.GetAttributes ((uint) AssemblyAttributes.PublicKey); }
set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.PublicKey, value); }
}
public bool IsSideBySideCompatible {
get { return attributes.GetAttributes ((uint) AssemblyAttributes.SideBySideCompatible); }
set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.SideBySideCompatible, value); }
}
public bool IsRetargetable {
get { return attributes.GetAttributes ((uint) AssemblyAttributes.Retargetable); }
set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.Retargetable, value); }
}
public bool IsWindowsRuntime {
get { return attributes.GetAttributes ((uint) AssemblyAttributes.WindowsRuntime); }
set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.WindowsRuntime, value); }
}
public byte [] PublicKey {
get { return public_key ?? Empty<byte>.Array; }
set {
public_key = value;
HasPublicKey = !public_key.IsNullOrEmpty ();
public_key_token = Empty<byte>.Array;
full_name = null;
}
}
public byte [] PublicKeyToken {
get {
if (public_key_token.IsNullOrEmpty () && !public_key.IsNullOrEmpty ()) {
var hash = HashPublicKey ();
// we need the last 8 bytes in reverse order
var local_public_key_token = new byte [8];
Array.Copy (hash, (hash.Length - 8), local_public_key_token, 0, 8);
Array.Reverse (local_public_key_token, 0, 8);
public_key_token = local_public_key_token; // publish only once finished (required for thread-safety)
}
return public_key_token ?? Empty<byte>.Array;
}
set {
public_key_token = value;
full_name = null;
}
}
byte [] HashPublicKey ()
{
HashAlgorithm algorithm;
switch (hash_algorithm) {
case AssemblyHashAlgorithm.Reserved:
#if SILVERLIGHT
throw new NotSupportedException ();
#else
algorithm = MD5.Create ();
break;
#endif
default:
// None default to SHA1
#if SILVERLIGHT
algorithm = new SHA1Managed ();
break;
#else
algorithm = SHA1.Create ();
break;
#endif
}
using (algorithm)
return algorithm.ComputeHash (public_key);
}
public virtual MetadataScopeType MetadataScopeType {
get { return MetadataScopeType.AssemblyNameReference; }
}
public string FullName {
get {
if (full_name != null)
return full_name;
const string sep = ", ";
var builder = new StringBuilder ();
builder.Append (name);
builder.Append (sep);
builder.Append ("Version=");
builder.Append (version.ToString (fieldCount: 4));
builder.Append (sep);
builder.Append ("Culture=");
builder.Append (string.IsNullOrEmpty (culture) ? "neutral" : culture);
builder.Append (sep);
builder.Append ("PublicKeyToken=");
var pk_token = PublicKeyToken;
if (!pk_token.IsNullOrEmpty () && pk_token.Length > 0) {
for (int i = 0 ; i < pk_token.Length ; i++) {
builder.Append (pk_token [i].ToString ("x2"));
}
} else
builder.Append ("null");
return full_name = builder.ToString ();
}
}
public static AssemblyNameReference Parse (string fullName)
{
if (fullName == null)
throw new ArgumentNullException ("fullName");
if (fullName.Length == 0)
throw new ArgumentException ("Name can not be empty");
var name = new AssemblyNameReference ();
var tokens = fullName.Split (',');
for (int i = 0; i < tokens.Length; i++) {
var token = tokens [i].Trim ();
if (i == 0) {
name.Name = token;
continue;
}
var parts = token.Split ('=');
if (parts.Length != 2)
throw new ArgumentException ("Malformed name");
switch (parts [0].ToLowerInvariant ()) {
case "version":
name.Version = new Version (parts [1]);
break;
case "culture":
name.Culture = parts [1] == "neutral" ? "" : parts [1];
break;
case "publickeytoken":
var pk_token = parts [1];
if (pk_token == "null")
break;
name.PublicKeyToken = new byte [pk_token.Length / 2];
for (int j = 0; j < name.PublicKeyToken.Length; j++)
name.PublicKeyToken [j] = Byte.Parse (pk_token.Substring (j * 2, 2), NumberStyles.HexNumber);
break;
}
}
return name;
}
public AssemblyHashAlgorithm HashAlgorithm {
get { return hash_algorithm; }
set { hash_algorithm = value; }
}
public virtual byte [] Hash {
get { return hash; }
set { hash = value; }
}
public MetadataToken MetadataToken {
get { return token; }
set { token = value; }
}
internal AssemblyNameReference ()
{
this.version = Mixin.ZeroVersion;
this.token = new MetadataToken (TokenType.AssemblyRef);
}
public AssemblyNameReference (string name, Version version)
{
if (name == null)
throw new ArgumentNullException ("name");
this.name = name;
this.version = Mixin.CheckVersion (version);
this.hash_algorithm = AssemblyHashAlgorithm.None;
this.token = new MetadataToken (TokenType.AssemblyRef);
}
public override string ToString ()
{
return this.FullName;
}
}
partial class Mixin {
public static Version ZeroVersion = new Version (0, 0, 0 ,0);
public static Version CheckVersion (Version version)
{
if (version == null)
return ZeroVersion;
if (version.Build == -1)
return new Version (version.Major, version.Minor, 0, 0);
if (version.Revision == -1)
return new Version (version.Major, version.Minor, version.Build, 0);
return version;
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Avalonia.Diagnostics;
using Avalonia.Platform;
namespace Avalonia.Collections
{
/// <summary>
/// Describes the action notified on a clear of a <see cref="AvaloniaList{T}"/>.
/// </summary>
public enum ResetBehavior
{
/// <summary>
/// Clearing the list notifies a with a
/// <see cref="NotifyCollectionChangedAction.Reset"/>.
/// </summary>
Reset,
/// <summary>
/// Clearing the list notifies a with a
/// <see cref="NotifyCollectionChangedAction.Remove"/>.
/// </summary>
Remove,
}
/// <summary>
/// A notifying list.
/// </summary>
/// <typeparam name="T">The type of the list items.</typeparam>
/// <remarks>
/// <para>
/// AvaloniaList is similar to <see cref="System.Collections.ObjectModel.ObservableCollection{T}"/>
/// with a few added features:
/// </para>
///
/// <list type="bullet">
/// <item>
/// It can be configured to notify the <see cref="CollectionChanged"/> event with a
/// <see cref="NotifyCollectionChangedAction.Remove"/> action instead of a
/// <see cref="NotifyCollectionChangedAction.Reset"/> when the list is cleared by
/// setting <see cref="ResetBehavior"/> to <see cref="ResetBehavior.Remove"/>.
/// removed
/// </item>
/// <item>
/// A <see cref="Validate"/> function can be used to validate each item before insertion.
/// removed
/// </item>
/// </list>
/// </remarks>
public class AvaloniaList<T> : IAvaloniaList<T>, IList, INotifyCollectionChangedDebug
{
private List<T> _inner;
private NotifyCollectionChangedEventHandler _collectionChanged;
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class.
/// </summary>
public AvaloniaList()
: this(Enumerable.Empty<T>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class.
/// </summary>
/// <param name="items">The initial items for the collection.</param>
public AvaloniaList(IEnumerable<T> items)
{
_inner = new List<T>(items);
}
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class.
/// </summary>
/// <param name="items">The initial items for the collection.</param>
public AvaloniaList(params T[] items)
{
_inner = new List<T>(items);
}
/// <summary>
/// Raised when a change is made to the collection's items.
/// </summary>
public event NotifyCollectionChangedEventHandler CollectionChanged
{
add { _collectionChanged += value; }
remove { _collectionChanged -= value; }
}
/// <summary>
/// Raised when a property on the collection changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets the number of items in the collection.
/// </summary>
public int Count => _inner.Count;
/// <summary>
/// Gets or sets the reset behavior of the list.
/// </summary>
public ResetBehavior ResetBehavior { get; set; }
/// <summary>
/// Gets or sets a validation routine that can be used to validate items before they are
/// added.
/// </summary>
public Action<T> Validate { get; set; }
/// <inheritdoc/>
bool IList.IsFixedSize => false;
/// <inheritdoc/>
bool IList.IsReadOnly => false;
/// <inheritdoc/>
int ICollection.Count => _inner.Count;
/// <inheritdoc/>
bool ICollection.IsSynchronized => false;
/// <inheritdoc/>
object ICollection.SyncRoot => null;
/// <inheritdoc/>
bool ICollection<T>.IsReadOnly => false;
/// <summary>
/// Gets or sets the item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>The item.</returns>
public T this[int index]
{
get
{
return _inner[index];
}
set
{
Validate?.Invoke(value);
T old = _inner[index];
if (!object.Equals(old, value))
{
_inner[index] = value;
if (_collectionChanged != null)
{
var e = new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Replace,
value,
old,
index);
_collectionChanged(this, e);
}
}
}
}
/// <summary>
/// Gets or sets the item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>The item.</returns>
object IList.this[int index]
{
get { return this[index]; }
set { this[index] = (T)value; }
}
/// <summary>
/// Adds an item to the collection.
/// </summary>
/// <param name="item">The item.</param>
public virtual void Add(T item)
{
Validate?.Invoke(item);
int index = _inner.Count;
_inner.Add(item);
NotifyAdd(new[] { item }, index);
}
/// <summary>
/// Adds multiple items to the collection.
/// </summary>
/// <param name="items">The items.</param>
public virtual void AddRange(IEnumerable<T> items)
{
Contract.Requires<ArgumentNullException>(items != null);
var list = (items as IList) ?? items.ToList();
if (list.Count > 0)
{
if (Validate != null)
{
foreach (var item in list)
{
Validate((T)item);
}
}
int index = _inner.Count;
_inner.AddRange(items);
NotifyAdd(list, index);
}
}
/// <summary>
/// Removes all items from the collection.
/// </summary>
public virtual void Clear()
{
if (this.Count > 0)
{
var old = _inner;
_inner = new List<T>();
NotifyReset(old);
}
}
/// <summary>
/// Tests if the collection contains the specified item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>True if the collection contains the item; otherwise false.</returns>
public bool Contains(T item)
{
return _inner.Contains(item);
}
/// <summary>
/// Copies the collection's contents to an array.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">The first index of the array to copy to.</param>
public void CopyTo(T[] array, int arrayIndex)
{
_inner.CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns an enumerator that enumerates the items in the collection.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}"/>.</returns>
public IEnumerator<T> GetEnumerator()
{
return _inner.GetEnumerator();
}
/// <summary>
/// Gets a range of items from the collection.
/// </summary>
/// <param name="index">The first index to remove.</param>
/// <param name="count">The number of items to remove.</param>
public IEnumerable<T> GetRange(int index, int count)
{
return _inner.GetRange(index, count);
}
/// <summary>
/// Gets the index of the specified item in the collection.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>
/// The index of the item or -1 if the item is not contained in the collection.
/// </returns>
public int IndexOf(T item)
{
return _inner.IndexOf(item);
}
/// <summary>
/// Inserts an item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="item">The item.</param>
public virtual void Insert(int index, T item)
{
Validate?.Invoke(item);
_inner.Insert(index, item);
NotifyAdd(new[] { item }, index);
}
/// <summary>
/// Inserts multiple items at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="items">The items.</param>
public virtual void InsertRange(int index, IEnumerable<T> items)
{
Contract.Requires<ArgumentNullException>(items != null);
var list = (items as IList) ?? items.ToList();
if (list.Count > 0)
{
if (Validate != null)
{
foreach (var item in list)
{
Validate((T)item);
}
}
_inner.InsertRange(index, items);
NotifyAdd((items as IList) ?? items.ToList(), index);
}
}
/// <summary>
/// Moves an item to a new index.
/// </summary>
/// <param name="oldIndex">The index of the item to move.</param>
/// <param name="newIndex">The index to move the item to.</param>
public void Move(int oldIndex, int newIndex)
{
var item = this[oldIndex];
_inner.RemoveAt(oldIndex);
_inner.Insert(newIndex, item);
if (_collectionChanged != null)
{
var e = new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Move,
item,
newIndex,
oldIndex);
_collectionChanged(this, e);
}
}
/// <summary>
/// Moves multiple items to a new index.
/// </summary>
/// <param name="oldIndex">The first index of the items to move.</param>
/// <param name="count">The number of items to move.</param>
/// <param name="newIndex">The index to move the items to.</param>
public void MoveRange(int oldIndex, int count, int newIndex)
{
var items = _inner.GetRange(oldIndex, count);
var modifiedNewIndex = newIndex;
_inner.RemoveRange(oldIndex, count);
if (newIndex > oldIndex)
{
modifiedNewIndex -= count;
}
_inner.InsertRange(modifiedNewIndex, items);
if (_collectionChanged != null)
{
var e = new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Move,
items,
newIndex,
oldIndex);
_collectionChanged(this, e);
}
}
/// <summary>
/// Removes an item from the collection.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>True if the item was found and removed, otherwise false.</returns>
public virtual bool Remove(T item)
{
int index = _inner.IndexOf(item);
if (index != -1)
{
_inner.RemoveAt(index);
NotifyRemove(new[] { item }, index);
return true;
}
return false;
}
/// <summary>
/// Removes multiple items from the collection.
/// </summary>
/// <param name="items">The items.</param>
public virtual void RemoveAll(IEnumerable<T> items)
{
Contract.Requires<ArgumentNullException>(items != null);
foreach (var i in items)
{
// TODO: Optimize to only send as many notifications as necessary.
Remove(i);
}
}
/// <summary>
/// Removes the item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
public virtual void RemoveAt(int index)
{
T item = _inner[index];
_inner.RemoveAt(index);
NotifyRemove(new[] { item }, index);
}
/// <summary>
/// Removes a range of elements from the collection.
/// </summary>
/// <param name="index">The first index to remove.</param>
/// <param name="count">The number of items to remove.</param>
public virtual void RemoveRange(int index, int count)
{
if (count > 0)
{
var list = _inner.GetRange(index, count);
_inner.RemoveRange(index, count);
NotifyRemove(list, index);
}
}
/// <inheritdoc/>
int IList.Add(object value)
{
int index = Count;
Add((T)value);
return index;
}
/// <inheritdoc/>
bool IList.Contains(object value)
{
return Contains((T)value);
}
/// <inheritdoc/>
void IList.Clear()
{
Clear();
}
/// <inheritdoc/>
int IList.IndexOf(object value)
{
return IndexOf((T)value);
}
/// <inheritdoc/>
void IList.Insert(int index, object value)
{
Insert(index, (T)value);
}
/// <inheritdoc/>
void IList.Remove(object value)
{
Remove((T)value);
}
/// <inheritdoc/>
void IList.RemoveAt(int index)
{
RemoveAt(index);
}
/// <inheritdoc/>
void ICollection.CopyTo(Array array, int index)
{
_inner.CopyTo((T[])array, index);
}
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator()
{
return _inner.GetEnumerator();
}
/// <inheritdoc/>
Delegate[] INotifyCollectionChangedDebug.GetCollectionChangedSubscribers() => _collectionChanged?.GetInvocationList();
/// <summary>
/// Raises the <see cref="CollectionChanged"/> event with an add action.
/// </summary>
/// <param name="t">The items that were added.</param>
/// <param name="index">The starting index.</param>
private void NotifyAdd(IList t, int index)
{
if (_collectionChanged != null)
{
var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, t, index);
_collectionChanged(this, e);
}
NotifyCountChanged();
}
/// <summary>
/// Raises the <see cref="PropertyChanged"/> event when the <see cref="Count"/> property
/// changes.
/// </summary>
private void NotifyCountChanged()
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Count"));
}
/// <summary>
/// Raises the <see cref="CollectionChanged"/> event with a remove action.
/// </summary>
/// <param name="t">The items that were removed.</param>
/// <param name="index">The starting index.</param>
private void NotifyRemove(IList t, int index)
{
if (_collectionChanged != null)
{
var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, t, index);
_collectionChanged(this, e);
}
NotifyCountChanged();
}
/// <summary>
/// Raises the <see cref="CollectionChanged"/> event with a reset action.
/// </summary>
/// <param name="t">The items that were removed.</param>
private void NotifyReset(IList t)
{
if (_collectionChanged != null)
{
NotifyCollectionChangedEventArgs e;
e = ResetBehavior == ResetBehavior.Reset ?
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset) :
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, t, 0);
_collectionChanged(this, e);
}
NotifyCountChanged();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Compiler;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Contracts.Foxtrot.Utils;
namespace Microsoft.Contracts.Foxtrot
{
/// <summary>
/// Visitor that creates special closure type for async postconditions.
/// </summary>
/// <remarks>
///
/// Current class generate AsyncClosure with CheckMethod and CheckException methods.
///
/// Following transformation are applied to the original async method:
///
/// // This is oroginal task, generated by the AsyncTaskMethodBuilder
/// var originalTask = t_builder.Task;
///
/// var closure = new AsyncClosure();
/// var task2 = originalTask.ContinueWith(closure.CheckPost).Unwrap();
/// return task2;
///
/// There are 2 cases:
/// 1) Task has no return value.
/// In this case only EnsuresOnThrow could be used, and we emit:
/// Task CheckMethod(Task t)
/// {
/// if (t.Status == TaskStatus.Faulted)
/// {
/// // CheckException will throw if EnsuresOnThrow is not held
/// CheckException(t.Exception);
/// }
///
/// return t;
/// }
///
/// 2) Task(T) reutrns a T value.
/// In this case both EnsuresOnThrow and Contract.Ensures(Contract.Result) could be used.
/// We emit:
///
/// Task<int> CheckMethod(Task<int> t)
/// {
/// if (t.Status == TaskStatus.Faulted)
/// {
/// // CheckException will throw if EnsuresOnThrow is not held
/// CheckException(t.Exception);
/// }
///
/// if (t.Status == TaskStatus.RanToCompletion)
/// {
/// // Check ensures
/// }
/// }
/// </remarks>
internal class EmitAsyncClosure : StandardVisitor
{
/// <summary>
/// Class that maps generic arguments of the enclosed class/method to the generic arguments of the closure.
/// </summary>
/// <remarks>
/// The problem.
/// Original implementation of the Code Contract didn't support async postconditions in generics.
/// Here is why:
/// Suppose we have following function (in class <c>Foo</c>:
/// <code><![CDATA[
/// public static Task<T> FooAsync() where T: class
/// {
/// Contract.Ensures(Contract.Result<T>() != null);
/// }
/// ]]></code>
/// In this case, ccrewrite will generate async closure class called <c>Foo.AsyncContractClosure_0<T></c>
/// with following structure:
/// <code><![CDATA[
/// [CompilerGenerated]
/// private class <Foo>AsyncContractClosure_0<T> where T : class
/// {
/// public Task<T> CheckPost(Task<T> task)
/// {
/// TaskStatus status = task.Status;
/// if (status == TaskStatus.RanToCompletion)
/// {
/// RewriterMethods.Ensures(task.Result != null, null, "Contract.Result<T>() != null");
/// }
/// return task;
/// }
/// }
/// ]]>
/// </code>
/// The code looks good, but the IL could be invalid (without the trick that this class provides).
/// Postcondition of the method in our case is declared in the generic method (in <code>FooAsync</code>)
/// but ccrewrite moves it into non-generic method (<code>CheckPost</code>) of the generic class (closure).
///
/// But on IL level there is different instructions for referencing method generic arguments and type generic arguments.
///
/// After changing <code>Contract.Result</code> to <code>task.Result</code> and moving postcondition to <code>CheckPost</code>
/// method, following IL would be generated:
///
/// <code> <![CDATA[
/// IL_0011: call instance !0 class [mscorlib]System.Threading.Tasks.Task`1<!T>::get_Result()
/// IL_0016: box !!0 // <-- here is our problem!
/// ]]>
/// </code>
///
/// This means that method <code>CheckPost</code> would contains a reference to generic method argument of the
/// original method.
///
/// The goal of this class is to store a mapping between enclosing generic types and closure generic types.
/// </remarks>
private class GenericTypeMapper
{
class TypeNodePair
{
public TypeNodePair(TypeNode enclosingGenericType, TypeNode closureGenericType)
{
EnclosingGenericType = enclosingGenericType;
ClosureGenericType = closureGenericType;
}
public TypeNode EnclosingGenericType { get; private set; }
public TypeNode ClosureGenericType { get; private set; }
}
// Mapping between enclosing generic type and closure generic type.
// This is a simple list not a dictionary, because number of generic arguments is very small.
// So linear complexity will not harm performance.
private List<TypeNodePair> typeParametersMapping = new List<TypeNodePair>();
public bool IsEmpty { get { return typeParametersMapping.Count == 0; } }
public void AddMapping(TypeNode enclosingGenericType, TypeNode closureGenericType)
{
typeParametersMapping.Add(new TypeNodePair(enclosingGenericType, closureGenericType));
}
/// <summary>
/// Returns associated generic type of the closure class by enclosing generic type (for instance, by
/// generic type of the enclosing generic method that uses current closure).
/// </summary>
/// <remarks>
/// Function returns the same argument if the matching argument does not exists.
/// </remarks>
public TypeNode GetClosureTypeParameterByEnclosingTypeParameter(TypeNode enclosingType)
{
if (enclosingType == null)
{
return null;
}
var gen = enclosingType;
if (gen.ConsolidatedTemplateParameters != null && gen.ConsolidatedTemplateParameters.Count != 0)
{
gen = gen.ConsolidatedTemplateParameters[0];
}
var candidate = typeParametersMapping.FirstOrDefault(t => t.EnclosingGenericType == enclosingType);
return candidate != null ? candidate.ClosureGenericType : enclosingType;
}
/// <summary>
/// Returns associated generic type of the closure class by enclosing generic type (for instance, by
/// generic type of the enclosing generic method that uses current closure).
/// </summary>
/// <remarks>
/// Function returns the same argument if the matching argument does not exists.
/// </remarks>
public TypeNode GetEnclosingTypeParameterByClosureTypeParameter(TypeNode closureType)
{
if (closureType == null)
{
return null;
}
var candidate = typeParametersMapping.FirstOrDefault(t => t.ClosureGenericType == closureType);
return candidate != null ? candidate.EnclosingGenericType : closureType;
}
}
// This assembly should be in this class but not in the SystemTypes from System.CompilerCC.
// Moving this type there will lead to test failures and assembly resolution errors.
private static readonly AssemblyNode/*!*/ SystemCoreAssembly = SystemTypes.GetSystemCoreAssembly(false, true);
private static TypeNode TaskExtensionsTypeNode = HelperMethods.FindType(
SystemCoreAssembly,
Identifier.For("System.Threading.Tasks"),
Identifier.For("TaskExtensions"));
private static readonly Identifier CheckExceptionMethodId = Identifier.For("CheckException");
private static readonly Identifier CheckMethodId = Identifier.For("CheckPost");
private readonly Cache<TypeNode> aggregateExceptionType;
private readonly Cache<TypeNode> func2Type;
private readonly Dictionary<Local, MemberBinding> closureLocals = new Dictionary<Local, MemberBinding>();
private readonly List<SourceContext> contractResultCapturedInStaticContext = new List<SourceContext>();
private readonly Rewriter rewriter;
private readonly TypeNode declaringType;
private readonly Class closureClass;
private readonly Class closureClassInstance;
private readonly Specializer /*?*/ forwarder;
private readonly Local closureLocal;
// Fields for the CheckMethod generation
private Method checkPostMethod;
private StatementList checkPostBody;
// Holds a copy of CheckMethod argument
private Local originalResultLocal;
private Parameter checkMethodTaskParameter;
private readonly TypeNode checkMethodTaskType;
private readonly GenericTypeMapper genericTypeMapper = new GenericTypeMapper();
public EmitAsyncClosure(Method from, Rewriter rewriter)
{
Contract.Requires(from != null);
Contract.Requires(from.DeclaringType != null);
Contract.Requires(rewriter != null);
if (TaskExtensionsTypeNode == null)
{
throw new InvalidOperationException(
"Can't generate async closure because System.Threading.Tasks.TaskExceptions class is unavailable.");
}
this.rewriter = rewriter;
this.declaringType = from.DeclaringType;
var closureName = HelperMethods.NextUnusedMemberName(declaringType, "<" + from.Name.Name + ">AsyncContractClosure");
this.closureClass = new Class(
declaringModule: declaringType.DeclaringModule,
declaringType: declaringType,
attributes: null,
flags: TypeFlags.NestedPrivate,
Namespace: null,
name: Identifier.For(closureName),
baseClass: SystemTypes.Object,
interfaces: null,
members: null);
declaringType.Members.Add(this.closureClass);
RewriteHelper.TryAddCompilerGeneratedAttribute(this.closureClass);
var taskType = from.ReturnType;
this.aggregateExceptionType = new Cache<TypeNode>(() =>
HelperMethods.FindType(rewriter.AssemblyBeingRewritten, StandardIds.System,
Identifier.For("AggregateException")));
this.func2Type = new Cache<TypeNode>(() =>
HelperMethods.FindType(SystemTypes.SystemAssembly, StandardIds.System, Identifier.For("Func`2")));
// Should distinguish between generic enclosing method and non-generic method in enclosing type.
// In both cases generated closure should be generic.
var enclosingTemplateParameters = GetGenericTypesFrom(from);
if (!enclosingTemplateParameters.IsNullOrEmpty())
{
this.closureClass.TemplateParameters = CreateTemplateParameters(closureClass, enclosingTemplateParameters, declaringType);
this.closureClass.IsGeneric = true;
this.closureClass.EnsureMangledName();
this.forwarder = new Specializer(
targetModule: this.declaringType.DeclaringModule,
pars: enclosingTemplateParameters,
args: this.closureClass.TemplateParameters);
this.forwarder.VisitTypeParameterList(this.closureClass.TemplateParameters);
taskType = this.forwarder.VisitTypeReference(taskType);
for (int i = 0; i < enclosingTemplateParameters.Count; i++)
{
this.genericTypeMapper.AddMapping(enclosingTemplateParameters[i], closureClass.TemplateParameters[i]);
}
}
else
{
this.closureClassInstance = this.closureClass;
}
this.checkMethodTaskType = taskType;
// Emiting CheckPost method declaration
EmitCheckPostMethodCore(checkMethodTaskType);
// Generate closure constructor.
// Constructor should be generated AFTER visiting type parameters in
// the previous block of code. Otherwise current class would not have
// appropriate number of generic arguments!
var ctor = CreateConstructor(closureClass);
closureClass.Members.Add(ctor);
// Now that we added the ctor and the check method, let's instantiate the closure class if necessary
if (this.closureClassInstance == null)
{
var consArgs = new TypeNodeList();
var args = new TypeNodeList();
var parentCount = this.closureClass.DeclaringType.ConsolidatedTemplateParameters == null
? 0
: this.closureClass.DeclaringType.ConsolidatedTemplateParameters.Count;
for (int i = 0; i < parentCount; i++)
{
consArgs.Add(this.closureClass.DeclaringType.ConsolidatedTemplateParameters[i]);
}
if (!enclosingTemplateParameters.IsNullOrEmpty())
{
for (int i = 0; i < enclosingTemplateParameters.Count; i++)
{
consArgs.Add(enclosingTemplateParameters[i]);
args.Add(enclosingTemplateParameters[i]);
}
}
this.closureClassInstance =
(Class)
this.closureClass.GetConsolidatedTemplateInstance(this.rewriter.AssemblyBeingRewritten,
closureClass.DeclaringType, closureClass.DeclaringType, args, consArgs);
}
// create closure initializer for context method
this.closureLocal = new Local(this.ClosureClass);
this.ClosureInitializer = new Block(new StatementList());
// Generate constructor call that initializes closure instance
this.ClosureInitializer.Statements.Add(
new AssignmentStatement(
this.closureLocal,
new Construct(new MemberBinding(null, this.Ctor), new ExpressionList())));
}
/// <summary>
/// Add postconditions for the task-based methods.
/// </summary>
/// <remarks>
/// Method inserts all required logic to the <paramref name="returnBlock"/> calling
/// ContinueWith method on the <paramref name="taskBasedResult"/>.
/// </remarks>
public void AddAsyncPostconditions(List<Ensures> asyncPostconditions, Block returnBlock, Local taskBasedResult)
{
Contract.Requires(asyncPostconditions != null);
Contract.Requires(returnBlock != null);
Contract.Requires(taskBasedResult != null);
Contract.Requires(asyncPostconditions.Count > 0);
// Async postconditions are impelemented using custom closure class
// with CheckPost method that checks postconditions when the task
// is finished.
// Add Async postconditions to the AsyncClosure
AddAsyncPost(asyncPostconditions);
// Add task.ContinueWith().Unwrap(); method call to returnBlock
AddContinueWithMethodToReturnBlock(returnBlock, taskBasedResult);
ChangeThisReferencesToClosureLocals();
}
private void ChangeThisReferencesToClosureLocals()
{
var fieldRewriter = new FieldRewriter(this);
fieldRewriter.Visit(this.checkPostMethod);
}
/// <summary>
/// Returns a list of source spans where non-capturing lambdas were used.
/// </summary>
public IList<SourceContext> ContractResultCapturedInStaticContext
{
get { return contractResultCapturedInStaticContext; }
}
/// <summary>
/// Instance used in calling method context
/// </summary>
public Class ClosureClass
{
get { return this.closureClassInstance; }
}
/// <summary>
/// Local instance of the async closure class
/// </summary>
public Local ClosureLocal { get { return this.closureLocal; } }
/// <summary>
/// Block of code, responsible for closure instance initialization
/// </summary>
public Block ClosureInitializer { get; private set; }
private InstanceInitializer Ctor
{
get { return (InstanceInitializer)this.closureClassInstance.GetMembersNamed(StandardIds.Ctor)[0]; }
}
private static TypeNodeList GetGenericTypesFrom(Method method)
{
if (method.IsGeneric)
{
return method.TemplateParameters;
}
if (method.DeclaringType.IsGeneric)
{
return GetFirstNonEmptyGenericListWalkingUpDeclaringTypes(method.DeclaringType);
}
return null;
}
private static TypeNodeList GetFirstNonEmptyGenericListWalkingUpDeclaringTypes(TypeNode node)
{
if (node == null)
{
return null;
}
if (node.TemplateParameters != null && node.TemplateParameters.Count != 0)
{
return node.TemplateParameters;
}
return GetFirstNonEmptyGenericListWalkingUpDeclaringTypes(node.DeclaringType);
}
[Pure]
private static TypeNodeList CreateTemplateParameters(Class closureClass, TypeNodeList inputTemplateParameters, TypeNode declaringType)
{
Contract.Requires(closureClass != null);
Contract.Requires(inputTemplateParameters != null);
Contract.Requires(declaringType != null);
var dup = new Duplicator(declaringType.DeclaringModule, declaringType);
var templateParameters = new TypeNodeList();
var parentCount = declaringType.ConsolidatedTemplateParameters.CountOrDefault();
for (int i = 0; i < inputTemplateParameters.Count; i++)
{
var tp = HelperMethods.NewEqualTypeParameter(
dup, (ITypeParameter)inputTemplateParameters[i],
closureClass, parentCount + i);
templateParameters.Add(tp);
}
return templateParameters;
}
private void AddContinueWithMethodToReturnBlock(Block returnBlock, Local taskBasedResult)
{
Contract.Requires(returnBlock != null);
Contract.Requires(taskBasedResult != null);
var taskType = taskBasedResult.Type;
// To find appropriate ContinueWith method task type should be unwrapped
var taskTemplate = HelperMethods.Unspecialize(taskType);
var continueWithMethodLocal = GetContinueWithMethod(closureClass, taskTemplate, taskType);
// TODO: not sure that this is possible situation when continueWith method is null.
// Maybe Contract.Assert(continueWithMethod != null) should be used instead!
if (continueWithMethodLocal != null)
{
// We need to create delegate instance that should be passed to ContinueWith method
var funcType = continueWithMethodLocal.Parameters[0].Type;
var funcCtor = funcType.GetConstructor(SystemTypes.Object, SystemTypes.IntPtr);
Contract.Assume(funcCtor != null);
var funcLocal = new Local(funcCtor.DeclaringType);
// Creating a method pointer to the AsyncClosure.CheckMethod
// In this case we can't use checkMethod field.
// Getting CheckMethod from clsoureClassInstance will provide correct (potentially updated)
// generic arguments for enclosing type.
var checkMethodFromClosureInstance = (Method) closureClassInstance.GetMembersNamed(CheckMethodId)[0];
Contract.Assume(checkMethodFromClosureInstance != null);
var ldftn = new UnaryExpression(
new MemberBinding(null, checkMethodFromClosureInstance),
NodeType.Ldftn,
CoreSystemTypes.IntPtr);
// Creating delegate that would be used as a continuation for original task
returnBlock.Statements.Add(
new AssignmentStatement(funcLocal,
new Construct(new MemberBinding(null, funcCtor),
new ExpressionList(closureLocal, ldftn))));
// Wrapping continuation into TaskExtensions.Unwrap method
// (this helps to preserve original exception and original result of the task,
// but allows to throw postconditions violations).
// Generating: result.ContinueWith(closure.CheckPost);
var taskContinuationOption = new Literal(TaskContinuationOptions.ExecuteSynchronously);
var continueWithCall =
new MethodCall(
new MemberBinding(taskBasedResult, continueWithMethodLocal),
new ExpressionList(funcLocal, taskContinuationOption));
// Generating: TaskExtensions.Unwrap(result.ContinueWith(...))
var unwrapMethod = GetUnwrapMethod(checkMethodTaskType);
var unwrapCall =
new MethodCall(
new MemberBinding(null, unwrapMethod), new ExpressionList(continueWithCall));
// Generating: result = Unwrap(...);
var resultAssignment =
new AssignmentStatement(taskBasedResult, unwrapCall);
returnBlock.Statements.Add(resultAssignment);
}
}
/// <summary>
/// Method generates core part of the CheckMethod
/// </summary>
private void EmitCheckPostMethodCore(TypeNode taskType)
{
Contract.Requires(taskType != null);
this.checkMethodTaskParameter = new Parameter(Identifier.For("task"), taskType);
// TODO ST: can I switch to new Local(taskType.Type)?!? In this case this initialization
// could be moved outside this method
this.originalResultLocal = new Local(new Identifier("taskLocal"), checkMethodTaskParameter.Type);
// Generate: public Task<T> CheckPost(Task<T> task) where T is taskType or
// public Task CheckPost(Task task) for non-generic task.
checkPostMethod = new Method(
declaringType: this.closureClass,
attributes: null,
name: CheckMethodId,
parameters: new ParameterList(checkMethodTaskParameter),
// was: taskType.TemplateArguments[0] when hasResult was true and SystemTypes.Void otherwise
returnType: taskType,
body: null);
checkPostMethod.CallingConvention = CallingConventionFlags.HasThis;
checkPostMethod.Flags |= MethodFlags.Public;
this.checkPostBody = new StatementList();
this.closureClass.Members.Add(this.checkPostMethod);
if (taskType.IsGeneric)
{
// Assign taskParameter to originalResultLocal because
// this field is used in a postcondition
checkPostBody.Add(new AssignmentStatement(this.originalResultLocal, checkMethodTaskParameter));
}
}
[ContractVerification(false)]
private void AddAsyncPost(List<Ensures> asyncPostconditions)
{
var origBody = new Block(this.checkPostBody);
origBody.HasLocals = true;
var newBodyBlock = new Block(new StatementList());
newBodyBlock.HasLocals = true;
var methodBody = new StatementList();
var methodBodyBlock = new Block(methodBody);
methodBodyBlock.HasLocals = true;
checkPostMethod.Body = methodBodyBlock;
methodBody.Add(newBodyBlock);
Block newExitBlock = new Block();
methodBody.Add(newExitBlock);
// Map closure locals to fields and initialize closure fields
foreach (Ensures e in asyncPostconditions)
{
if (e == null) continue;
this.Visit(e);
if (this.forwarder != null)
{
this.forwarder.Visit(e);
}
ReplaceResult repResult = new ReplaceResult(
this.checkPostMethod, this.originalResultLocal,
this.rewriter.AssemblyBeingRewritten);
repResult.Visit(e);
if (repResult.ContractResultWasCapturedInStaticContext)
{
this.contractResultCapturedInStaticContext.Add(e.Assertion.SourceContext);
}
// now need to initialize closure result fields
foreach (var target in repResult.NecessaryResultInitializationAsync(this.closureLocals))
{
// note: target here
methodBody.Add(new AssignmentStatement(target, this.originalResultLocal));
}
}
// Emit normal postconditions
SourceContext? lastEnsuresSourceContext = null;
var ensuresChecks = new StatementList();
Method contractEnsuresMethod = this.rewriter.RuntimeContracts.EnsuresMethod;
// For generic types need to 'fix' generic type parameters that are used in the closure method.
// See comment to the GenericTypeMapper for more details.
TypeParameterFixerVisitor fixer = null;
if (!this.genericTypeMapper.IsEmpty)
{
fixer = new TypeParameterFixerVisitor(genericTypeMapper);
}
foreach (Ensures e in GetTaskResultBasedEnsures(asyncPostconditions))
{
// TODO: Not sure that 'break' is enough! It seems that this is possible
// only when something is broken, because normal postconditions
// are using Contract.Result<T>() and this is possible only for
// generic tasks.
if (IsVoidTask()) break; // something is wrong in the original contract
lastEnsuresSourceContext = e.SourceContext;
//
// Call Contract.RewriterEnsures
//
ExpressionList args = new ExpressionList();
if (fixer != null)
{
fixer.Visit(e.PostCondition);
}
args.Add(e.PostCondition);
args.Add(e.UserMessage ?? Literal.Null);
args.Add(e.SourceConditionText ?? Literal.Null);
ensuresChecks.Add(
new ExpressionStatement(
new MethodCall(
new MemberBinding(null, contractEnsuresMethod),
args, NodeType.Call, SystemTypes.Void),
e.SourceContext));
}
this.rewriter.CleanUpCodeCoverage.VisitStatementList(ensuresChecks);
//
// Normal postconditions
//
// Wrapping normal ensures into following if statement
// if (task.Status == TaskStatus.RanToCompletion)
// { postcondition check }
//
// Implementation of this stuff is a bit tricky because if-statements
// are inverse in the IL.
// Basically, we need to generate following code:
// if (!(task.Status == Task.Status.RanToCompletion))
// goto EndOfNormalPostcondition;
// {postcondition check}
// EndOfNormalPostcondition:
// {other Code}
// Marker for EndOfNormalPostcondition
Block endOfNormalPostcondition = new Block();
// Generate: if (task.Status != RanToCompletion) goto endOfNormalPostcondition;
StatementList checkStatusStatements = CreateIfTaskResultIsEqualsTo(
checkMethodTaskParameter, TaskStatus.RanToCompletion, endOfNormalPostcondition);
methodBodyBlock.Statements.Add(new Block(checkStatusStatements));
// Emit a check for __ContractsRuntime.insideContractEvaluation around Ensures
// TODO ST: there is no sense to add recursion check in async postcondition that can be checked in different thread!
methodBodyBlock.Statements.Add(new Block(ensuresChecks));
// Emit a check for __ContractsRuntime.insideContractEvaluation around Ensures
//this.rewriter.EmitRecursionGuardAroundChecks(this.checkPostMethod, methodBodyBlock, ensuresChecks);
// Now, normal postconditions are written to the method body.
// We need to add endOfNormalPostcondition block as a marker.
methodBodyBlock.Statements.Add(endOfNormalPostcondition);
//
// Exceptional postconditions
//
var exceptionalPostconditions = GetExceptionalEnsures(asyncPostconditions).ToList();
if (exceptionalPostconditions.Count > 0)
{
// For exceptional postconditions we need to generate CheckException method first
Method checkExceptionMethod = CreateCheckExceptionMethod();
EmitCheckExceptionBody(checkExceptionMethod, exceptionalPostconditions);
this.closureClass.Members.Add(checkExceptionMethod);
// Then, we're using the same trick as for normal postconditions:
// wrapping exceptional postconditions only when task.Status is TaskStatus.Faulted
Block checkExceptionBlock = new Block(new StatementList());
// Marker for endOfExceptionPostcondition
Block endOfExceptionPostcondition = new Block();
StatementList checkStatusIsException = CreateIfTaskResultIsEqualsTo(
checkMethodTaskParameter, TaskStatus.Faulted, endOfExceptionPostcondition);
checkExceptionBlock.Statements.Add(new Block(checkStatusIsException));
// Now we need to emit actuall check for exceptional postconditions
// Emit: var ae = task.Exception;
var aeLocal = new Local(aggregateExceptionType.Value);
checkExceptionBlock.Statements.Add(
new AssignmentStatement(aeLocal,
new MethodCall(
new MemberBinding(checkMethodTaskParameter,
GetTaskProperty(checkMethodTaskParameter, "get_Exception")),
new ExpressionList())));
// Emit: CheckException(ae);
// Need to store method result somewhere, otherwise stack would be corrupted
var checkResultLocal = new Local(SystemTypes.Boolean);
checkExceptionBlock.Statements.Add(
new AssignmentStatement(checkResultLocal,
new MethodCall(new MemberBinding(null,
checkExceptionMethod),
new ExpressionList(checkExceptionMethod.ThisParameter, aeLocal))));
checkExceptionBlock.Statements.Add(endOfExceptionPostcondition);
methodBody.Add(checkExceptionBlock);
}
// Copy original block to body statement for both: normal and exceptional postconditions.
newBodyBlock.Statements.Add(origBody);
Block returnBlock = CreateReturnBlock(checkMethodTaskParameter, lastEnsuresSourceContext);
methodBody.Add(returnBlock);
}
/// <summary>
/// Helper visitor class that changes all references to type parameters to appropriate once.
/// </summary>
private class TypeParameterFixerVisitor : StandardVisitor
{
private readonly GenericTypeMapper genericParametersMapping;
public TypeParameterFixerVisitor(GenericTypeMapper genericParametersMapping)
{
Contract.Requires(genericParametersMapping != null);
this.genericParametersMapping = genericParametersMapping;
}
public override Expression VisitAddressDereference(AddressDereference addr)
{
// Replacing initobj !!0 to initobj !0
var newType = genericParametersMapping.GetClosureTypeParameterByEnclosingTypeParameter(addr.Type);
if (newType != addr.Type)
{
return new AddressDereference(addr.Address, newType, addr.Volatile, addr.Alignment, addr.SourceContext);
}
return base.VisitAddressDereference(addr);
}
// Literal is used when contract result compares to null: Contract.Result<T>() != null
public override Expression VisitLiteral(Literal literal)
{
var origin = literal.Value as TypeNode;
if (origin == null)
{
return base.VisitLiteral(literal);
}
var newLiteralType = this.genericParametersMapping.GetClosureTypeParameterByEnclosingTypeParameter(origin);
if (newLiteralType != origin)
{
return new Literal(newLiteralType);
}
return base.VisitLiteral(literal);
}
public override TypeNode VisitTypeParameter(TypeNode typeParameter)
{
var fixedVersion = this.genericParametersMapping.GetClosureTypeParameterByEnclosingTypeParameter(typeParameter);
if (fixedVersion != typeParameter)
{
return fixedVersion;
}
return base.VisitTypeParameter(typeParameter);
}
public override TypeNode VisitTypeReference(TypeNode type)
{
var fixedVersion = this.genericParametersMapping.GetClosureTypeParameterByEnclosingTypeParameter(type);
if (fixedVersion != type)
{
return fixedVersion;
}
return base.VisitTypeReference(type);
}
public override TypeNode VisitTypeNode(TypeNode typeNode)
{
var fixedVersion = this.genericParametersMapping.GetClosureTypeParameterByEnclosingTypeParameter(typeNode);
if (fixedVersion != typeNode)
{
return fixedVersion;
}
return base.VisitTypeNode(typeNode);
}
}
private static IEnumerable<Ensures> GetTaskResultBasedEnsures(List<Ensures> asyncPostconditions)
{
return asyncPostconditions.Where(post => !(post is EnsuresExceptional));
}
private static IEnumerable<EnsuresExceptional> GetExceptionalEnsures(List<Ensures> asyncPostconditions)
{
return asyncPostconditions.OfType<EnsuresExceptional>();
}
/// <summary>
/// Returns TaskExtensions.Unwrap method.
/// </summary>
[Pure]
private Member GetUnwrapMethod(TypeNode checkMethodTaskType)
{
Contract.Requires(checkMethodTaskType != null);
Contract.Ensures(Contract.Result<Member>() != null);
Contract.Assert(TaskExtensionsTypeNode != null, "Can't find System.Threading.Tasks.TaskExtensions type");
var unwrapCandidates = TaskExtensionsTypeNode.GetMembersNamed(Identifier.For("Unwrap"));
Contract.Assert(unwrapCandidates != null,
"Can't find Unwrap method in the TaskExtensions type");
// Should be only two methods. If that is not true, we need to change this code to reflect this!
Contract.Assume(unwrapCandidates.Count == 2, "Should be exactly two candidate Unwrap methods.");
// We need to find appropriate Unwrap method based on CheckMethod argument type.
var firstMethod = (Method)unwrapCandidates[0];
var secondMethod = (Method)unwrapCandidates[1];
Contract.Assume(firstMethod != null && secondMethod != null);
var genericUnwrapCandidate = firstMethod.IsGeneric ? firstMethod : secondMethod;
var nonGenericUnwrapCandidate = firstMethod.IsGeneric ? secondMethod : firstMethod;
if (checkMethodTaskType.IsGeneric)
{
// We need to "instantiate" generic first.
// I.e. for Task<int> we need to have Unwrap(Task<Task<int>>): Task<int>
// In this case we need to map back generic types.
// CheckPost method is a non-generic method from (potentially) generic closure class.
// In this case, if enclosing method is generic we need to map generic types back
// and use !!0 (reference to method template arg) instead of using !0 (which is reference
// to closure class template arg).
var enclosingGeneritType =
this.genericTypeMapper.GetEnclosingTypeParameterByClosureTypeParameter(
checkMethodTaskType.TemplateArguments[0]);
return genericUnwrapCandidate.GetTemplateInstance(null, enclosingGeneritType);
}
return nonGenericUnwrapCandidate;
}
/// <summary>
/// Factory method that creates bool CheckException(Exception e)
/// </summary>
[Pure]
private Method CreateCheckExceptionMethod()
{
Contract.Ensures(Contract.Result<Method>() != null);
var exnParameter = new Parameter(Identifier.For("e"), SystemTypes.Exception);
var checkExceptionMethod =
new Method(
declaringType: this.closureClass,
attributes: null,
name: CheckExceptionMethodId,
parameters: new ParameterList(exnParameter),
returnType: SystemTypes.Boolean,
body: new Block(new StatementList()));
checkExceptionMethod.Body.HasLocals = true;
checkExceptionMethod.CallingConvention = CallingConventionFlags.HasThis;
checkExceptionMethod.Flags |= MethodFlags.Public;
if (checkExceptionMethod.ExceptionHandlers == null)
checkExceptionMethod.ExceptionHandlers = new ExceptionHandlerList();
return checkExceptionMethod;
}
private void EmitCheckExceptionBody(Method checkExceptionMethod, List<EnsuresExceptional> exceptionalPostconditions)
{
Contract.Requires(checkExceptionMethod != null);
Contract.Requires(exceptionalPostconditions != null);
Contract.Requires(exceptionalPostconditions.Count > 0);
// We emit the following method:
// bool CheckException(Exception e) {
// var ex = e as C1;
// if (ex != null) {
// EnsuresOnThrow(predicate)
// }
// else {
// var ex2 = e as AggregateException;
// if (ex2 != null) {
// ex2.Handle(CheckException);
// }
// }
//
// // Method always returns true. This is by design!
// // We need to check all exceptions in the AggregateException
// // and fail in EnsuresOnThrow if the postcondition is not met.
// return true; // handled
var body = checkExceptionMethod.Body.Statements;
var returnBlock = new Block(new StatementList());
foreach (var e in exceptionalPostconditions)
{
// The catchBlock contains the catchBody, and then
// an empty block that is used in the EH.
// TODO ST: name is confusing because there is no catch blocks in this method!
Block catchBlock = new Block(new StatementList());
// local is: var ex1 = e as C1;
Local localEx = new Local(e.Type);
body.Add(
new AssignmentStatement(localEx,
new BinaryExpression(checkExceptionMethod.Parameters[0],
new MemberBinding(null, e.Type),
NodeType.Isinst)));
Block skipBlock = new Block();
body.Add(new Branch(new UnaryExpression(localEx, NodeType.LogicalNot), skipBlock));
body.Add(catchBlock);
body.Add(skipBlock);
// call Contract.EnsuresOnThrow
ExpressionList args = new ExpressionList();
args.Add(e.PostCondition);
args.Add(e.UserMessage ?? Literal.Null);
args.Add(e.SourceConditionText ?? Literal.Null);
args.Add(localEx);
var checks = new StatementList();
checks.Add(
new ExpressionStatement(
new MethodCall(
new MemberBinding(null, this.rewriter.RuntimeContracts.EnsuresOnThrowMethod),
args,
NodeType.Call,
SystemTypes.Void),
e.SourceContext));
this.rewriter.CleanUpCodeCoverage.VisitStatementList(checks);
// TODO ST: actually I can't see this recursion guard check in the resulting IL!!
rewriter.EmitRecursionGuardAroundChecks(checkExceptionMethod, catchBlock, checks);
catchBlock.Statements.Add(new Branch(null, returnBlock));
}
// recurse on AggregateException itself
{
// var ae = e as AggregateException;
// if (ae != null) {
// ae.Handle(this.CheckException);
// }
Block catchBlock = new Block(new StatementList());
var aggregateType = aggregateExceptionType.Value;
// var ex2 = e as AggregateException;
Local localEx2 = new Local(aggregateType);
body.Add(
new AssignmentStatement(localEx2,
new BinaryExpression(
checkExceptionMethod.Parameters[0],
new MemberBinding(null, aggregateType),
NodeType.Isinst)));
Block skipBlock = new Block();
body.Add(new Branch(new UnaryExpression(localEx2, NodeType.LogicalNot), skipBlock));
body.Add(catchBlock);
body.Add(skipBlock);
var funcType = func2Type.Value;
funcType = funcType.GetTemplateInstance(this.rewriter.AssemblyBeingRewritten, SystemTypes.Exception, SystemTypes.Boolean);
var handleMethod = aggregateType.GetMethod(Identifier.For("Handle"), funcType);
var funcLocal = new Local(funcType);
var ldftn =
new UnaryExpression(
new MemberBinding(null, checkExceptionMethod),
NodeType.Ldftn,
CoreSystemTypes.IntPtr);
catchBlock.Statements.Add(
new AssignmentStatement(funcLocal,
new Construct(
new MemberBinding(null, funcType.GetConstructor(SystemTypes.Object, SystemTypes.IntPtr)),
new ExpressionList(checkExceptionMethod.ThisParameter, ldftn))));
catchBlock.Statements.Add(
new ExpressionStatement(new MethodCall(new MemberBinding(localEx2, handleMethod),
new ExpressionList(funcLocal))));
}
// add return true to CheckException method
body.Add(returnBlock);
body.Add(new Return(Literal.True));
}
/// <summary>
/// Returns property for the task object.
/// </summary>
private static Method GetTaskProperty(Parameter taskParameter, string propertyName)
{
Contract.Requires(taskParameter != null);
Contract.Ensures(Contract.Result<Method>() != null);
// For generic task Status property defined in the base class.
// That's why we need to check what the taskParameter type is - is it generic or not.
// If the taskParameter is generic we need to use base type (because Task<T> : Task).
var taskTypeWithStatusProperty = taskParameter.Type.IsGeneric
? taskParameter.Type.BaseType
: taskParameter.Type;
return taskTypeWithStatusProperty.GetMethod(Identifier.For(propertyName));
}
/// <summary>
/// Method returns a list of statements that checks task status.
/// </summary>
private static StatementList CreateIfTaskResultIsEqualsTo(
Parameter taskParameterToCheck, TaskStatus expectedStatus,
Block endBlock)
{
Contract.Ensures(Contract.Result<StatementList>() != null);
var result = new StatementList();
// If-statement is slightly different in IL.
// To get `if (condition) {statements}`
// we need to generate:
// if (!condition) goto endBLock; statements; endBlock:
// This method emits a check that simplifies CheckMethod implementation.
var statusProperty = GetTaskProperty(taskParameterToCheck, "get_Status");
Contract.Assert(statusProperty != null, "Can't find Task.Status property");
// Emitting: var tmpStatus = task.Status;
var tmpStatus = new Local(statusProperty.ReturnType);
result.Add(
new AssignmentStatement(tmpStatus,
new MethodCall(new MemberBinding(taskParameterToCheck, statusProperty),
new ExpressionList())));
// if (tmpStatus != expectedStatus)
// goto endOfMethod;
// This is an inverted form of the check: if (tmpStatus == expectedStatus) {check}
result.Add(
new Branch(
new BinaryExpression(
tmpStatus,
new Literal(expectedStatus),
NodeType.Ne),
endBlock));
return result;
}
private static Block CreateReturnBlock(Parameter checkPostTaskParameter, SourceContext? lastEnsuresSourceContext)
{
Statement returnStatement = new Return(checkPostTaskParameter);
if (lastEnsuresSourceContext != null)
{
returnStatement.SourceContext = lastEnsuresSourceContext.Value;
}
Block returnBlock = new Block(new StatementList(1));
returnBlock.Statements.Add(returnStatement);
return returnBlock;
}
/// <summary>
/// Returns correct version of the ContinueWith method.
/// </summary>
/// <remarks>
/// This function returns ContinueWith overload that takes TaskContinuationOptions.
/// </remarks>
private static Method GetContinueWithMethod(Class closureClass, TypeNode taskTemplate, TypeNode taskType)
{
var continueWithCandidates = taskTemplate.GetMembersNamed(Identifier.For("ContinueWith"));
// Looking for an overload with TaskContinuationOptions
const int expectedNumberOfArguments = 2;
for (int i = 0; i < continueWithCandidates.Count; i++)
{
var cand = continueWithCandidates[i] as Method;
if (cand == null) continue;
// For non-generic version we're looking for ContinueWith(Action<Task>, TaskContinuationOptions)
if (!taskType.IsGeneric)
{
if (cand.IsGeneric) continue;
if (cand.ParameterCount != expectedNumberOfArguments) continue;
if (cand.Parameters[0].Type.GetMetadataName() != "Action`1") continue;
if (cand.Parameters[1].Type.GetMetadataName() != "TaskContinuationOptions") continue;
return cand;
}
// For generic version we're looking for ContinueWith(Func<Task, T>, TaskContinuationOptions)
if (!cand.IsGeneric) continue;
if (cand.TemplateParameters.Count != 1) continue;
if (cand.ParameterCount != expectedNumberOfArguments) continue;
if (cand.Parameters[0].Type.GetMetadataName() != "Func`2") continue;
if (cand.Parameters[1].Type.GetMetadataName() != "TaskContinuationOptions") continue;
// now create instance, first of task
var taskInstance = taskTemplate.GetTemplateInstance(
closureClass.DeclaringModule,
taskType.TemplateArguments[0]);
// ST: some black magic is happening, but it seems it is required to get ContinueWith
// from generic instantiated version of the task
var candMethod = (Method)taskInstance.GetMembersNamed(Identifier.For("ContinueWith"))[i];
// Candidate method would have following signature:
// Task<T> ContinueWith(Task<T> t) for generic version
return candMethod.GetTemplateInstance(null, taskType);
}
return null;
}
private static InstanceInitializer CreateConstructor(Class closureClass)
{
var ctor = new InstanceInitializer(closureClass, null, null, null);
ctor.CallingConvention = CallingConventionFlags.HasThis;
ctor.Flags |= MethodFlags.Public | MethodFlags.HideBySig;
// Regular block that calls base class constructor
ctor.Body = new Block(
new StatementList(
new ExpressionStatement(
new MethodCall(new MemberBinding(ctor.ThisParameter, SystemTypes.Object.GetConstructor()),
new ExpressionList())),
new Return()));
return ctor;
}
private bool IsVoidTask()
{
return this.checkPostMethod.ReturnType == SystemTypes.Void;
}
class FieldRewriter : StandardVisitor
{
private readonly EmitAsyncClosure closure;
private Field enclosingInstance;
public FieldRewriter(EmitAsyncClosure closure)
{
this.closure = closure;
}
public override Expression VisitMemberBinding(MemberBinding memberBinding)
{
// Original postcondition could have an access to the instance state via Contract.Ensures(_state == "foo");
// Now postcondition body resides in the different class and all references to 'this' pointer should be changed.
// If member binding references 'this', then we need to initialize '_this' field that points to the enclosing class
// and redirect the binding to this field.
var thisNode = memberBinding != null ? memberBinding.TargetObject as This : null;
if (thisNode != null && thisNode.DeclaringMethod != null && thisNode.DeclaringMethod.DeclaringType != null &&
// Need to change only when 'this' belongs to enclosing class instance
thisNode.DeclaringMethod.DeclaringType.Equals(this.closure.declaringType))
{
var thisField = EnsureClosureInitialization(memberBinding.TargetObject);
return new MemberBinding(
new MemberBinding(this.closure.checkPostMethod.ThisParameter, thisField),
memberBinding.BoundMember);
}
return base.VisitMemberBinding(memberBinding);
}
/// <summary>
/// Ensures that async closure has a field with enclosing class field, like public EnclosingType _this.
/// </summary>
private Field EnsureClosureInitialization(Expression targetObject)
{
if (this.enclosingInstance == null)
{
var localType = this.closure.forwarder != null ? this.closure.forwarder.VisitTypeReference(targetObject.Type) : targetObject.Type;
var enclosedTypeField = new Field(
this.closure.closureClass, null, FieldFlags.Public, new Identifier("_this"), localType, null);
this.closure.closureClass.Members.Add(enclosedTypeField);
// initialize the closure field
var instantiatedField = Rewriter.GetMemberInstanceReference(enclosedTypeField, this.closure.closureClassInstance);
this.closure.ClosureInitializer.Statements.Add(
new AssignmentStatement(
new MemberBinding(this.closure.closureLocal, instantiatedField), targetObject));
this.enclosingInstance = enclosedTypeField;
}
return this.enclosingInstance;
}
}
// Visitor for changing closure locals to fields
public override Expression VisitLocal(Local local)
{
if (HelperMethods.IsClosureType(this.declaringType, local.Type))
{
MemberBinding mb;
if (!closureLocals.TryGetValue(local, out mb))
{
// TODO ST: not clear what's going on here!
// Clarification: this method changes access to local variables to apropriate fields.
// Consider following example:
// public async Task<int> FooAsync(int[] arguments, int length)
// {
// Contract.Ensures(Contract.ForAll(arguments, i => i == Contract.Result<int>() && i == length));
// }
// In this case, CheckPost method should reference length that will become a field of the generated
// closure class.
// So this code will change all locals (like length) to appropriate fields of the async closure instance.
// Forwarder would be null, if enclosing method with async closure is not generic
var localType = forwarder != null ? forwarder.VisitTypeReference(local.Type) : local.Type;
var closureField = new Field(this.closureClass, null, FieldFlags.Public, local.Name, localType, null);
this.closureClass.Members.Add(closureField);
mb = new MemberBinding(this.checkPostMethod.ThisParameter, closureField);
closureLocals.Add(local, mb);
// initialize the closure field
var instantiatedField = Rewriter.GetMemberInstanceReference(closureField, this.closureClassInstance);
this.ClosureInitializer.Statements.Add(
new AssignmentStatement(
new MemberBinding(this.closureLocal, instantiatedField), local));
}
return mb;
}
return local;
}
}
}
| |
#pragma warning disable 1591
using System;
using System.Collections.Generic;
using System.Text;
namespace Braintree
{
public class WebhookTestingGateway : IWebhookTestingGateway
{
private readonly BraintreeService service;
protected internal WebhookTestingGateway(BraintreeGateway gateway)
{
gateway.Configuration.AssertHasAccessTokenOrKeys();
service = new BraintreeService(gateway.Configuration);
}
public virtual Dictionary<string, string> SampleNotification(WebhookKind kind, string id)
{
var response = new Dictionary<string, string>();
string payload = BuildPayload(kind, id);
response["bt_payload"] = payload;
response["bt_signature"] = BuildSignature(payload);
return response;
}
private string BuildPayload(WebhookKind kind, string id)
{
var currentTime = DateTime.Now.ToUniversalTime().ToString("u");
var payload = string.Format("<notification><timestamp type=\"datetime\">{0}</timestamp><kind>{1}</kind><subject>{2}</subject></notification>", currentTime, kind, SubjectSampleXml(kind, id));
return Convert.ToBase64String(Encoding.Default.GetBytes(payload)) + '\n';
}
private string BuildSignature(string payload)
{
return string.Format("{0}|{1}", service.PublicKey, new Sha1Hasher().HmacHash(service.PrivateKey, payload).Trim().ToLower());
}
private string SubjectSampleXml(WebhookKind kind, string id)
{
if (kind == WebhookKind.SUB_MERCHANT_ACCOUNT_APPROVED) {
return MerchantAccountApprovedSampleXml(id);
} else if (kind == WebhookKind.SUB_MERCHANT_ACCOUNT_DECLINED) {
return MerchantAccountDeclinedSampleXml(id);
} else if (kind == WebhookKind.TRANSACTION_DISBURSED) {
return TransactionDisbursedSampleXml(id);
} else if (kind == WebhookKind.DISBURSEMENT_EXCEPTION) {
return DisbursementExceptionSampleXml(id);
} else if (kind == WebhookKind.DISBURSEMENT) {
return DisbursementSampleXml(id);
} else if (kind == WebhookKind.PARTNER_MERCHANT_CONNECTED) {
return PartnerMerchantConnectedSampleXml(id);
} else if (kind == WebhookKind.PARTNER_MERCHANT_DISCONNECTED) {
return PartnerMerchantDisconnectedSampleXml(id);
} else if (kind == WebhookKind.PARTNER_MERCHANT_DECLINED) {
return PartnerMerchantDeclinedSampleXml(id);
} else if (kind == WebhookKind.DISPUTE_OPENED) {
return DisputeOpenedSampleXml(id);
} else if (kind == WebhookKind.DISPUTE_LOST) {
return DisputeLostSampleXml(id);
} else if (kind == WebhookKind.DISPUTE_WON) {
return DisputeWonSampleXml(id);
} else if (kind == WebhookKind.SUBSCRIPTION_CHARGED_SUCCESSFULLY) {
return SubscriptionChargedSuccessfullySampleXml(id);
} else if (kind == WebhookKind.CHECK) {
return CheckSampleXml();
} else if (kind == WebhookKind.ACCOUNT_UPDATER_DAILY_REPORT) {
return AccountUpdaterDailyReportSampleXml(id);
} else {
return SubscriptionXml(id);
}
}
private static readonly string TYPE_DATE = "type=\"date\"";
private static readonly string TYPE_ARRAY = "type=\"array\"";
private static readonly string TYPE_SYMBOL = "type=\"symbol\"";
private static readonly string NIL_TRUE = "nil=\"true\"";
private static readonly string TYPE_BOOLEAN = "type=\"boolean\"";
private string MerchantAccountDeclinedSampleXml(string id)
{
return Node("api-error-response",
Node("message", "Applicant declined due to OFAC."),
NodeAttr("errors", TYPE_ARRAY,
Node("merchant-account",
NodeAttr("errors", TYPE_ARRAY,
Node("error",
Node("code", "82621"),
Node("message", "Applicant declined due to OFAC."),
NodeAttr("attribute", TYPE_SYMBOL, "base")
)
)
)
),
Node("merchant-account",
Node("id", id),
Node("status", "suspended"),
Node("master-merchant-account",
Node("id", "master_ma_for_" + id),
Node("status", "suspended")
)
)
);
}
private string TransactionDisbursedSampleXml(string id)
{
return Node("transaction",
Node("id", id),
Node("amount", "100.00"),
Node("disbursement-details",
NodeAttr("disbursement-date", TYPE_DATE, "2013-07-09")
),
Node("billing"),
Node("credit-card"),
Node("customer"),
Node("descriptor"),
Node("shipping"),
Node("subscription")
);
}
private string DisbursementExceptionSampleXml(string id)
{
return Node("disbursement",
Node("id", id),
Node("amount", "100.00"),
Node("exception-message", "bank_rejected"),
NodeAttr("disbursement-date", TYPE_DATE, "2014-02-10"),
Node("follow-up-action", "update_funding_information"),
NodeAttr("success", TYPE_BOOLEAN, "false"),
NodeAttr("retry", TYPE_BOOLEAN, "false"),
Node("merchant-account",
Node("id", "merchant_account_id"),
Node("master-merchant-account",
Node("id", "master_ma"),
Node("status", "active")
),
Node("status", "active")
),
NodeAttr("transaction-ids", TYPE_ARRAY,
Node("item", "asdf"),
Node("item", "qwer")
)
);
}
private string DisbursementSampleXml(string id)
{
return Node("disbursement",
Node("id", id),
Node("amount", "100.00"),
NodeAttr("exception-message", NIL_TRUE, ""),
NodeAttr("disbursement-date", TYPE_DATE, "2014-02-10"),
NodeAttr("follow-up-action", NIL_TRUE, ""),
NodeAttr("success", TYPE_BOOLEAN, "true"),
NodeAttr("retry", TYPE_BOOLEAN, "false"),
Node("merchant-account",
Node("id", "merchant_account_id"),
Node("master-merchant-account",
Node("id", "master_ma"),
Node("status", "active")
),
Node("status", "active")
),
NodeAttr("transaction-ids", TYPE_ARRAY,
Node("item", "asdf"),
Node("item", "qwer")
)
);
}
private string DisputeOpenedSampleXml(string id) {
return Node("dispute",
Node("id", id),
Node("amount", "250.00"),
NodeAttr("received-date", TYPE_DATE, "2014-03-21"),
NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"),
Node("currency-iso-code", "USD"),
Node("kind", "chargeback"),
Node("status", "open"),
Node("reason", "fraud"),
Node("transaction",
Node("id", id),
Node("amount", "250.00")
),
NodeAttr("date-opened", TYPE_DATE, "2014-03-21")
);
}
private string DisputeLostSampleXml(string id) {
return Node("dispute",
Node("id", id),
Node("amount", "250.00"),
NodeAttr("received-date", TYPE_DATE, "2014-03-21"),
NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"),
Node("currency-iso-code", "USD"),
Node("kind", "chargeback"),
Node("status", "lost"),
Node("reason", "fraud"),
Node("transaction",
Node("id", id),
Node("amount", "250.00")
),
NodeAttr("date-opened", TYPE_DATE, "2014-03-21")
);
}
private string DisputeWonSampleXml(string id) {
return Node("dispute",
Node("id", id),
Node("amount", "250.00"),
NodeAttr("received-date", TYPE_DATE, "2014-03-21"),
NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"),
Node("currency-iso-code", "USD"),
Node("kind", "chargeback"),
Node("status", "won"),
Node("reason", "fraud"),
Node("transaction",
Node("id", id),
Node("amount", "250.00")
),
NodeAttr("date-opened", TYPE_DATE, "2014-03-21"),
NodeAttr("date-won", TYPE_DATE, "2014-03-22")
);
}
private string SubscriptionXml(string id)
{
return Node("subscription",
Node("id", id),
NodeAttr("transactions", TYPE_ARRAY),
NodeAttr("add_ons", TYPE_ARRAY),
NodeAttr("discounts", TYPE_ARRAY)
);
}
private string SubscriptionChargedSuccessfullySampleXml(string id)
{
return Node("subscription",
Node("id", id),
Node("transactions",
Node("transaction",
Node("id", id),
Node("amount", "49.99"),
Node("status", "submitted_for_settlement"),
Node("disbursement-details",
NodeAttr("disbursement-date", TYPE_DATE, "2013-07-09")
),
Node("billing"),
Node("credit-card"),
Node("customer"),
Node("descriptor"),
Node("shipping"),
Node("subscription")
)
),
NodeAttr("add_ons", TYPE_ARRAY),
NodeAttr("discounts", TYPE_ARRAY)
);
}
private string CheckSampleXml()
{
return NodeAttr("check", TYPE_BOOLEAN, "true");
}
private string MerchantAccountApprovedSampleXml(string id)
{
return Node("merchant-account",
Node("id", id),
Node("master-merchant-account",
Node("id", "master_ma_for_" + id),
Node("status", "active")
),
Node("status", "active")
);
}
private string PartnerMerchantConnectedSampleXml(string id) {
return Node("partner-merchant",
Node("partner-merchant-id", "abc123"),
Node("merchant-public-id", "public_id"),
Node("public-key", "public_key"),
Node("private-key", "private_key"),
Node("client-side-encryption-key", "cse_key")
);
}
private string PartnerMerchantDisconnectedSampleXml(string id) {
return Node("partner-merchant",
Node("partner-merchant-id", "abc123")
);
}
private string PartnerMerchantDeclinedSampleXml(string id) {
return Node("partner-merchant",
Node("partner-merchant-id", "abc123")
);
}
private string AccountUpdaterDailyReportSampleXml(string id) {
return Node("account-updater-daily-report",
NodeAttr("report-date", TYPE_DATE, "2016-01-14"),
Node("report-url", "link-to-csv-report")
);
}
private static string Node(string name, params string[] contents) {
return NodeAttr(name, null, contents);
}
private static string NodeAttr(string name, string attributes, params string[] contents) {
StringBuilder buffer = new StringBuilder();
buffer.Append('<').Append(name);
if (attributes != null) {
buffer.Append(" ").Append(attributes);
}
buffer.Append('>');
foreach (string content in contents) {
buffer.Append(content);
}
buffer.Append("</").Append(name).Append('>');
return buffer.ToString();
}
}
}
| |
/*
* 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 copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps=OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.CoreModules.Agent.Capabilities
{
public class CapabilitiesModule : INonSharedRegionModule, ICapabilitiesModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Scene m_scene;
/// <summary>
/// Each agent has its own capabilities handler.
/// </summary>
protected Dictionary<UUID, Caps> m_capsHandlers = new Dictionary<UUID, Caps>();
protected Dictionary<UUID, string> capsPaths = new Dictionary<UUID, string>();
protected Dictionary<UUID, Dictionary<ulong, string>> childrenSeeds
= new Dictionary<UUID, Dictionary<ulong, string>>();
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<ICapabilitiesModule>(this);
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
m_scene.UnregisterModuleInterface<ICapabilitiesModule>(this);
}
public void PostInitialise() {}
public void Close() {}
public string Name
{
get { return "Capabilities Module"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddCapsHandler(UUID agentId)
{
if (m_scene.RegionInfo.EstateSettings.IsBanned(agentId))
return;
String capsObjectPath = GetCapsPath(agentId);
if (m_capsHandlers.ContainsKey(agentId))
{
Caps oldCaps = m_capsHandlers[agentId];
m_log.DebugFormat(
"[CAPS]: Reregistering caps for agent {0}. Old caps path {1}, new caps path {2}. ",
agentId, oldCaps.CapsObjectPath, capsObjectPath);
// This should not happen. The caller code is confused. We need to fix that.
// CAPs can never be reregistered, or the client will be confused.
// Hence this return here.
//return;
}
Caps caps
= new Caps(
m_scene.AssetService, MainServer.Instance, m_scene.RegionInfo.ExternalHostName,
MainServer.Instance.Port,
capsObjectPath, agentId, m_scene.DumpAssetsToFile, m_scene.RegionInfo.RegionName);
caps.RegisterHandlers();
m_scene.EventManager.TriggerOnRegisterCaps(agentId, caps);
caps.AddNewInventoryItem = m_scene.AddUploadedInventoryItem;
caps.ItemUpdatedCall = m_scene.CapsUpdateInventoryItemAsset;
caps.TaskScriptUpdatedCall = m_scene.CapsUpdateTaskInventoryScriptAsset;
caps.CAPSFetchInventoryDescendents = m_scene.HandleFetchInventoryDescendentsCAPS;
caps.GetClient = m_scene.SceneContents.GetControllingClient;
m_capsHandlers[agentId] = caps;
}
public void RemoveCapsHandler(UUID agentId)
{
if (childrenSeeds.ContainsKey(agentId))
{
childrenSeeds.Remove(agentId);
}
lock (m_capsHandlers)
{
if (m_capsHandlers.ContainsKey(agentId))
{
m_capsHandlers[agentId].DeregisterHandlers();
m_scene.EventManager.TriggerOnDeregisterCaps(agentId, m_capsHandlers[agentId]);
m_capsHandlers.Remove(agentId);
}
else
{
m_log.WarnFormat(
"[CAPS]: Received request to remove CAPS handler for root agent {0} in {1}, but no such CAPS handler found!",
agentId, m_scene.RegionInfo.RegionName);
}
}
}
public Caps GetCapsHandlerForUser(UUID agentId)
{
lock (m_capsHandlers)
{
if (m_capsHandlers.ContainsKey(agentId))
{
return m_capsHandlers[agentId];
}
}
return null;
}
public void NewUserConnection(AgentCircuitData agent)
{
capsPaths[agent.AgentID] = agent.CapsPath;
childrenSeeds[agent.AgentID]
= ((agent.ChildrenCapSeeds == null) ? new Dictionary<ulong, string>() : agent.ChildrenCapSeeds);
}
public string GetCapsPath(UUID agentId)
{
if (capsPaths.ContainsKey(agentId))
{
return capsPaths[agentId];
}
return null;
}
public Dictionary<ulong, string> GetChildrenSeeds(UUID agentID)
{
Dictionary<ulong, string> seeds = null;
if (childrenSeeds.TryGetValue(agentID, out seeds))
return seeds;
return new Dictionary<ulong, string>();
}
public void DropChildSeed(UUID agentID, ulong handle)
{
Dictionary<ulong, string> seeds;
if (childrenSeeds.TryGetValue(agentID, out seeds))
{
seeds.Remove(handle);
}
}
public string GetChildSeed(UUID agentID, ulong handle)
{
Dictionary<ulong, string> seeds;
string returnval;
if (childrenSeeds.TryGetValue(agentID, out seeds))
{
if (seeds.TryGetValue(handle, out returnval))
return returnval;
}
return null;
}
public void SetChildrenSeed(UUID agentID, Dictionary<ulong, string> seeds)
{
//m_log.DebugFormat(" !!! Setting child seeds in {0} to {1}", m_scene.RegionInfo.RegionName, seeds.Count);
childrenSeeds[agentID] = seeds;
}
public void DumpChildrenSeeds(UUID agentID)
{
m_log.Info("================ ChildrenSeed "+m_scene.RegionInfo.RegionName+" ================");
foreach (KeyValuePair<ulong, string> kvp in childrenSeeds[agentID])
{
uint x, y;
Utils.LongToUInts(kvp.Key, out x, out y);
x = x / Constants.RegionSize;
y = y / Constants.RegionSize;
m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.LanguageServices.ProjectInfoService;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> :
IGenerateTypeService
where TService : AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
where TSimpleNameSyntax : TExpressionSyntax
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TExpressionSyntax : SyntaxNode
where TTypeDeclarationSyntax : SyntaxNode
where TArgumentSyntax : SyntaxNode
{
protected AbstractGenerateTypeService()
{
}
protected abstract bool TryInitializeState(SemanticDocument document, TSimpleNameSyntax simpleName, CancellationToken cancellationToken, out GenerateTypeServiceStateOptions generateTypeServiceStateOptions);
protected abstract TExpressionSyntax GetLeftSideOfDot(TSimpleNameSyntax simpleName);
protected abstract bool TryGetArgumentList(TObjectCreationExpressionSyntax objectCreationExpression, out IList<TArgumentSyntax> argumentList);
protected abstract string DefaultFileExtension { get; }
protected abstract IList<ITypeParameterSymbol> GetTypeParameters(State state, SemanticModel semanticModel, CancellationToken cancellationToken);
protected abstract Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken);
protected abstract IList<string> GenerateParameterNames(SemanticModel semanticModel, IList<TArgumentSyntax> arguments);
protected abstract INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, TSimpleNameSyntax simpleName, CancellationToken cancellationToken);
protected abstract ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, TArgumentSyntax argument, CancellationToken cancellationToken);
protected abstract bool IsInCatchDeclaration(TExpressionSyntax expression);
protected abstract bool IsArrayElementType(TExpressionSyntax expression);
protected abstract bool IsInVariableTypeContext(TExpressionSyntax expression);
protected abstract bool IsInValueTypeConstraintContext(SemanticModel semanticModel, TExpressionSyntax expression, CancellationToken cancellationToken);
protected abstract bool IsInInterfaceList(TExpressionSyntax expression);
internal abstract bool TryGetBaseList(TExpressionSyntax expression, out TypeKindOptions returnValue);
internal abstract bool IsPublicOnlyAccessibility(TExpressionSyntax expression, Project project);
internal abstract bool IsGenericName(TSimpleNameSyntax simpleName);
internal abstract bool IsSimpleName(TExpressionSyntax expression);
internal abstract Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, TSimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken);
protected abstract bool TryGetNameParts(TExpressionSyntax expression, out IList<string> nameParts);
public abstract string GetRootNamespace(CompilationOptions options);
public abstract Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbolAsync(INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken);
public async Task<IEnumerable<CodeAction>> GenerateTypeAsync(
Document document,
SyntaxNode node,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateType, cancellationToken))
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
if (state != null)
{
var actions = GetActions(semanticDocument, node, state, cancellationToken).ToList();
if (actions.Count > 1)
{
// Wrap the generate type actions into a single top level suggestion
// so as to not clutter the list.
return SpecializedCollections.SingletonEnumerable(
new MyCodeAction(FeaturesResources.Generate_type, actions.AsImmutable()));
}
else
{
return actions;
}
}
return SpecializedCollections.EmptyEnumerable<CodeAction>();
}
}
private IEnumerable<CodeAction> GetActions(
SemanticDocument document,
SyntaxNode node,
State state,
CancellationToken cancellationToken)
{
var generateNewTypeInDialog = false;
if (state.NamespaceToGenerateInOpt != null)
{
var workspace = document.Project.Solution.Workspace;
if (workspace == null || workspace.CanApplyChange(ApplyChangesKind.AddDocument))
{
generateNewTypeInDialog = true;
yield return new GenerateTypeCodeAction((TService)this, document.Document, state, intoNamespace: true, inNewFile: true);
}
// If they just are generating "Foo" then we want to offer to generate it into the
// namespace in the same file. However, if they are generating "SomeNS.Foo", then we
// only want to allow them to generate if "SomeNS" is the namespace they are
// currently in.
var isSimpleName = state.SimpleName == state.NameOrMemberAccessExpression;
var generateIntoContaining = IsGeneratingIntoContainingNamespace(document, node, state, cancellationToken);
if ((isSimpleName || generateIntoContaining) &&
CanGenerateIntoContainingNamespace(document, node, state, cancellationToken))
{
yield return new GenerateTypeCodeAction((TService)this, document.Document, state, intoNamespace: true, inNewFile: false);
}
}
if (state.TypeToGenerateInOpt != null)
{
yield return new GenerateTypeCodeAction((TService)this, document.Document, state, intoNamespace: false, inNewFile: false);
}
if (generateNewTypeInDialog)
{
yield return new GenerateTypeCodeActionWithOption((TService)this, document.Document, state);
}
}
private bool CanGenerateIntoContainingNamespace(SemanticDocument document, SyntaxNode node, State state, CancellationToken cancellationToken)
{
var containingNamespace = document.SemanticModel.GetEnclosingNamespace(node.SpanStart, cancellationToken);
// Only allow if the containing namespace is one that can be generated
// into.
var declarationService = document.Project.LanguageServices.GetService<ISymbolDeclarationService>();
var decl = declarationService.GetDeclarations(containingNamespace)
.Where(r => r.SyntaxTree == node.SyntaxTree)
.Select(r => r.GetSyntax(cancellationToken))
.FirstOrDefault(node.GetAncestorsOrThis<SyntaxNode>().Contains);
return
decl != null &&
document.Project.LanguageServices.GetService<ICodeGenerationService>().CanAddTo(decl, document.Project.Solution, cancellationToken);
}
private bool IsGeneratingIntoContainingNamespace(
SemanticDocument document,
SyntaxNode node,
State state,
CancellationToken cancellationToken)
{
var containingNamespace = document.SemanticModel.GetEnclosingNamespace(node.SpanStart, cancellationToken);
if (containingNamespace != null)
{
var containingNamespaceName = containingNamespace.ToDisplayString();
return containingNamespaceName.Equals(state.NamespaceToGenerateInOpt);
}
return false;
}
protected static string GetTypeName(State state)
{
const string AttributeSuffix = "Attribute";
return state.IsAttribute && !state.NameIsVerbatim && !state.Name.EndsWith(AttributeSuffix, StringComparison.Ordinal)
? state.Name + AttributeSuffix
: state.Name;
}
protected IList<ITypeParameterSymbol> GetTypeParameters(
State state,
SemanticModel semanticModel,
IEnumerable<SyntaxNode> typeArguments,
CancellationToken cancellationToken)
{
var arguments = typeArguments.ToList();
var arity = arguments.Count;
var typeParameters = new List<ITypeParameterSymbol>();
// For anything that was a type parameter, just use the name (if we haven't already
// used it). Otherwise, synthesize new names for the parameters.
var names = new string[arity];
var isFixed = new bool[arity];
for (var i = 0; i < arity; i++)
{
var argument = i < arguments.Count ? arguments[i] : null;
var type = argument == null ? null : semanticModel.GetTypeInfo(argument, cancellationToken).Type;
if (type is ITypeParameterSymbol)
{
var name = type.Name;
// If we haven't seen this type parameter already, then we can use this name
// and 'fix' it so that it doesn't change. Otherwise, use it, but allow it
// to be changed if it collides with anything else.
isFixed[i] = !names.Contains(name);
names[i] = name;
typeParameters.Add((ITypeParameterSymbol)type);
}
else
{
names[i] = "T";
typeParameters.Add(null);
}
}
// We can use a type parameter as long as it hasn't been used in an outer type.
var canUse = state.TypeToGenerateInOpt == null
? default(Func<string, bool>)
: s => state.TypeToGenerateInOpt.GetAllTypeParameters().All(t => t.Name != s);
var uniqueNames = NameGenerator.EnsureUniqueness(names, isFixed, canUse: canUse);
for (int i = 0; i < uniqueNames.Count; i++)
{
if (typeParameters[i] == null || typeParameters[i].Name != uniqueNames[i])
{
typeParameters[i] = CodeGenerationSymbolFactory.CreateTypeParameterSymbol(uniqueNames[i]);
}
}
return typeParameters;
}
protected Accessibility DetermineDefaultAccessibility(
State state,
SemanticModel semanticModel,
bool intoNamespace,
CancellationToken cancellationToken)
{
if (state.IsPublicAccessibilityForTypeGeneration)
{
return Accessibility.Public;
}
// If we're a nested type of the type being generated into, then the new type can be
// private. otherwise, it needs to be internal.
if (!intoNamespace && state.TypeToGenerateInOpt != null)
{
var outerTypeSymbol = semanticModel.GetEnclosingNamedType(state.SimpleName.SpanStart, cancellationToken);
if (outerTypeSymbol != null && outerTypeSymbol.IsContainedWithin(state.TypeToGenerateInOpt))
{
return Accessibility.Private;
}
}
return Accessibility.Internal;
}
protected IList<ITypeParameterSymbol> GetAvailableTypeParameters(
State state,
SemanticModel semanticModel,
bool intoNamespace,
CancellationToken cancellationToken)
{
var availableInnerTypeParameters = GetTypeParameters(state, semanticModel, cancellationToken);
var availableOuterTypeParameters = !intoNamespace && state.TypeToGenerateInOpt != null
? state.TypeToGenerateInOpt.GetAllTypeParameters()
: SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
return availableOuterTypeParameters.Concat(availableInnerTypeParameters).ToList();
}
protected async Task<bool> IsWithinTheImportingNamespaceAsync(Document document, int triggeringPosition, string includeUsingsOrImports, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (semanticModel != null)
{
var namespaceSymbol = semanticModel.GetEnclosingNamespace(triggeringPosition, cancellationToken);
if (namespaceSymbol != null && namespaceSymbol.ToDisplayString().StartsWith(includeUsingsOrImports, StringComparison.Ordinal))
{
return true;
}
}
return false;
}
protected bool GeneratedTypesMustBePublic(Project project)
{
var projectInfoService = project.Solution.Workspace.Services.GetService<IProjectInfoService>();
if (projectInfoService != null)
{
return projectInfoService.GeneratedTypesMustBePublic(project);
}
return false;
}
private class MyCodeAction : CodeAction.SimpleCodeAction
{
public MyCodeAction(string title, ImmutableArray<CodeAction> nestedActions)
: base(title, nestedActions)
{
}
}
}
}
| |
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;
}
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)
{
TimeSpan ts;
if (TimeSpan.TryParse(((DatePickerTextBox)sender).Text, SpecificCultureInfo, out ts))
{
SelectedTime = ts;
}
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;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Internal.Runtime.CompilerServices;
namespace System.Runtime.InteropServices.WindowsRuntime
{
// This is a set of stub methods implementing the support for the IVector`1 interface on managed
// objects that implement IList`1. Used by the interop mashaling infrastructure.
//
// The methods on this class must be written VERY carefully to avoid introducing security holes.
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not ListToVectorAdapter objects. Rather, they are of type
// IList<T>. No actual ListToVectorAdapter object is ever instantiated. Thus, you will
// see a lot of expressions that cast "this" to "IList<T>".
internal sealed class ListToVectorAdapter
{
private ListToVectorAdapter()
{
Debug.Fail("This class is never instantiated");
}
// T GetAt(uint index)
internal T GetAt<T>(uint index)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
EnsureIndexInt32(index, _this.Count);
try
{
return _this[(int)index];
}
catch (ArgumentOutOfRangeException ex)
{
throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
}
}
// uint Size { get }
internal uint Size<T>()
{
IList<T> _this = Unsafe.As<IList<T>>(this);
return (uint)_this.Count;
}
// IVectorView<T> GetView()
internal IReadOnlyList<T> GetView<T>()
{
IList<T> _this = Unsafe.As<IList<T>>(this);
Debug.Assert(_this != null);
// Note: This list is not really read-only - you could QI for a modifiable
// list. We gain some perf by doing this. We believe this is acceptable.
if (!(_this is IReadOnlyList<T> roList))
{
roList = new ReadOnlyCollection<T>(_this);
}
return roList;
}
// bool IndexOf(T value, out uint index)
internal bool IndexOf<T>(T value, out uint index)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
int ind = _this.IndexOf(value);
if (-1 == ind)
{
index = 0;
return false;
}
index = (uint)ind;
return true;
}
// void SetAt(uint index, T value)
internal void SetAt<T>(uint index, T value)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
EnsureIndexInt32(index, _this.Count);
try
{
_this[(int)index] = value;
}
catch (ArgumentOutOfRangeException ex)
{
throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
}
}
// void InsertAt(uint index, T value)
internal void InsertAt<T>(uint index, T value)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
// Inserting at an index one past the end of the list is equivalent to appending
// so we need to ensure that we're within (0, count + 1).
EnsureIndexInt32(index, _this.Count + 1);
try
{
_this.Insert((int)index, value);
}
catch (ArgumentOutOfRangeException ex)
{
// Change error code to match what WinRT expects
ex.HResult = HResults.E_BOUNDS;
throw;
}
}
// void RemoveAt(uint index)
internal void RemoveAt<T>(uint index)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
EnsureIndexInt32(index, _this.Count);
try
{
_this.RemoveAt((int)index);
}
catch (ArgumentOutOfRangeException ex)
{
// Change error code to match what WinRT expects
ex.HResult = HResults.E_BOUNDS;
throw;
}
}
// void Append(T value)
internal void Append<T>(T value)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
_this.Add(value);
}
// void RemoveAtEnd()
internal void RemoveAtEnd<T>()
{
IList<T> _this = Unsafe.As<IList<T>>(this);
if (_this.Count == 0)
{
Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection);
e.HResult = HResults.E_BOUNDS;
throw e;
}
uint size = (uint)_this.Count;
RemoveAt<T>(size - 1);
}
// void Clear()
internal void Clear<T>()
{
IList<T> _this = Unsafe.As<IList<T>>(this);
_this.Clear();
}
// uint GetMany(uint startIndex, T[] items)
internal uint GetMany<T>(uint startIndex, T[] items)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
return GetManyHelper<T>(_this, startIndex, items);
}
// void ReplaceAll(T[] items)
internal void ReplaceAll<T>(T[] items)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
_this.Clear();
if (items != null)
{
foreach (T item in items)
{
_this.Add(item);
}
}
}
// Helpers:
private static void EnsureIndexInt32(uint index, int listCapacity)
{
// We use '<=' and not '<' becasue int.MaxValue == index would imply
// that Size > int.MaxValue:
if (((uint)int.MaxValue) <= index || index >= (uint)listCapacity)
{
Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue);
e.HResult = HResults.E_BOUNDS;
throw e;
}
}
private static uint GetManyHelper<T>(IList<T> sourceList, uint startIndex, T[] items)
{
// Calling GetMany with a start index equal to the size of the list should always
// return 0 elements, regardless of the input item size
if (startIndex == sourceList.Count)
{
return 0;
}
EnsureIndexInt32(startIndex, sourceList.Count);
if (items == null)
{
return 0;
}
uint itemCount = Math.Min((uint)items.Length, (uint)sourceList.Count - startIndex);
for (uint i = 0; i < itemCount; ++i)
{
items[i] = sourceList[(int)(i + startIndex)];
}
if (typeof(T) == typeof(string))
{
string[] stringItems = (items as string[])!;
// Fill in rest of the array with string.Empty to avoid marshaling failure
for (uint i = itemCount; i < items.Length; ++i)
stringItems[i] = string.Empty;
}
return itemCount;
}
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using System.Text;
#nullable enable
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
{
internal static class StringUtilities
{
private static readonly SpanAction<char, IntPtr> s_getAsciiOrUTF8StringNonNullCharacters = GetAsciiStringNonNullCharactersWithMarker;
private static readonly SpanAction<char, IntPtr> s_getAsciiStringNonNullCharacters = GetAsciiStringNonNullCharacters;
private static readonly SpanAction<char, IntPtr> s_getLatin1StringNonNullCharacters = GetLatin1StringNonNullCharacters;
private static readonly SpanAction<char, (string? str, char separator, uint number)> s_populateSpanWithHexSuffix = PopulateSpanWithHexSuffix;
public static unsafe string GetAsciiOrUTF8StringNonNullCharacters(this ReadOnlySpan<byte> span, Encoding defaultEncoding)
{
if (span.IsEmpty)
{
return string.Empty;
}
fixed (byte* source = &MemoryMarshal.GetReference(span))
{
var resultString = string.Create(span.Length, (IntPtr)source, s_getAsciiOrUTF8StringNonNullCharacters);
// If resultString is marked, perform UTF-8 encoding
if (resultString[0] == '\0')
{
// null characters are considered invalid
if (span.IndexOf((byte)0) != -1)
{
throw new InvalidOperationException();
}
try
{
resultString = defaultEncoding.GetString(span);
}
catch (DecoderFallbackException)
{
throw new InvalidOperationException();
}
}
return resultString;
}
}
private static unsafe void GetAsciiStringNonNullCharactersWithMarker(Span<char> buffer, IntPtr state)
{
fixed (char* output = &MemoryMarshal.GetReference(buffer))
{
// This version of AsciiUtilities returns false if there are any null ('\0') or non-Ascii
// character (> 127) in the string.
if (!TryGetAsciiString((byte*)state.ToPointer(), output, buffer.Length))
{
// Mark resultString for UTF-8 encoding
output[0] = '\0';
}
}
}
public static unsafe string GetAsciiStringNonNullCharacters(this ReadOnlySpan<byte> span)
{
if (span.IsEmpty)
{
return string.Empty;
}
fixed (byte* source = &MemoryMarshal.GetReference(span))
{
return string.Create(span.Length, (IntPtr)source, s_getAsciiStringNonNullCharacters);
}
}
private static unsafe void GetAsciiStringNonNullCharacters(Span<char> buffer, IntPtr state)
{
fixed (char* output = &MemoryMarshal.GetReference(buffer))
{
// This version of AsciiUtilities returns false if there are any null ('\0') or non-Ascii
// character (> 127) in the string.
if (!TryGetAsciiString((byte*)state.ToPointer(), output, buffer.Length))
{
throw new InvalidOperationException();
}
}
}
public static unsafe string GetLatin1StringNonNullCharacters(this ReadOnlySpan<byte> span)
{
if (span.IsEmpty)
{
return string.Empty;
}
fixed (byte* source = &MemoryMarshal.GetReference(span))
{
return string.Create(span.Length, (IntPtr)source, s_getLatin1StringNonNullCharacters);
}
}
private static unsafe void GetLatin1StringNonNullCharacters(Span<char> buffer, IntPtr state)
{
fixed (char* output = &MemoryMarshal.GetReference(buffer))
{
if (!TryGetLatin1String((byte*)state.ToPointer(), output, buffer.Length))
{
// null characters are considered invalid
throw new InvalidOperationException();
}
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe bool TryGetAsciiString(byte* input, char* output, int count)
{
Debug.Assert(input != null);
Debug.Assert(output != null);
var end = input + count;
Debug.Assert((long)end >= Vector256<sbyte>.Count);
// PERF: so the JIT can reuse the zero from a register
var zero = Vector128<sbyte>.Zero;
if (Sse2.IsSupported)
{
if (Avx2.IsSupported && input <= end - Vector256<sbyte>.Count)
{
var avxZero = Vector256<sbyte>.Zero;
do
{
var vector = Avx.LoadVector256(input).AsSByte();
if (!CheckBytesInAsciiRange(vector, avxZero))
{
return false;
}
var tmp0 = Avx2.UnpackLow(vector, avxZero);
var tmp1 = Avx2.UnpackHigh(vector, avxZero);
// Bring into the right order
var out0 = Avx2.Permute2x128(tmp0, tmp1, 0x20);
var out1 = Avx2.Permute2x128(tmp0, tmp1, 0x31);
Avx.Store((ushort*)output, out0.AsUInt16());
Avx.Store((ushort*)output + Vector256<ushort>.Count, out1.AsUInt16());
input += Vector256<sbyte>.Count;
output += Vector256<sbyte>.Count;
} while (input <= end - Vector256<sbyte>.Count);
if (input == end)
{
return true;
}
}
if (input <= end - Vector128<sbyte>.Count)
{
do
{
var vector = Sse2.LoadVector128(input).AsSByte();
if (!CheckBytesInAsciiRange(vector, zero))
{
return false;
}
var c0 = Sse2.UnpackLow(vector, zero).AsUInt16();
var c1 = Sse2.UnpackHigh(vector, zero).AsUInt16();
Sse2.Store((ushort*)output, c0);
Sse2.Store((ushort*)output + Vector128<ushort>.Count, c1);
input += Vector128<sbyte>.Count;
output += Vector128<sbyte>.Count;
} while (input <= end - Vector128<sbyte>.Count);
if (input == end)
{
return true;
}
}
}
else if (Vector.IsHardwareAccelerated)
{
while (input <= end - Vector<sbyte>.Count)
{
var vector = Unsafe.AsRef<Vector<sbyte>>(input);
if (!CheckBytesInAsciiRange(vector))
{
return false;
}
Vector.Widen(
vector,
out Unsafe.AsRef<Vector<short>>(output),
out Unsafe.AsRef<Vector<short>>(output + Vector<short>.Count));
input += Vector<sbyte>.Count;
output += Vector<sbyte>.Count;
}
if (input == end)
{
return true;
}
}
if (Environment.Is64BitProcess) // Use Intrinsic switch for branch elimination
{
// 64-bit: Loop longs by default
while (input <= end - sizeof(long))
{
var value = *(long*)input;
if (!CheckBytesInAsciiRange(value))
{
return false;
}
// BMI2 could be used, but this variant is faster on both Intel and AMD.
if (Sse2.X64.IsSupported)
{
var vecNarrow = Sse2.X64.ConvertScalarToVector128Int64(value).AsSByte();
var vecWide = Sse2.UnpackLow(vecNarrow, zero).AsUInt64();
Sse2.Store((ulong*)output, vecWide);
}
else
{
output[0] = (char)input[0];
output[1] = (char)input[1];
output[2] = (char)input[2];
output[3] = (char)input[3];
output[4] = (char)input[4];
output[5] = (char)input[5];
output[6] = (char)input[6];
output[7] = (char)input[7];
}
input += sizeof(long);
output += sizeof(long);
}
if (input <= end - sizeof(int))
{
var value = *(int*)input;
if (!CheckBytesInAsciiRange(value))
{
return false;
}
WidenFourAsciiBytesToUtf16AndWriteToBuffer(output, input, value, zero);
input += sizeof(int);
output += sizeof(int);
}
}
else
{
// 32-bit: Loop ints by default
while (input <= end - sizeof(int))
{
var value = *(int*)input;
if (!CheckBytesInAsciiRange(value))
{
return false;
}
WidenFourAsciiBytesToUtf16AndWriteToBuffer(output, input, value, zero);
input += sizeof(int);
output += sizeof(int);
}
}
if (input <= end - sizeof(short))
{
if (!CheckBytesInAsciiRange(((short*)input)[0]))
{
return false;
}
output[0] = (char)input[0];
output[1] = (char)input[1];
input += sizeof(short);
output += sizeof(short);
}
if (input < end)
{
if (!CheckBytesInAsciiRange(((sbyte*)input)[0]))
{
return false;
}
output[0] = (char)input[0];
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe bool TryGetLatin1String(byte* input, char* output, int count)
{
Debug.Assert(input != null);
Debug.Assert(output != null);
// Calculate end position
var end = input + count;
// Start as valid
var isValid = true;
do
{
// If Vector not-accelerated or remaining less than vector size
if (!Vector.IsHardwareAccelerated || input > end - Vector<sbyte>.Count)
{
if (Environment.Is64BitProcess) // Use Intrinsic switch for branch elimination
{
// 64-bit: Loop longs by default
while (input <= end - sizeof(long))
{
isValid &= CheckBytesNotNull(((long*)input)[0]);
output[0] = (char)input[0];
output[1] = (char)input[1];
output[2] = (char)input[2];
output[3] = (char)input[3];
output[4] = (char)input[4];
output[5] = (char)input[5];
output[6] = (char)input[6];
output[7] = (char)input[7];
input += sizeof(long);
output += sizeof(long);
}
if (input <= end - sizeof(int))
{
isValid &= CheckBytesNotNull(((int*)input)[0]);
output[0] = (char)input[0];
output[1] = (char)input[1];
output[2] = (char)input[2];
output[3] = (char)input[3];
input += sizeof(int);
output += sizeof(int);
}
}
else
{
// 32-bit: Loop ints by default
while (input <= end - sizeof(int))
{
isValid &= CheckBytesNotNull(((int*)input)[0]);
output[0] = (char)input[0];
output[1] = (char)input[1];
output[2] = (char)input[2];
output[3] = (char)input[3];
input += sizeof(int);
output += sizeof(int);
}
}
if (input <= end - sizeof(short))
{
isValid &= CheckBytesNotNull(((short*)input)[0]);
output[0] = (char)input[0];
output[1] = (char)input[1];
input += sizeof(short);
output += sizeof(short);
}
if (input < end)
{
isValid &= CheckBytesNotNull(((sbyte*)input)[0]);
output[0] = (char)input[0];
}
return isValid;
}
// do/while as entry condition already checked
do
{
// Use byte/ushort instead of signed equivalents to ensure it doesn't fill based on the high bit.
var vector = Unsafe.AsRef<Vector<byte>>(input);
isValid &= CheckBytesNotNull(vector);
Vector.Widen(
vector,
out Unsafe.AsRef<Vector<ushort>>(output),
out Unsafe.AsRef<Vector<ushort>>(output + Vector<ushort>.Count));
input += Vector<byte>.Count;
output += Vector<byte>.Count;
} while (input <= end - Vector<byte>.Count);
// Vector path done, loop back to do non-Vector
// If is a exact multiple of vector size, bail now
} while (input < end);
return isValid;
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static bool BytesOrdinalEqualsStringAndAscii(string previousValue, ReadOnlySpan<byte> newValue)
{
// previousValue is a previously materialized string which *must* have already passed validation.
Debug.Assert(IsValidHeaderString(previousValue));
// Ascii bytes => Utf-16 chars will be the same length.
// The caller should have already compared lengths before calling this method.
// However; let's double check, and early exit if they are not the same length.
if (previousValue.Length != newValue.Length)
{
// Lengths don't match, so there cannot be an exact ascii conversion between the two.
goto NotEqual;
}
// Note: Pointer comparison is unsigned, so we use the compare pattern (offset + length <= count)
// rather than (offset <= count - length) which we'd do with signed comparison to avoid overflow.
// This isn't problematic as we know the maximum length is max string length (from test above)
// which is a signed value so half the size of the unsigned pointer value so we can safely add
// a Vector<byte>.Count to it without overflowing.
var count = (nint)newValue.Length;
var offset = (nint)0;
// Get references to the first byte in the span, and the first char in the string.
ref var bytes = ref MemoryMarshal.GetReference(newValue);
ref var str = ref MemoryMarshal.GetReference(previousValue.AsSpan());
do
{
// If Vector not-accelerated or remaining less than vector size
if (!Vector.IsHardwareAccelerated || (offset + Vector<byte>.Count) > count)
{
if (IntPtr.Size == 8) // Use Intrinsic switch for branch elimination
{
// 64-bit: Loop longs by default
while ((offset + sizeof(long)) <= count)
{
if (!WidenFourAsciiBytesToUtf16AndCompareToChars(
ref Unsafe.Add(ref str, offset),
Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref bytes, offset))) ||
!WidenFourAsciiBytesToUtf16AndCompareToChars(
ref Unsafe.Add(ref str, offset + 4),
Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref bytes, offset + 4))))
{
goto NotEqual;
}
offset += sizeof(long);
}
if ((offset + sizeof(int)) <= count)
{
if (!WidenFourAsciiBytesToUtf16AndCompareToChars(
ref Unsafe.Add(ref str, offset),
Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref bytes, offset))))
{
goto NotEqual;
}
offset += sizeof(int);
}
}
else
{
// 32-bit: Loop ints by default
while ((offset + sizeof(int)) <= count)
{
if (!WidenFourAsciiBytesToUtf16AndCompareToChars(
ref Unsafe.Add(ref str, offset),
Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref bytes, offset))))
{
goto NotEqual;
}
offset += sizeof(int);
}
}
if ((offset + sizeof(short)) <= count)
{
if (!WidenTwoAsciiBytesToUtf16AndCompareToChars(
ref Unsafe.Add(ref str, offset),
Unsafe.ReadUnaligned<ushort>(ref Unsafe.Add(ref bytes, offset))))
{
goto NotEqual;
}
offset += sizeof(short);
}
if (offset < count)
{
var ch = (char)Unsafe.Add(ref bytes, offset);
if (((ch & 0x80) != 0) || Unsafe.Add(ref str, offset) != ch)
{
goto NotEqual;
}
}
// End of input reached, there are no inequalities via widening; so the input bytes are both ascii
// and a match to the string if it was converted via Encoding.ASCII.GetString(...)
return true;
}
// Create a comparision vector for all bits being equal
var AllTrue = new Vector<short>(-1);
// do/while as entry condition already checked, remaining length must be Vector<byte>.Count or larger.
do
{
// Read a Vector length from the input as bytes
var vector = Unsafe.ReadUnaligned<Vector<sbyte>>(ref Unsafe.Add(ref bytes, offset));
if (!CheckBytesInAsciiRange(vector))
{
goto NotEqual;
}
// Widen the bytes directly to chars (ushort) as if they were ascii.
// As widening doubles the size we get two vectors back.
Vector.Widen(vector, out var vector0, out var vector1);
// Read two char vectors from the string to perform the match.
var compare0 = Unsafe.ReadUnaligned<Vector<short>>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref str, offset)));
var compare1 = Unsafe.ReadUnaligned<Vector<short>>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref str, offset + Vector<ushort>.Count)));
// If the string is not ascii, then the widened bytes cannot match
// as each widened byte element as chars will be in the range 0-255
// so cannot match any higher unicode values.
// Compare to our all bits true comparision vector
if (!AllTrue.Equals(
// BitwiseAnd the two equals together
Vector.BitwiseAnd(
// Check equality for the two widened vectors
Vector.Equals(compare0, vector0),
Vector.Equals(compare1, vector1))))
{
goto NotEqual;
}
offset += Vector<byte>.Count;
} while ((offset + Vector<byte>.Count) <= count);
// Vector path done, loop back to do non-Vector
// If is a exact multiple of vector size, bail now
} while (offset < count);
// If we get here (input is exactly a multiple of Vector length) then there are no inequalities via widening;
// so the input bytes are both ascii and a match to the string if it was converted via Encoding.ASCII.GetString(...)
return true;
NotEqual:
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe void WidenFourAsciiBytesToUtf16AndWriteToBuffer(char* output, byte* input, int value, Vector128<sbyte> zero)
{
// BMI2 could be used, but this variant is faster on both Intel and AMD.
if (Sse2.X64.IsSupported)
{
var vecNarrow = Sse2.ConvertScalarToVector128Int32(value).AsSByte();
var vecWide = Sse2.UnpackLow(vecNarrow, zero).AsUInt64();
Unsafe.WriteUnaligned(output, Sse2.X64.ConvertToUInt64(vecWide));
}
else
{
output[0] = (char)input[0];
output[1] = (char)input[1];
output[2] = (char)input[2];
output[3] = (char)input[3];
}
}
/// <summary>
/// Given a DWORD which represents a buffer of 4 bytes, widens the buffer into 4 WORDs and
/// compares them to the WORD buffer with machine endianness.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static bool WidenFourAsciiBytesToUtf16AndCompareToChars(ref char charStart, uint value)
{
if (!AllBytesInUInt32AreAscii(value))
{
return false;
}
// BMI2 could be used, but this variant is faster on both Intel and AMD.
if (Sse2.X64.IsSupported)
{
var vecNarrow = Sse2.ConvertScalarToVector128UInt32(value).AsByte();
var vecWide = Sse2.UnpackLow(vecNarrow, Vector128<byte>.Zero).AsUInt64();
return Unsafe.ReadUnaligned<ulong>(ref Unsafe.As<char, byte>(ref charStart)) ==
Sse2.X64.ConvertToUInt64(vecWide);
}
else
{
if (BitConverter.IsLittleEndian)
{
return charStart == (char)(byte)value &&
Unsafe.Add(ref charStart, 1) == (char)(byte)(value >> 8) &&
Unsafe.Add(ref charStart, 2) == (char)(byte)(value >> 16) &&
Unsafe.Add(ref charStart, 3) == (char)(value >> 24);
}
else
{
return Unsafe.Add(ref charStart, 3) == (char)(byte)value &&
Unsafe.Add(ref charStart, 2) == (char)(byte)(value >> 8) &&
Unsafe.Add(ref charStart, 1) == (char)(byte)(value >> 16) &&
charStart == (char)(value >> 24);
}
}
}
/// <summary>
/// Given a WORD which represents a buffer of 2 bytes, widens the buffer into 2 WORDs and
/// compares them to the WORD buffer with machine endianness.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static bool WidenTwoAsciiBytesToUtf16AndCompareToChars(ref char charStart, ushort value)
{
if (!AllBytesInUInt16AreAscii(value))
{
return false;
}
// BMI2 could be used, but this variant is faster on both Intel and AMD.
if (Sse2.IsSupported)
{
var vecNarrow = Sse2.ConvertScalarToVector128UInt32(value).AsByte();
var vecWide = Sse2.UnpackLow(vecNarrow, Vector128<byte>.Zero).AsUInt32();
return Unsafe.ReadUnaligned<uint>(ref Unsafe.As<char, byte>(ref charStart)) ==
Sse2.ConvertToUInt32(vecWide);
}
else
{
if (BitConverter.IsLittleEndian)
{
return charStart == (char)(byte)value &&
Unsafe.Add(ref charStart, 1) == (char)(byte)(value >> 8);
}
else
{
return Unsafe.Add(ref charStart, 1) == (char)(byte)value &&
charStart == (char)(byte)(value >> 8);
}
}
}
/// <summary>
/// Returns <see langword="true"/> iff all bytes in <paramref name="value"/> are ASCII.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool AllBytesInUInt32AreAscii(uint value)
{
return ((value & 0x80808080u) == 0);
}
/// <summary>
/// Returns <see langword="true"/> iff all bytes in <paramref name="value"/> are ASCII.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool AllBytesInUInt16AreAscii(ushort value)
{
return ((value & 0x8080u) == 0);
}
private static bool IsValidHeaderString(string value)
{
// Method for Debug.Assert to ensure BytesOrdinalEqualsStringAndAscii
// is not called with an unvalidated string comparitor.
try
{
if (value is null) return false;
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetByteCount(value);
return !value.Contains('\0');
}
catch (DecoderFallbackException)
{
return false;
}
}
/// <summary>
/// A faster version of String.Concat(<paramref name="str"/>, <paramref name="separator"/>, <paramref name="number"/>.ToString("X8"))
/// </summary>
/// <param name="str"></param>
/// <param name="separator"></param>
/// <param name="number"></param>
/// <returns></returns>
public static string ConcatAsHexSuffix(string str, char separator, uint number)
{
var length = 1 + 8;
if (str != null)
{
length += str.Length;
}
return string.Create(length, (str, separator, number), s_populateSpanWithHexSuffix);
}
private static void PopulateSpanWithHexSuffix(Span<char> buffer, (string? str, char separator, uint number) tuple)
{
var (tupleStr, tupleSeparator, tupleNumber) = tuple;
var i = 0;
if (tupleStr != null)
{
tupleStr.AsSpan().CopyTo(buffer);
i = tupleStr.Length;
}
buffer[i] = tupleSeparator;
i++;
if (Ssse3.IsSupported)
{
// The constant inline vectors are read from the data section without any additional
// moves. See https://github.com/dotnet/runtime/issues/44115 Case 1.1 for further details.
var lowNibbles = Ssse3.Shuffle(Vector128.CreateScalarUnsafe(tupleNumber).AsByte(), Vector128.Create(
0xF, 0xF, 3, 0xF,
0xF, 0xF, 2, 0xF,
0xF, 0xF, 1, 0xF,
0xF, 0xF, 0, 0xF
).AsByte());
var highNibbles = Sse2.ShiftRightLogical(Sse2.ShiftRightLogical128BitLane(lowNibbles, 2).AsInt32(), 4).AsByte();
var indices = Sse2.And(Sse2.Or(lowNibbles, highNibbles), Vector128.Create((byte)0xF));
// Lookup the hex values at the positions of the indices
var hex = Ssse3.Shuffle(Vector128.Create(
(byte)'0', (byte)'1', (byte)'2', (byte)'3',
(byte)'4', (byte)'5', (byte)'6', (byte)'7',
(byte)'8', (byte)'9', (byte)'A', (byte)'B',
(byte)'C', (byte)'D', (byte)'E', (byte)'F'
), indices);
// The high bytes (0x00) of the chars have also been converted to ascii hex '0', so clear them out.
hex = Sse2.And(hex, Vector128.Create((ushort)0xFF).AsByte());
// This generates much more efficient asm than fixing the buffer and using
// Sse2.Store((byte*)(p + i), chars.AsByte());
Unsafe.WriteUnaligned(
ref Unsafe.As<char, byte>(
ref Unsafe.Add(ref MemoryMarshal.GetReference(buffer), i)),
hex);
}
else
{
var number = (int)tupleNumber;
// Slice the buffer so we can use constant offsets in a backwards order
// and the highest index [7] will eliminate the bounds checks for all the lower indicies.
buffer = buffer.Slice(i);
// This must be explicity typed as ReadOnlySpan<byte>
// This then becomes a non-allocating mapping to the data section of the assembly.
// If it is a var, Span<byte> or byte[], it allocates the byte array per call.
ReadOnlySpan<byte> hexEncodeMap = new byte[] { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F' };
// Note: this only works with byte due to endian ambiguity for other types,
// hence the later (char) casts
buffer[7] = (char)hexEncodeMap[number & 0xF];
buffer[6] = (char)hexEncodeMap[(number >> 4) & 0xF];
buffer[5] = (char)hexEncodeMap[(number >> 8) & 0xF];
buffer[4] = (char)hexEncodeMap[(number >> 12) & 0xF];
buffer[3] = (char)hexEncodeMap[(number >> 16) & 0xF];
buffer[2] = (char)hexEncodeMap[(number >> 20) & 0xF];
buffer[1] = (char)hexEncodeMap[(number >> 24) & 0xF];
buffer[0] = (char)hexEncodeMap[(number >> 28) & 0xF];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] // Needs a push
private static bool CheckBytesInAsciiRange(Vector<sbyte> check)
{
// Vectorized byte range check, signed byte > 0 for 1-127
return Vector.GreaterThanAll(check, Vector<sbyte>.Zero);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool CheckBytesInAsciiRange(Vector256<sbyte> check, Vector256<sbyte> zero)
{
Debug.Assert(Avx2.IsSupported);
var mask = Avx2.CompareGreaterThan(check, zero);
return (uint)Avx2.MoveMask(mask) == 0xFFFF_FFFF;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool CheckBytesInAsciiRange(Vector128<sbyte> check, Vector128<sbyte> zero)
{
Debug.Assert(Sse2.IsSupported);
var mask = Sse2.CompareGreaterThan(check, zero);
return Sse2.MoveMask(mask) == 0xFFFF;
}
// Validate: bytes != 0 && bytes <= 127
// Subtract 1 from all bytes to move 0 to high bits
// bitwise or with self to catch all > 127 bytes
// mask off non high bits and check if 0
[MethodImpl(MethodImplOptions.AggressiveInlining)] // Needs a push
private static bool CheckBytesInAsciiRange(long check)
{
const long HighBits = unchecked((long)0x8080808080808080L);
return (((check - 0x0101010101010101L) | check) & HighBits) == 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool CheckBytesInAsciiRange(int check)
{
const int HighBits = unchecked((int)0x80808080);
return (((check - 0x01010101) | check) & HighBits) == 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool CheckBytesInAsciiRange(short check)
{
const short HighBits = unchecked((short)0x8080);
return (((short)(check - 0x0101) | check) & HighBits) == 0;
}
private static bool CheckBytesInAsciiRange(sbyte check)
=> check > 0;
[MethodImpl(MethodImplOptions.AggressiveInlining)] // Needs a push
private static bool CheckBytesNotNull(Vector<byte> check)
{
// Vectorized byte range check, signed byte != null
return !Vector.EqualsAny(check, Vector<byte>.Zero);
}
// Validate: bytes != 0
// Subtract 1 from all bytes to move 0 to high bits
// bitwise and with ~check so high bits are only set for bytes that were originally 0
// mask off non high bits and check if 0
[MethodImpl(MethodImplOptions.AggressiveInlining)] // Needs a push
private static bool CheckBytesNotNull(long check)
{
const long HighBits = unchecked((long)0x8080808080808080L);
return ((check - 0x0101010101010101L) & ~check & HighBits) == 0;
}
private static bool CheckBytesNotNull(int check)
{
const int HighBits = unchecked((int)0x80808080);
return ((check - 0x01010101) & ~check & HighBits) == 0;
}
private static bool CheckBytesNotNull(short check)
{
const short HighBits = unchecked((short)0x8080);
return ((check - 0x0101) & ~check & HighBits) == 0;
}
private static bool CheckBytesNotNull(sbyte check)
=> check != 0;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
/// <summary>
/// System.Collections.Generic.IEqualityComparer.Equals(T,T)
/// </summary>
public class IEqualityComparerEquals
{
private int c_MINI_STRING_LENGTH = 8;
private int c_MAX_STRING_LENGTH = 256;
public static int Main(string[] args)
{
IEqualityComparerEquals testObj = new IEqualityComparerEquals();
TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.EqualityComparer.Equals(T,T)");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Using EqualityComparer<T> which implemented the Equals method in IEqualityComparer<T> and Type is int...";
const string c_TEST_ID = "P001";
EqualityComparer<int> equalityComparer = EqualityComparer<int>.Default;
int x = TestLibrary.Generator.GetInt32(-55);
int y = x;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((IEqualityComparer<int>)equalityComparer).Equals(x, y))
{
string errorDesc = "result should be true when two int both are " + x;
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Using EqualityComparer<T> which implemented the Equals method in IEqualityComparer<T> and Type is String...";
const string c_TEST_ID = "P002";
String x = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
String y = x;
EqualityComparer<String> equalityComparer = EqualityComparer<String>.Default;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((IEqualityComparer<String>)equalityComparer).Equals(x, y))
{
string errorDesc = "result should be true when two String object is the same reference";
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Using EqualityComparer<T> which implemented the Equals method in IEqualityComparer<T> and Type is user-defined class...";
const string c_TEST_ID = "P003";
MyClass x = new MyClass();
MyClass y = x;
EqualityComparer<MyClass> equalityComparer = EqualityComparer<MyClass>.Default;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((IEqualityComparer<MyClass>)equalityComparer).Equals(x, y))
{
string errorDesc = "result should be true when two MyClass object is the same reference";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: Using user-defined class which implemented the Equals method in IEqualityComparer<T>...";
const string c_TEST_ID = "P004";
MyEqualityComparer<String> myEC = new MyEqualityComparer<String>();
String str1 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
String str2 = str1 + TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (((IEqualityComparer<String>)myEC).Equals(str1, str2))
{
string errorDesc = "result should be true when two string are difference";
errorDesc += "\n str1 is " + str1;
errorDesc += "\n str2 is " + str2;
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest5: Using user-defined class which implemented the Equals method in IEqualityComparer<T> and two parament are null...";
const string c_TEST_ID = "P005";
MyEqualityComparer<Object> myEC = new MyEqualityComparer<Object>();
Object x = null;
Object y = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((IEqualityComparer<Object>)myEC).Equals(x, y))
{
string errorDesc = "result should be true when two object are null";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Help Class
public class MyEqualityComparer<T> : IEqualityComparer<T>
{
#region IEqualityComparer<T> Members
bool IEqualityComparer<T>.Equals(T x, T y)
{
if (x != null)
{
if (y != null) return x.Equals(y);
return false;
}
if (y != null) return false;
return true;
}
int IEqualityComparer<T>.GetHashCode(T obj)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
public class MyClass
{
}
#endregion
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
public class CreatedTests
{
[Fact]
public static void FileSystemWatcher_Created_File()
{
using (var watcher = new FileSystemWatcher("."))
{
string fileName = Guid.NewGuid().ToString();
watcher.Filter = fileName;
AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
watcher.EnableRaisingEvents = true;
using (var file = new TemporaryTestFile(fileName))
{
Utility.ExpectEvent(eventOccurred, "created");
}
}
}
[Fact]
public static void FileSystemWatcher_Created_Directory()
{
using (var watcher = new FileSystemWatcher("."))
{
string dirName = Guid.NewGuid().ToString();
watcher.Filter = dirName;
AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
watcher.EnableRaisingEvents = true;
using (var dir = new TemporaryTestDirectory(dirName))
{
Utility.ExpectEvent(eventOccurred, "created");
}
}
}
[Fact]
[ActiveIssue(2011, PlatformID.OSX)]
public static void FileSystemWatcher_Created_MoveDirectory()
{
// create two test directories
using (TemporaryTestDirectory dir = Utility.CreateTestDirectory(),
targetDir = new TemporaryTestDirectory(dir.Path + "_target"))
using (var watcher = new FileSystemWatcher("."))
{
string testFileName = "testFile.txt";
// watch the target dir
watcher.Path = Path.GetFullPath(targetDir.Path);
watcher.Filter = testFileName;
AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
string sourceFile = Path.Combine(dir.Path, testFileName);
string targetFile = Path.Combine(targetDir.Path, testFileName);
// create a test file in source
File.WriteAllText(sourceFile, "test content");
watcher.EnableRaisingEvents = true;
// move the test file from source to target directory
File.Move(sourceFile, targetFile);
Utility.ExpectEvent(eventOccurred, "created");
}
}
[Fact]
public static void FileSystemWatcher_Created_Negative()
{
using (var dir = Utility.CreateTestDirectory())
using (var watcher = new FileSystemWatcher())
{
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*.*";
AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
// run all scenarios together to avoid unnecessary waits,
// assert information is verbose enough to trace to failure cause
using (var testFile = new TemporaryTestFile(Path.Combine(dir.Path, "file")))
using (var testDir = new TemporaryTestDirectory(Path.Combine(dir.Path, "dir")))
{
// start listening after we've created these
watcher.EnableRaisingEvents = true;
// change a file
testFile.WriteByte(0xFF);
testFile.Flush();
// renaming a directory
//
// We don't do this on Linux because depending on the timing of MOVED_FROM and MOVED_TO events,
// a rename can trigger delete + create as a deliberate handling of an edge case, and this
// test is checking that no create events are raised.
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
testDir.Move(testDir.Path + "_rename");
}
// deleting a file & directory by leaving the using block
}
Utility.ExpectNoEvent(eventOccurred, "created");
}
}
[Fact]
public static void FileSystemWatcher_Created_FileCreatedInNestedDirectory()
{
Utility.TestNestedDirectoriesHelper(WatcherChangeTypes.Created, (AutoResetEvent are, TemporaryTestDirectory ttd) =>
{
using (var nestedFile = new TemporaryTestFile(Path.Combine(ttd.Path, "nestedFile")))
{
Utility.ExpectEvent(are, "nested file created");
}
});
}
// This can potentially fail, depending on where the test is run from, due to
// the MAX_PATH limitation. When issue 645 is closed, this shouldn't be a problem
[Fact, ActiveIssue(645, PlatformID.Any)]
public static void FileSystemWatcher_Created_DeepDirectoryStructure()
{
// List of created directories
List<TemporaryTestDirectory> lst = new List<TemporaryTestDirectory>();
try
{
using (var dir = Utility.CreateTestDirectory())
using (var watcher = new FileSystemWatcher())
{
AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*.*";
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
// Priming directory
TemporaryTestDirectory priming = new TemporaryTestDirectory(Path.Combine(dir.Path, "dir"));
lst.Add(priming);
Utility.ExpectEvent(eventOccurred, "priming create");
// Create a deep directory structure and expect things to work
for (int i = 1; i < 20; i++)
{
lst.Add(new TemporaryTestDirectory(Path.Combine(lst[i - 1].Path, String.Format("dir{0}", i))));
Utility.ExpectEvent(eventOccurred, lst[i].Path + " create");
}
// Put a file at the very bottom and expect it to raise an event
using (var file = new TemporaryTestFile(Path.Combine(lst[lst.Count - 1].Path, "temp file")))
{
Utility.ExpectEvent(eventOccurred, "temp file create");
}
}
}
finally
{
// Cleanup
foreach (TemporaryTestDirectory d in lst)
d.Dispose();
}
}
[Fact]
[ActiveIssue(1477, PlatformID.Windows)]
[ActiveIssue(3215, PlatformID.OSX)]
public static void FileSystemWatcher_Created_WatcherDoesntFollowSymLinkToFile()
{
using (var dir = Utility.CreateTestDirectory())
using (var temp = Utility.CreateTestFile(Path.GetTempFileName()))
using (var watcher = new FileSystemWatcher())
{
AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*";
watcher.EnableRaisingEvents = true;
// Make the symlink in our path (to the temp file) and make sure an event is raised
Utility.CreateSymLink(Path.GetFullPath(temp.Path), Path.Combine(dir.Path, Path.GetFileName(temp.Path)), false);
Utility.ExpectEvent(eventOccurred, "symlink created");
}
}
[Fact, ActiveIssue(1477, PlatformID.Windows)]
public static void FileSystemWatcher_Created_WatcherDoesntFollowSymLinkToFolder()
{
using (var dir = Utility.CreateTestDirectory())
using (var temp = Utility.CreateTestDirectory(Path.Combine(Path.GetTempPath(), "FooBar")))
using (var watcher = new FileSystemWatcher())
{
AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*";
watcher.EnableRaisingEvents = true;
// Make the symlink in our path (to the temp folder) and make sure an event is raised
Utility.CreateSymLink(Path.GetFullPath(temp.Path), Path.Combine(dir.Path, Path.GetFileName(temp.Path)), true);
Utility.ExpectEvent(eventOccurred, "symlink created");
}
}
}
| |
namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class RegressionTestFixture : AbstractCompilerTestCase
{
[Test]
public void array_ldelem()
{
RunCompilerTestCase(@"array_ldelem.boo");
}
[Test]
public void BOO_1005_1()
{
RunCompilerTestCase(@"BOO-1005-1.boo");
}
[Test]
public void BOO_1005_2()
{
RunCompilerTestCase(@"BOO-1005-2.boo");
}
[Test]
public void BOO_1006_1()
{
RunCompilerTestCase(@"BOO-1006-1.boo");
}
[Test]
public void BOO_1008_1()
{
RunCompilerTestCase(@"BOO-1008-1.boo");
}
[Test]
public void BOO_1009_1()
{
RunCompilerTestCase(@"BOO-1009-1.boo");
}
[Test]
public void BOO_1013_1()
{
RunCompilerTestCase(@"BOO-1013-1.boo");
}
[Test]
public void BOO_1013_2()
{
RunCompilerTestCase(@"BOO-1013-2.boo");
}
[Test]
public void BOO_1016_1()
{
RunCompilerTestCase(@"BOO-1016-1.boo");
}
[Test]
public void BOO_1016_2()
{
RunCompilerTestCase(@"BOO-1016-2.boo");
}
[Test]
public void BOO_1027_1()
{
RunCompilerTestCase(@"BOO-1027-1.boo");
}
[Test]
public void BOO_1031_1()
{
RunCompilerTestCase(@"BOO-1031-1.boo");
}
[Test]
public void BOO_1031_2()
{
RunCompilerTestCase(@"BOO-1031-2.boo");
}
[Test]
public void BOO_1031_3()
{
RunCompilerTestCase(@"BOO-1031-3.boo");
}
[Test]
public void BOO_1031_4()
{
RunCompilerTestCase(@"BOO-1031-4.boo");
}
[Test]
public void boo_1032_1()
{
RunCompilerTestCase(@"boo-1032-1.boo");
}
[Test]
public void boo_1032_2()
{
RunCompilerTestCase(@"boo-1032-2.boo");
}
[Test]
public void BOO_1035_1()
{
RunCompilerTestCase(@"BOO-1035-1.boo");
}
[Test]
public void BOO_104_1()
{
RunCompilerTestCase(@"BOO-104-1.boo");
}
[Test]
public void BOO_1040_1()
{
RunCompilerTestCase(@"BOO-1040-1.boo");
}
[Test]
public void BOO_1047()
{
RunCompilerTestCase(@"BOO-1047.boo");
}
[Test]
public void boo_1051()
{
RunCompilerTestCase(@"boo-1051.boo");
}
[Test]
public void BOO_1069_1()
{
RunCompilerTestCase(@"BOO-1069-1.boo");
}
[Test]
public void BOO_1070_1()
{
RunCompilerTestCase(@"BOO-1070-1.boo");
}
[Test]
public void BOO_1071()
{
RunCompilerTestCase(@"BOO-1071.boo");
}
[Test]
public void BOO_1076()
{
RunCompilerTestCase(@"BOO-1076.boo");
}
[Ignore("broken by SRE bug")][Test]
public void BOO_1078_1()
{
RunCompilerTestCase(@"BOO-1078-1.boo");
}
[Test]
public void BOO_1080_1()
{
RunCompilerTestCase(@"BOO-1080-1.boo");
}
[Test]
public void BOO_1082()
{
RunCompilerTestCase(@"BOO-1082.boo");
}
[Test]
public void BOO_1085()
{
RunCompilerTestCase(@"BOO-1085.boo");
}
[Test]
public void BOO_1086()
{
RunCompilerTestCase(@"BOO-1086.boo");
}
[Test]
public void BOO_1088_1()
{
RunCompilerTestCase(@"BOO-1088-1.boo");
}
[Test]
public void BOO_1091_1()
{
RunCompilerTestCase(@"BOO-1091-1.boo");
}
[Test]
public void BOO_1095_1()
{
RunCompilerTestCase(@"BOO-1095-1.boo");
}
[Test]
public void BOO_1111_1()
{
RunCompilerTestCase(@"BOO-1111-1.boo");
}
[Test]
public void BOO_1127_1()
{
RunCompilerTestCase(@"BOO-1127-1.boo");
}
[Test]
public void BOO_1130_1()
{
RunCompilerTestCase(@"BOO-1130-1.boo");
}
[Test]
public void BOO_1135_1()
{
RunCompilerTestCase(@"BOO-1135-1.boo");
}
[Test]
public void BOO_1147_1()
{
RunCompilerTestCase(@"BOO-1147-1.boo");
}
[Test]
public void BOO_1147_2()
{
RunCompilerTestCase(@"BOO-1147-2.boo");
}
[Test]
public void BOO_1154_1()
{
RunCompilerTestCase(@"BOO-1154-1.boo");
}
[Test]
public void BOO_1160_1()
{
RunCompilerTestCase(@"BOO-1160-1.boo");
}
[Test]
public void BOO_1162_1()
{
RunCompilerTestCase(@"BOO-1162-1.boo");
}
[Test]
public void BOO_1170()
{
RunCompilerTestCase(@"BOO-1170.boo");
}
[Test]
public void BOO_1171_1()
{
RunCompilerTestCase(@"BOO-1171-1.boo");
}
[Test]
public void BOO_1176_1()
{
RunCompilerTestCase(@"BOO-1176-1.boo");
}
[Test]
public void BOO_1177_1()
{
RunCompilerTestCase(@"BOO-1177-1.boo");
}
[Test]
public void BOO_1206_1()
{
RunCompilerTestCase(@"BOO-1206-1.boo");
}
[Test]
public void BOO_121_1()
{
RunCompilerTestCase(@"BOO-121-1.boo");
}
[Test]
public void BOO_1210_1()
{
RunCompilerTestCase(@"BOO-1210-1.boo");
}
[Test]
public void BOO_1217_1()
{
RunCompilerTestCase(@"BOO-1217-1.boo");
}
[Test]
public void BOO_122_1()
{
RunCompilerTestCase(@"BOO-122-1.boo");
}
[Test]
public void BOO_1220_1()
{
RunCompilerTestCase(@"BOO-1220-1.boo");
}
[Test]
public void BOO_123_1()
{
RunCompilerTestCase(@"BOO-123-1.boo");
}
[Test]
public void BOO_1256()
{
RunCompilerTestCase(@"BOO-1256.boo");
}
[Test]
public void BOO_1261_1()
{
RunCompilerTestCase(@"BOO-1261-1.boo");
}
[Ignore("WIP")][Test]
public void BOO_1264()
{
RunCompilerTestCase(@"BOO-1264.boo");
}
[Test]
public void BOO_1288()
{
RunCompilerTestCase(@"BOO-1288.boo");
}
[Test]
public void BOO_129_1()
{
RunCompilerTestCase(@"BOO-129-1.boo");
}
[Test]
public void BOO_1290()
{
RunCompilerTestCase(@"BOO-1290.boo");
}
[Test]
public void BOO_1306()
{
RunCompilerTestCase(@"BOO-1306.boo");
}
[Test]
public void BOO_1307()
{
RunCompilerTestCase(@"BOO-1307.boo");
}
[Test]
public void BOO_1308()
{
RunCompilerTestCase(@"BOO-1308.boo");
}
[Test]
public void BOO_138_1()
{
RunCompilerTestCase(@"BOO-138-1.boo");
}
[Test]
public void BOO_145_1()
{
RunCompilerTestCase(@"BOO-145-1.boo");
}
[Test]
public void BOO_176_1()
{
RunCompilerTestCase(@"BOO-176-1.boo");
}
[Test]
public void BOO_178_1()
{
RunCompilerTestCase(@"BOO-178-1.boo");
}
[Test]
public void BOO_178_2()
{
RunCompilerTestCase(@"BOO-178-2.boo");
}
[Test]
public void BOO_189_1()
{
RunCompilerTestCase(@"BOO-189-1.boo");
}
[Test]
public void BOO_189_2()
{
RunCompilerTestCase(@"BOO-189-2.boo");
}
[Test]
public void BOO_195_1()
{
RunCompilerTestCase(@"BOO-195-1.boo");
}
[Test]
public void BOO_203_1()
{
RunCompilerTestCase(@"BOO-203-1.boo");
}
[Test]
public void BOO_210_1()
{
RunCompilerTestCase(@"BOO-210-1.boo");
}
[Test]
public void BOO_226_1()
{
RunCompilerTestCase(@"BOO-226-1.boo");
}
[Test]
public void BOO_226_2()
{
RunCompilerTestCase(@"BOO-226-2.boo");
}
[Test]
public void BOO_227_1()
{
RunCompilerTestCase(@"BOO-227-1.boo");
}
[Test]
public void BOO_231_1()
{
RunCompilerTestCase(@"BOO-231-1.boo");
}
[Test]
public void BOO_241_1()
{
RunCompilerTestCase(@"BOO-241-1.boo");
}
[Test]
public void BOO_248_1()
{
RunCompilerTestCase(@"BOO-248-1.boo");
}
[Test]
public void BOO_260_1()
{
RunCompilerTestCase(@"BOO-260-1.boo");
}
[Test]
public void BOO_265_1()
{
RunCompilerTestCase(@"BOO-265-1.boo");
}
[Test]
public void BOO_270_1()
{
RunCompilerTestCase(@"BOO-270-1.boo");
}
[Test]
public void BOO_281_1()
{
RunCompilerTestCase(@"BOO-281-1.boo");
}
[Test]
public void BOO_281_2()
{
RunCompilerTestCase(@"BOO-281-2.boo");
}
[Test]
public void BOO_301_1()
{
RunCompilerTestCase(@"BOO-301-1.boo");
}
[Test]
public void BOO_301_2()
{
RunCompilerTestCase(@"BOO-301-2.boo");
}
[Test]
public void BOO_308_1()
{
RunCompilerTestCase(@"BOO-308-1.boo");
}
[Test]
public void BOO_308_2()
{
RunCompilerTestCase(@"BOO-308-2.boo");
}
[Test]
public void BOO_313_1()
{
RunCompilerTestCase(@"BOO-313-1.boo");
}
[Test]
public void BOO_313_10()
{
RunCompilerTestCase(@"BOO-313-10.boo");
}
[Test]
public void BOO_313_11()
{
RunCompilerTestCase(@"BOO-313-11.boo");
}
[Test]
public void BOO_313_12()
{
RunCompilerTestCase(@"BOO-313-12.boo");
}
[Test]
public void BOO_313_2()
{
RunCompilerTestCase(@"BOO-313-2.boo");
}
[Test]
public void BOO_313_3()
{
RunCompilerTestCase(@"BOO-313-3.boo");
}
[Test]
public void BOO_313_4()
{
RunCompilerTestCase(@"BOO-313-4.boo");
}
[Test]
public void BOO_313_5()
{
RunCompilerTestCase(@"BOO-313-5.boo");
}
[Test]
public void BOO_313_6()
{
RunCompilerTestCase(@"BOO-313-6.boo");
}
[Test]
public void BOO_313_7()
{
RunCompilerTestCase(@"BOO-313-7.boo");
}
[Test]
public void BOO_313_8()
{
RunCompilerTestCase(@"BOO-313-8.boo");
}
[Test]
public void BOO_313_9()
{
RunCompilerTestCase(@"BOO-313-9.boo");
}
[Test]
public void BOO_327_1()
{
RunCompilerTestCase(@"BOO-327-1.boo");
}
[Test]
public void BOO_338_1()
{
RunCompilerTestCase(@"BOO-338-1.boo");
}
[Test]
public void BOO_356_1()
{
RunCompilerTestCase(@"BOO-356-1.boo");
}
[Test]
public void BOO_357_1()
{
RunCompilerTestCase(@"BOO-357-1.boo");
}
[Test]
public void BOO_357_2()
{
RunCompilerTestCase(@"BOO-357-2.boo");
}
[Test]
public void BOO_366_1()
{
RunCompilerTestCase(@"BOO-366-1.boo");
}
[Test]
public void BOO_366_2()
{
RunCompilerTestCase(@"BOO-366-2.boo");
}
[Test]
public void BOO_367_1()
{
RunCompilerTestCase(@"BOO-367-1.boo");
}
[Test]
public void BOO_368_1()
{
RunCompilerTestCase(@"BOO-368-1.boo");
}
[Test]
public void BOO_369_1()
{
RunCompilerTestCase(@"BOO-369-1.boo");
}
[Test]
public void BOO_369_2()
{
RunCompilerTestCase(@"BOO-369-2.boo");
}
[Test]
public void BOO_372_1()
{
RunCompilerTestCase(@"BOO-372-1.boo");
}
[Test]
public void BOO_390_1()
{
RunCompilerTestCase(@"BOO-390-1.boo");
}
[Test]
public void BOO_396_1()
{
RunCompilerTestCase(@"BOO-396-1.boo");
}
[Test]
public void BOO_398_1()
{
RunCompilerTestCase(@"BOO-398-1.boo");
}
[Test]
public void BOO_40_1()
{
RunCompilerTestCase(@"BOO-40-1.boo");
}
[Test]
public void BOO_407_1()
{
RunCompilerTestCase(@"BOO-407-1.boo");
}
[Test]
public void BOO_408_1()
{
RunCompilerTestCase(@"BOO-408-1.boo");
}
[Test]
public void BOO_411_1()
{
RunCompilerTestCase(@"BOO-411-1.boo");
}
[Test]
public void BOO_417_1()
{
RunCompilerTestCase(@"BOO-417-1.boo");
}
[Test]
public void BOO_420_1()
{
RunCompilerTestCase(@"BOO-420-1.boo");
}
[Test]
public void BOO_440_1()
{
RunCompilerTestCase(@"BOO-440-1.boo");
}
[Test]
public void BOO_440_2()
{
RunCompilerTestCase(@"BOO-440-2.boo");
}
[Test]
public void BOO_440_3()
{
RunCompilerTestCase(@"BOO-440-3.boo");
}
[Test]
public void BOO_441_1()
{
RunCompilerTestCase(@"BOO-441-1.boo");
}
[Test]
public void BOO_441_2()
{
RunCompilerTestCase(@"BOO-441-2.boo");
}
[Test]
public void BOO_46_1()
{
RunCompilerTestCase(@"BOO-46-1.boo");
}
[Test]
public void BOO_46_2()
{
RunCompilerTestCase(@"BOO-46-2.boo");
}
[Test]
public void BOO_464_1()
{
RunCompilerTestCase(@"BOO-464-1.boo");
}
[Test]
public void BOO_474_1()
{
RunCompilerTestCase(@"BOO-474-1.boo");
}
[Test]
public void BOO_540_1()
{
RunCompilerTestCase(@"BOO-540-1.boo");
}
[Test]
public void BOO_540_2()
{
RunCompilerTestCase(@"BOO-540-2.boo");
}
[Test]
public void BOO_549_1()
{
RunCompilerTestCase(@"BOO-549-1.boo");
}
[Category("FailsOnMono")][Test]
public void BOO_569_1()
{
RunCompilerTestCase(@"BOO-569-1.boo");
}
[Test]
public void BOO_585_1()
{
RunCompilerTestCase(@"BOO-585-1.boo");
}
[Test]
public void BOO_590_1()
{
RunCompilerTestCase(@"BOO-590-1.boo");
}
[Test]
public void BOO_603_1()
{
RunCompilerTestCase(@"BOO-603-1.boo");
}
[Test]
public void BOO_605_1()
{
RunCompilerTestCase(@"BOO-605-1.boo");
}
[Test]
public void BOO_608_1()
{
RunCompilerTestCase(@"BOO-608-1.boo");
}
[Test]
public void BOO_612_1()
{
RunCompilerTestCase(@"BOO-612-1.boo");
}
[Test]
public void BOO_612_2()
{
RunCompilerTestCase(@"BOO-612-2.boo");
}
[Test]
public void BOO_632_1()
{
RunCompilerTestCase(@"BOO-632-1.boo");
}
[Test]
public void BOO_642_1()
{
RunCompilerTestCase(@"BOO-642-1.boo");
}
[Test]
public void BOO_650_1()
{
RunCompilerTestCase(@"BOO-650-1.boo");
}
[Test]
public void BOO_651_1()
{
RunCompilerTestCase(@"BOO-651-1.boo");
}
[Test]
public void BOO_656_1()
{
RunCompilerTestCase(@"BOO-656-1.boo");
}
[Test]
public void BOO_662_1()
{
RunCompilerTestCase(@"BOO-662-1.boo");
}
[Test]
public void BOO_662_2()
{
RunCompilerTestCase(@"BOO-662-2.boo");
}
[Test]
public void BOO_684_1()
{
RunCompilerTestCase(@"BOO-684-1.boo");
}
[Test]
public void BOO_685_1()
{
RunCompilerTestCase(@"BOO-685-1.boo");
}
[Test]
public void BOO_697_1()
{
RunCompilerTestCase(@"BOO-697-1.boo");
}
[Test]
public void BOO_698_1()
{
RunCompilerTestCase(@"BOO-698-1.boo");
}
[Test]
public void BOO_705_1()
{
RunCompilerTestCase(@"BOO-705-1.boo");
}
[Category("FailsOnMono")][Test]
public void BOO_707_1()
{
RunCompilerTestCase(@"BOO-707-1.boo");
}
[Category("FailsOnMono")][Test]
public void BOO_709_1()
{
RunCompilerTestCase(@"BOO-709-1.boo");
}
[Test]
public void BOO_710_1()
{
RunCompilerTestCase(@"BOO-710-1.boo");
}
[Test]
public void BOO_714_1()
{
RunCompilerTestCase(@"BOO-714-1.boo");
}
[Test]
public void BOO_719_1()
{
RunCompilerTestCase(@"BOO-719-1.boo");
}
[Test]
public void BOO_719_2()
{
RunCompilerTestCase(@"BOO-719-2.boo");
}
[Test]
public void BOO_723_1()
{
RunCompilerTestCase(@"BOO-723-1.boo");
}
[Test]
public void BOO_724_1()
{
RunCompilerTestCase(@"BOO-724-1.boo");
}
[Test]
public void BOO_724_2()
{
RunCompilerTestCase(@"BOO-724-2.boo");
}
[Test]
public void BOO_725_1()
{
RunCompilerTestCase(@"BOO-725-1.boo");
}
[Test]
public void BOO_729_1()
{
RunCompilerTestCase(@"BOO-729-1.boo");
}
[Test]
public void BOO_736_1()
{
RunCompilerTestCase(@"BOO-736-1.boo");
}
[Test]
public void BOO_739_1()
{
RunCompilerTestCase(@"BOO-739-1.boo");
}
[Test]
public void BOO_739_2()
{
RunCompilerTestCase(@"BOO-739-2.boo");
}
[Test]
public void BOO_747_1()
{
RunCompilerTestCase(@"BOO-747-1.boo");
}
[Test]
public void BOO_747_2()
{
RunCompilerTestCase(@"BOO-747-2.boo");
}
[Test]
public void BOO_748_1()
{
RunCompilerTestCase(@"BOO-748-1.boo");
}
[Test]
public void BOO_75_1()
{
RunCompilerTestCase(@"BOO-75-1.boo");
}
[Test]
public void BOO_753_1()
{
RunCompilerTestCase(@"BOO-753-1.boo");
}
[Test]
public void BOO_753_2()
{
RunCompilerTestCase(@"BOO-753-2.boo");
}
[Test]
public void BOO_76_1()
{
RunCompilerTestCase(@"BOO-76-1.boo");
}
[Test]
public void BOO_76_2()
{
RunCompilerTestCase(@"BOO-76-2.boo");
}
[Test]
public void BOO_77_1()
{
RunCompilerTestCase(@"BOO-77-1.boo");
}
[Test]
public void BOO_770_1()
{
RunCompilerTestCase(@"BOO-770-1.boo");
}
[Ignore("Preference for generic not complete")][Test]
public void BOO_779_1()
{
RunCompilerTestCase(@"BOO-779-1.boo");
}
[Ignore("Preference for generic not complete")][Test]
public void BOO_779_2()
{
RunCompilerTestCase(@"BOO-779-2.boo");
}
[Ignore("Non-IEnumerable definitions of GetEnumerator() not yet supported")][Test]
public void BOO_779_3()
{
RunCompilerTestCase(@"BOO-779-3.boo");
}
[Test]
public void BOO_779_4()
{
RunCompilerTestCase(@"BOO-779-4.boo");
}
[Test]
public void BOO_792_1()
{
RunCompilerTestCase(@"BOO-792-1.boo");
}
[Test]
public void BOO_792_2()
{
RunCompilerTestCase(@"BOO-792-2.boo");
}
[Test]
public void BOO_799_1()
{
RunCompilerTestCase(@"BOO-799-1.boo");
}
[Test]
public void BOO_806_1()
{
RunCompilerTestCase(@"BOO-806-1.boo");
}
[Test]
public void BOO_809_1()
{
RunCompilerTestCase(@"BOO-809-1.boo");
}
[Test]
public void BOO_809_2()
{
RunCompilerTestCase(@"BOO-809-2.boo");
}
[Test]
public void BOO_809_3()
{
RunCompilerTestCase(@"BOO-809-3.boo");
}
[Test]
public void BOO_809_4()
{
RunCompilerTestCase(@"BOO-809-4.boo");
}
[Test]
public void BOO_813_1()
{
RunCompilerTestCase(@"BOO-813-1.boo");
}
[Test]
public void BOO_826()
{
RunCompilerTestCase(@"BOO-826.boo");
}
[Test]
public void BOO_835_1()
{
RunCompilerTestCase(@"BOO-835-1.boo");
}
[Test]
public void BOO_844_1()
{
RunCompilerTestCase(@"BOO-844-1.boo");
}
[Test]
public void BOO_844_2()
{
RunCompilerTestCase(@"BOO-844-2.boo");
}
[Test]
public void BOO_85_1()
{
RunCompilerTestCase(@"BOO-85-1.boo");
}
[Test]
public void BOO_860_1()
{
RunCompilerTestCase(@"BOO-860-1.boo");
}
[Test]
public void BOO_861_1()
{
RunCompilerTestCase(@"BOO-861-1.boo");
}
[Test]
public void BOO_862_1()
{
RunCompilerTestCase(@"BOO-862-1.boo");
}
[Test]
public void BOO_862_2()
{
RunCompilerTestCase(@"BOO-862-2.boo");
}
[Test]
public void BOO_864_1()
{
RunCompilerTestCase(@"BOO-864-1.boo");
}
[Test]
public void BOO_865_1()
{
RunCompilerTestCase(@"BOO-865-1.boo");
}
[Test]
public void BOO_88_1()
{
RunCompilerTestCase(@"BOO-88-1.boo");
}
[Test]
public void BOO_882()
{
RunCompilerTestCase(@"BOO-882.boo");
}
[Test]
public void BOO_893_1()
{
RunCompilerTestCase(@"BOO-893-1.boo");
}
[Test]
public void BOO_90_1()
{
RunCompilerTestCase(@"BOO-90-1.boo");
}
[Test]
public void BOO_913_1()
{
RunCompilerTestCase(@"BOO-913-1.boo");
}
[Test]
public void BOO_935_1()
{
RunCompilerTestCase(@"BOO-935-1.boo");
}
[Test]
public void BOO_935_2()
{
RunCompilerTestCase(@"BOO-935-2.boo");
}
[Test]
public void BOO_948_1()
{
RunCompilerTestCase(@"BOO-948-1.boo");
}
[Test]
public void BOO_949_1()
{
RunCompilerTestCase(@"BOO-949-1.boo");
}
[Test]
public void BOO_949_2()
{
RunCompilerTestCase(@"BOO-949-2.boo");
}
[Test]
public void BOO_952_1()
{
RunCompilerTestCase(@"BOO-952-1.boo");
}
[Test]
public void BOO_955_1()
{
RunCompilerTestCase(@"BOO-955-1.boo");
}
[Test]
public void BOO_958_1()
{
RunCompilerTestCase(@"BOO-958-1.boo");
}
[Test]
public void BOO_960()
{
RunCompilerTestCase(@"BOO-960.boo");
}
[Test]
public void BOO_973_1()
{
RunCompilerTestCase(@"BOO-973-1.boo");
}
[Test]
public void BOO_974_1()
{
RunCompilerTestCase(@"BOO-974-1.boo");
}
[Test]
public void BOO_975_1()
{
RunCompilerTestCase(@"BOO-975-1.boo");
}
[Test]
public void BOO_977_1()
{
RunCompilerTestCase(@"BOO-977-1.boo");
}
[Test]
public void BOO_979_1()
{
RunCompilerTestCase(@"BOO-979-1.boo");
}
[Test]
public void BOO_979_2()
{
RunCompilerTestCase(@"BOO-979-2.boo");
}
[Test]
public void BOO_982_1()
{
RunCompilerTestCase(@"BOO-982-1.boo");
}
[Test]
public void BOO_983_1()
{
RunCompilerTestCase(@"BOO-983-1.boo");
}
[Test]
public void BOO_983_2()
{
RunCompilerTestCase(@"BOO-983-2.boo");
}
[Test]
public void BOO_986_1()
{
RunCompilerTestCase(@"BOO-986-1.boo");
}
[Test]
public void BOO_99_1()
{
RunCompilerTestCase(@"BOO-99-1.boo");
}
[Test]
public void BOO_992_1()
{
RunCompilerTestCase(@"BOO-992-1.boo");
}
[Test]
public void BOO_992_2()
{
RunCompilerTestCase(@"BOO-992-2.boo");
}
[Test]
public void BOO_999_1()
{
RunCompilerTestCase(@"BOO-999-1.boo");
}
[Test]
public void complex_iterators_1()
{
RunCompilerTestCase(@"complex-iterators-1.boo");
}
[Test]
public void duck_default_member_overload()
{
RunCompilerTestCase(@"duck-default-member-overload.boo");
}
[Test]
public void duck_default_setter_overload()
{
RunCompilerTestCase(@"duck-default-setter-overload.boo");
}
[Test]
public void for_re_Split()
{
RunCompilerTestCase(@"for-re-Split.boo");
}
[Test]
public void generators_1()
{
RunCompilerTestCase(@"generators-1.boo");
}
[Test]
public void method_with_type_inference_rule_as_statement()
{
RunCompilerTestCase(@"method-with-type-inference-rule-as-statement.boo");
}
[Test]
public void nullables_and_generators()
{
RunCompilerTestCase(@"nullables-and-generators.boo");
}
[Test]
public void override_inference()
{
RunCompilerTestCase(@"override-inference.boo");
}
[Test]
public void linq_filter_error()
{
RunCompilerTestCase(@"linq-filter-error.boo");
}
[Test]
public void linq_filter_error_2()
{
RunCompilerTestCase(@"linq-filter-error-2.boo");
}
[Test]
public void delegate_overload()
{
RunCompilerTestCase(@"delegate-overload.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "regression";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Globalization;
using Xunit;
using SortedList_SortedListUtils;
namespace SortedListCtorIDicIKeyComp
{
public class Driver<KeyType, ValueType>
{
private Test m_test;
public Driver(Test test)
{
m_test = test;
}
private static CultureInfo s_english = new CultureInfo("en");
private static CultureInfo s_german = new CultureInfo("de");
private static CultureInfo s_danish = new CultureInfo("da");
private static CultureInfo s_turkish = new CultureInfo("tr");
//CompareString lcid_en-US, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 1, NULL_STRING
//CompareString 0x10407, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 0, NULL_STRING
//CompareString lcid_da-DK, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, -1, NULL_STRING
//CompareString lcid_en-US, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, 0, NULL_STRING
//CompareString lcid_tr-TR, "NORM_IGNORECASE", "\u0131", 0, 1, "\u0049", 0, 1, 0, NULL_STRING
private const String strAE = "AE";
private const String strUC4 = "\u00C4";
private const String straA = "aA";
private const String strAa = "Aa";
private const String strI = "I";
private const String strTurkishUpperI = "\u0131";
private const String strBB = "BB";
private const String strbb = "bb";
private const String value = "Default_Value";
public void TestEnum(IDictionary<String, String> idic)
{
SortedList<String, String> _dic;
IComparer<String> comparer;
String[] keys = new String[idic.Count];
idic.Keys.CopyTo(keys, 0);
String[] values = new String[idic.Count];
idic.Values.CopyTo(values, 0);
IComparer<String>[] predefinedComparers = new IComparer<String>[] {
StringComparer.CurrentCulture,
StringComparer.CurrentCultureIgnoreCase,
StringComparer.OrdinalIgnoreCase,
StringComparer.Ordinal};
foreach (IComparer<String> predefinedComparer in predefinedComparers)
{
_dic = new SortedList<String, String>(idic, predefinedComparer);
m_test.Eval(_dic.Comparer == predefinedComparer, String.Format("Err_4568aijueud! Comparer differ expected: {0} actual: {1}", predefinedComparer, _dic.Comparer));
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.ContainsKey(keys[i]), String.Format("Err_234afs! key not found: {0}", keys[i]));
m_test.Eval(_dic.ContainsValue(values[i]), String.Format("Err_3497sg! value not found: {0}", values[i]));
}
}
//Current culture
CultureInfo.DefaultThreadCurrentCulture = s_english;
comparer = StringComparer.CurrentCulture;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_58484aheued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strAE, value);
m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_235rdag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));
//bug #11263 in NDPWhidbey
CultureInfo.DefaultThreadCurrentCulture = s_german;
comparer = StringComparer.CurrentCulture;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_5468ahiede! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strAE, value);
// same result in Desktop
m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_23r7ag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));
//CurrentCultureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = s_english;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_4488ajede! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(straA, value);
m_test.Eval(_dic.ContainsKey(strAa), String.Format("Err_237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = s_danish;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_6884ahnjed! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
//OrdinalIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = s_english;
comparer = StringComparer.OrdinalIgnoreCase;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_95877ahiez! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strI, value);
m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234qf! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));
CultureInfo.DefaultThreadCurrentCulture = s_turkish;
comparer = StringComparer.OrdinalIgnoreCase;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_50548haied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strI, value);
m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234ra7g! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));
//Ordinal - not that many meaningful test
CultureInfo.DefaultThreadCurrentCulture = s_english;
comparer = StringComparer.Ordinal;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_1407hizbd! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strBB, value);
m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_1244sd! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
CultureInfo.DefaultThreadCurrentCulture = s_danish;
comparer = StringComparer.Ordinal;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_5088aied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strBB, value);
m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_235aeg! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
}
public void TestParm()
{
//passing null will revert to the default comparison mechanism
SortedList<String, String> _dic;
IComparer<String> comparer = null;
SortedList<String, String> dic1 = new SortedList<String, String>();
try
{
CultureInfo.DefaultThreadCurrentCulture = s_english;
_dic = new SortedList<String, String>(dic1, comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_9237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = s_danish;
_dic = new SortedList<String, String>(dic1, comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_90723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
comparer = StringComparer.CurrentCulture;
dic1 = null;
try
{
CultureInfo.DefaultThreadCurrentCulture = s_english;
_dic = new SortedList<String, String>(dic1, comparer);
m_test.Eval(false, String.Format("Err_387tsg! exception not thrown"));
}
catch (ArgumentNullException)
{
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
}
public void IkeyComparerOwnImplementation(IDictionary<String, String> idic)
{
//This just ensure that we can call our own implementation
SortedList<String, String> _dic;
IComparer<String> comparer = new MyOwnIKeyImplementation<String>();
try
{
CultureInfo.DefaultThreadCurrentCulture = s_english;
_dic = new SortedList<String, String>(idic, comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = s_danish;
_dic = new SortedList<String, String>(idic, comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_00723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
}
}
public class Constructor_IDictionary_IKeyComparer
{
[Fact]
[ActiveIssue(5460, PlatformID.AnyUnix)]
public static void RunTests()
{
//This mostly follows the format established by the original author of these tests
Test test = new Test();
Driver<String, String> driver1 = new Driver<String, String>(test);
Driver<SimpleRef<int>, SimpleRef<String>> driver2 = new Driver<SimpleRef<int>, SimpleRef<String>>(test);
Driver<SimpleRef<String>, SimpleRef<int>> driver3 = new Driver<SimpleRef<String>, SimpleRef<int>>(test);
Driver<SimpleRef<int>, SimpleRef<int>> driver4 = new Driver<SimpleRef<int>, SimpleRef<int>>(test);
Driver<SimpleRef<String>, SimpleRef<String>> driver5 = new Driver<SimpleRef<String>, SimpleRef<String>>(test);
int count;
SimpleRef<int>[] simpleInts;
SimpleRef<String>[] simpleStrings;
String[] strings;
SortedList<String, String> dic1;
count = 10;
strings = new String[count];
for (int i = 0; i < count; i++)
strings[i] = i.ToString();
simpleInts = GetSimpleInts(count);
simpleStrings = GetSimpleStrings(count);
dic1 = FillValues(strings, strings);
//Scenario 1: Pass all the enum values and ensure that the behavior is correct
driver1.TestEnum(dic1);
//Scenario 2: Parm validation: null
driver1.TestParm();
//Scenario 3: Implement our own IKeyComparer and check
driver1.IkeyComparerOwnImplementation(dic1);
//Scenario 5: ensure that SortedList items from the passed IDictionary object use the interface IKeyComparer's Equals and GetHashCode APIs.
//Ex. Pass the case invariant IKeyComparer and check
//@TODO!!!
//Scenario 6: Contradictory values and check: ex. IDictionary is case insensitive but IKeyComparer is not
Assert.True(test.result);
}
private static SortedList<KeyType, ValueType> FillValues<KeyType, ValueType>(KeyType[] keys, ValueType[] values)
{
SortedList<KeyType, ValueType> _dic = new SortedList<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
return _dic;
}
private static SimpleRef<int>[] GetSimpleInts(int count)
{
SimpleRef<int>[] simpleInts = new SimpleRef<int>[count];
for (int i = 0; i < count; i++)
simpleInts[i] = new SimpleRef<int>(i);
return simpleInts;
}
private static SimpleRef<String>[] GetSimpleStrings(int count)
{
SimpleRef<String>[] simpleStrings = new SimpleRef<String>[count];
for (int i = 0; i < count; i++)
simpleStrings[i] = new SimpleRef<String>(i.ToString());
return simpleStrings;
}
}
//[Serializable]
internal class MyOwnIKeyImplementation<KeyType> : IComparer<KeyType> where KeyType : IComparable<KeyType>
{
public int GetHashCode(KeyType key)
{
if (null == key)
return 0;
//We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly
return key.GetHashCode();
}
public int Compare(KeyType key1, KeyType key2)
{
if (null == key1)
{
if (null == key2)
return 0;
return -1;
}
return key1.CompareTo(key2);
}
public bool Equals(KeyType key1, KeyType key2)
{
if (null == key1)
return null == key2;
return key1.Equals(key2);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace System.Xml
{
#if XMLSERIALIZERGENERATOR
internal abstract class IncrementalReadDecoder
{
internal abstract int DecodedCount { get; }
internal abstract bool IsFull { get; }
internal abstract void SetNextOutputBuffer(Array array, int offset, int len);
internal abstract int Decode(char[] chars, int startPos, int len);
internal abstract int Decode(string str, int startPos, int len);
internal abstract void Reset();
}
#endif
internal class BinHexDecoder : IncrementalReadDecoder
{
//
// Fields
//
private byte[] _buffer;
private int _startIndex;
private int _curIndex;
private int _endIndex;
private bool _hasHalfByteCached;
private byte _cachedHalfByte;
//
// IncrementalReadDecoder interface
//
internal override int DecodedCount
{
get
{
return _curIndex - _startIndex;
}
}
internal override bool IsFull
{
get
{
return _curIndex == _endIndex;
}
}
[System.Security.SecuritySafeCritical]
internal override unsafe int Decode(char[] chars, int startPos, int len)
{
if (chars == null)
{
throw new ArgumentNullException(nameof(chars));
}
if (len < 0)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (startPos < 0)
{
throw new ArgumentOutOfRangeException(nameof(startPos));
}
if (chars.Length - startPos < len)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = &chars[startPos])
{
fixed (byte* pBytes = &_buffer[_curIndex])
{
Decode(pChars, pChars + len, pBytes, pBytes + (_endIndex - _curIndex),
ref _hasHalfByteCached, ref _cachedHalfByte, out charsDecoded, out bytesDecoded);
}
}
_curIndex += bytesDecoded;
return charsDecoded;
}
[System.Security.SecuritySafeCritical]
internal override unsafe int Decode(string str, int startPos, int len)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (len < 0)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (startPos < 0)
{
throw new ArgumentOutOfRangeException(nameof(startPos));
}
if (str.Length - startPos < len)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = str)
{
fixed (byte* pBytes = &_buffer[_curIndex])
{
Decode(pChars + startPos, pChars + startPos + len, pBytes, pBytes + (_endIndex - _curIndex),
ref _hasHalfByteCached, ref _cachedHalfByte, out charsDecoded, out bytesDecoded);
}
}
_curIndex += bytesDecoded;
return charsDecoded;
}
internal override void Reset()
{
_hasHalfByteCached = false;
_cachedHalfByte = 0;
}
internal override void SetNextOutputBuffer(Array buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(index >= 0);
Debug.Assert(buffer.Length - index >= count);
Debug.Assert((buffer as byte[]) != null);
_buffer = (byte[])buffer;
_startIndex = index;
_curIndex = index;
_endIndex = index + count;
}
//
// Static methods
//
[System.Security.SecuritySafeCritical]
public static unsafe byte[] Decode(char[] chars, bool allowOddChars)
{
if (chars == null)
{
throw new ArgumentNullException(nameof(chars));
}
int len = chars.Length;
if (len == 0)
{
return Array.Empty<byte>();
}
byte[] bytes = new byte[(len + 1) / 2];
int bytesDecoded, charsDecoded;
bool hasHalfByteCached = false;
byte cachedHalfByte = 0;
fixed (char* pChars = &chars[0])
{
fixed (byte* pBytes = &bytes[0])
{
Decode(pChars, pChars + len, pBytes, pBytes + bytes.Length, ref hasHalfByteCached, ref cachedHalfByte, out charsDecoded, out bytesDecoded);
}
}
if (hasHalfByteCached && !allowOddChars)
{
#if XMLSERIALIZERGENERATOR
throw new XmlException(SR.Format(SR.Xml_InvalidBinHexValueOddCount, new string(chars)));
#else
throw new XmlException(SR.Xml_InvalidBinHexValueOddCount, new string(chars));
#endif
}
if (bytesDecoded < bytes.Length)
{
byte[] tmp = new byte[bytesDecoded];
Buffer.BlockCopy(bytes, 0, tmp, 0, bytesDecoded);
bytes = tmp;
}
return bytes;
}
//
// Private methods
//
[System.Security.SecurityCritical]
private static unsafe void Decode(char* pChars, char* pCharsEndPos,
byte* pBytes, byte* pBytesEndPos,
ref bool hasHalfByteCached, ref byte cachedHalfByte,
out int charsDecoded, out int bytesDecoded)
{
#if DEBUG
Debug.Assert(pCharsEndPos - pChars >= 0);
Debug.Assert(pBytesEndPos - pBytes >= 0);
#endif
char* pChar = pChars;
byte* pByte = pBytes;
XmlCharType xmlCharType = XmlCharType.Instance;
while (pChar < pCharsEndPos && pByte < pBytesEndPos)
{
byte halfByte;
char ch = *pChar++;
if (ch >= 'a' && ch <= 'f')
{
halfByte = (byte)(ch - 'a' + 10);
}
else if (ch >= 'A' && ch <= 'F')
{
halfByte = (byte)(ch - 'A' + 10);
}
else if (ch >= '0' && ch <= '9')
{
halfByte = (byte)(ch - '0');
}
else if (xmlCharType.IsWhiteSpace(ch))
{
continue;
}
else
{
#if XMLSERIALIZERGENERATOR
throw new XmlException(SR.Format(SR.Xml_InvalidBinHexValue, new string(pChars, 0, (int)(pCharsEndPos - pChars))));
#else
throw new XmlException(SR.Xml_InvalidBinHexValue, new string(pChars, 0, (int)(pCharsEndPos - pChars)));
#endif
}
if (hasHalfByteCached)
{
*pByte++ = (byte)((cachedHalfByte << 4) + halfByte);
hasHalfByteCached = false;
}
else
{
cachedHalfByte = halfByte;
hasHalfByteCached = true;
}
}
bytesDecoded = (int)(pByte - pBytes);
charsDecoded = (int)(pChar - pChars);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Retail.V2.Snippets
{
using Google.Api;
using Google.LongRunning;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedUserEventServiceClientSnippets
{
/// <summary>Snippet for WriteUserEvent</summary>
public void WriteUserEventRequestObject()
{
// Snippet: WriteUserEvent(WriteUserEventRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
WriteUserEventRequest request = new WriteUserEventRequest
{
Parent = "",
UserEvent = new UserEvent(),
};
// Make the request
UserEvent response = userEventServiceClient.WriteUserEvent(request);
// End snippet
}
/// <summary>Snippet for WriteUserEventAsync</summary>
public async Task WriteUserEventRequestObjectAsync()
{
// Snippet: WriteUserEventAsync(WriteUserEventRequest, CallSettings)
// Additional: WriteUserEventAsync(WriteUserEventRequest, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
WriteUserEventRequest request = new WriteUserEventRequest
{
Parent = "",
UserEvent = new UserEvent(),
};
// Make the request
UserEvent response = await userEventServiceClient.WriteUserEventAsync(request);
// End snippet
}
/// <summary>Snippet for CollectUserEvent</summary>
public void CollectUserEventRequestObject()
{
// Snippet: CollectUserEvent(CollectUserEventRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
CollectUserEventRequest request = new CollectUserEventRequest
{
Parent = "",
UserEvent = "",
Uri = "",
Ets = 0L,
};
// Make the request
HttpBody response = userEventServiceClient.CollectUserEvent(request);
// End snippet
}
/// <summary>Snippet for CollectUserEventAsync</summary>
public async Task CollectUserEventRequestObjectAsync()
{
// Snippet: CollectUserEventAsync(CollectUserEventRequest, CallSettings)
// Additional: CollectUserEventAsync(CollectUserEventRequest, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
CollectUserEventRequest request = new CollectUserEventRequest
{
Parent = "",
UserEvent = "",
Uri = "",
Ets = 0L,
};
// Make the request
HttpBody response = await userEventServiceClient.CollectUserEventAsync(request);
// End snippet
}
/// <summary>Snippet for PurgeUserEvents</summary>
public void PurgeUserEventsRequestObject()
{
// Snippet: PurgeUserEvents(PurgeUserEventsRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
PurgeUserEventsRequest request = new PurgeUserEventsRequest
{
Parent = "",
Filter = "",
Force = false,
};
// Make the request
Operation<PurgeUserEventsResponse, PurgeMetadata> response = userEventServiceClient.PurgeUserEvents(request);
// Poll until the returned long-running operation is complete
Operation<PurgeUserEventsResponse, PurgeMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
PurgeUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<PurgeUserEventsResponse, PurgeMetadata> retrievedResponse = userEventServiceClient.PollOncePurgeUserEvents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
PurgeUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PurgeUserEventsAsync</summary>
public async Task PurgeUserEventsRequestObjectAsync()
{
// Snippet: PurgeUserEventsAsync(PurgeUserEventsRequest, CallSettings)
// Additional: PurgeUserEventsAsync(PurgeUserEventsRequest, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
PurgeUserEventsRequest request = new PurgeUserEventsRequest
{
Parent = "",
Filter = "",
Force = false,
};
// Make the request
Operation<PurgeUserEventsResponse, PurgeMetadata> response = await userEventServiceClient.PurgeUserEventsAsync(request);
// Poll until the returned long-running operation is complete
Operation<PurgeUserEventsResponse, PurgeMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
PurgeUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<PurgeUserEventsResponse, PurgeMetadata> retrievedResponse = await userEventServiceClient.PollOncePurgeUserEventsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
PurgeUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportUserEvents</summary>
public void ImportUserEventsRequestObject()
{
// Snippet: ImportUserEvents(ImportUserEventsRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
ImportUserEventsRequest request = new ImportUserEventsRequest
{
ParentAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"),
InputConfig = new UserEventInputConfig(),
ErrorsConfig = new ImportErrorsConfig(),
};
// Make the request
Operation<ImportUserEventsResponse, ImportMetadata> response = userEventServiceClient.ImportUserEvents(request);
// Poll until the returned long-running operation is complete
Operation<ImportUserEventsResponse, ImportMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ImportUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportUserEventsResponse, ImportMetadata> retrievedResponse = userEventServiceClient.PollOnceImportUserEvents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportUserEventsAsync</summary>
public async Task ImportUserEventsRequestObjectAsync()
{
// Snippet: ImportUserEventsAsync(ImportUserEventsRequest, CallSettings)
// Additional: ImportUserEventsAsync(ImportUserEventsRequest, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
ImportUserEventsRequest request = new ImportUserEventsRequest
{
ParentAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"),
InputConfig = new UserEventInputConfig(),
ErrorsConfig = new ImportErrorsConfig(),
};
// Make the request
Operation<ImportUserEventsResponse, ImportMetadata> response = await userEventServiceClient.ImportUserEventsAsync(request);
// Poll until the returned long-running operation is complete
Operation<ImportUserEventsResponse, ImportMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ImportUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportUserEventsResponse, ImportMetadata> retrievedResponse = await userEventServiceClient.PollOnceImportUserEventsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for RejoinUserEvents</summary>
public void RejoinUserEventsRequestObject()
{
// Snippet: RejoinUserEvents(RejoinUserEventsRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
RejoinUserEventsRequest request = new RejoinUserEventsRequest
{
Parent = "",
UserEventRejoinScope = RejoinUserEventsRequest.Types.UserEventRejoinScope.Unspecified,
};
// Make the request
Operation<RejoinUserEventsResponse, RejoinUserEventsMetadata> response = userEventServiceClient.RejoinUserEvents(request);
// Poll until the returned long-running operation is complete
Operation<RejoinUserEventsResponse, RejoinUserEventsMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
RejoinUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<RejoinUserEventsResponse, RejoinUserEventsMetadata> retrievedResponse = userEventServiceClient.PollOnceRejoinUserEvents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
RejoinUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for RejoinUserEventsAsync</summary>
public async Task RejoinUserEventsRequestObjectAsync()
{
// Snippet: RejoinUserEventsAsync(RejoinUserEventsRequest, CallSettings)
// Additional: RejoinUserEventsAsync(RejoinUserEventsRequest, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
RejoinUserEventsRequest request = new RejoinUserEventsRequest
{
Parent = "",
UserEventRejoinScope = RejoinUserEventsRequest.Types.UserEventRejoinScope.Unspecified,
};
// Make the request
Operation<RejoinUserEventsResponse, RejoinUserEventsMetadata> response = await userEventServiceClient.RejoinUserEventsAsync(request);
// Poll until the returned long-running operation is complete
Operation<RejoinUserEventsResponse, RejoinUserEventsMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
RejoinUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<RejoinUserEventsResponse, RejoinUserEventsMetadata> retrievedResponse = await userEventServiceClient.PollOnceRejoinUserEventsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
RejoinUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
// 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.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
public class HtmlHelperPasswordTest
{
public static TheoryData<object> HtmlAttributeData
{
get
{
return new TheoryData<object>
{
new Dictionary<string, object>
{
{ "name", "-expression-" }, // overridden
{ "test-key", "test-value" },
{ "value", "attribute-value" },
},
new
{
name = "-expression-", // overridden
test_key = "test-value",
value = "attribute-value",
},
};
}
}
public static TheoryData<ViewDataDictionary<PasswordModel>, object> PasswordWithViewDataAndAttributesData
{
get
{
var nullModelViewData = GetViewDataWithNullModelAndNonEmptyViewData();
var viewData = GetViewDataWithModelStateAndModelAndViewDataValues();
viewData.Model.Property1 = "does-not-get-used";
var data = new TheoryData<ViewDataDictionary<PasswordModel>, object>();
foreach (var items in HtmlAttributeData)
{
data.Add(viewData, items[0]);
data.Add(nullModelViewData, items[0]);
}
return data;
}
}
[Theory]
[MemberData(nameof(PasswordWithViewDataAndAttributesData))]
public void Password_UsesAttributeValueWhenValueArgumentIsNull(
ViewDataDictionary<PasswordModel> viewData,
object attributes)
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
@"test-key=""HtmlEncode[[test-value]]"" type=""HtmlEncode[[password]]"" " +
@"value=""HtmlEncode[[attribute-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
// Act
var result = helper.Password("Property1", value: null, htmlAttributes: attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(PasswordWithViewDataAndAttributesData))]
public void Password_UsesExplicitValue_IfSpecified(
ViewDataDictionary<PasswordModel> viewData,
object attributes)
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
@"test-key=""HtmlEncode[[test-value]]"" type=""HtmlEncode[[password]]"" " +
@"value=""HtmlEncode[[explicit-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
// Act
var result = helper.Password("Property1", "explicit-value", attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void PasswordWithPrefix_GeneratesExpectedValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix_Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[password]]"" " +
@"value=""HtmlEncode[[explicit-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
// Act
var result = helper.Password("Property1", "explicit-value", htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void PasswordWithPrefix_UsesIdDotReplacementToken()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix$Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[password]]"" " +
@"value=""HtmlEncode[[explicit-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
GetViewDataWithModelStateAndModelAndViewDataValues(),
idAttributeDotReplacement: "$");
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
// Act
var result = helper.Password("Property1", "explicit-value", htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void PasswordWithPrefixAndEmptyName_GeneratesExpectedValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix]]"" name=""HtmlEncode[[MyPrefix]]"" type=""HtmlEncode[[password]]"" value=""HtmlEncode[[explicit-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
var name = string.Empty;
// Act
var result = helper.Password(name, "explicit-value", htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void PasswordWithEmptyNameAndPrefixThrows()
{
// Arrange
var helper = DefaultTemplatesUtilities.GetHtmlHelper("model-value");
var expression = string.Empty;
var expectedMessage = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
// Act and Assert
ExceptionAssert.ThrowsArgument(
() => helper.Password(expression, value: null, htmlAttributes: null),
"expression",
expectedMessage);
}
[Fact]
public void PasswordWithEmptyNameAndPrefix_DoesNotThrow_WithNameAttribute()
{
// Arrange
var expected = @"<input name=""HtmlEncode[[-expression-]]"" type=""HtmlEncode[[password]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper("model-value");
var expression = string.Empty;
var htmlAttributes = new { name = "-expression-" };
// Act
var result = helper.Password(expression, value: null, htmlAttributes: htmlAttributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void Password_UsesModelStateErrors_ButDoesNotUseModelOrViewDataOrModelStateForValueAttribute()
{
// Arrange
var expected = @"<input class=""HtmlEncode[[some-class input-validation-error]]"" id=""HtmlEncode[[Property1]]""" +
@" name=""HtmlEncode[[Property1]]"" test-key=""HtmlEncode[[test-value]]"" type=""HtmlEncode[[password]]"" />";
var vdd = GetViewDataWithErrors();
vdd.Model.Property1 = "property-value";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(vdd);
var attributes = new Dictionary<string, object>
{
{ "test-key", "test-value" },
{ "class", "some-class"}
};
// Act
var result = helper.Password("Property1", value: null, htmlAttributes: attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void PasswordGeneratesUnobtrusiveValidation()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property2");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[password]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
// Act
var result = helper.Password("Property2", value: null, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
public static IEnumerable<object[]> PasswordWithComplexExpressions_UsesIdDotSeparatorData
{
get
{
yield return new object[]
{
"Property4.Property5",
@"<input data-test=""HtmlEncode[[val]]"" id=""HtmlEncode[[Property4$$Property5]]"" name=""HtmlEncode[[Property4.Property5]]"" " +
@"type=""HtmlEncode[[password]]"" />",
};
yield return new object[]
{
"Property4.Property6[0]",
@"<input data-test=""HtmlEncode[[val]]"" id=""HtmlEncode[[Property4$$Property6$$0$$]]"" name=""HtmlEncode[[Property4.Property6[0]]]"" " +
@"type=""HtmlEncode[[password]]"" />",
};
}
}
[Theory]
[MemberData(nameof(PasswordWithComplexExpressions_UsesIdDotSeparatorData))]
public void PasswordWithComplexExpressions_UsesIdDotSeparator(string expression, string expected)
{
// Arrange
var viewData = GetViewDataWithModelStateAndModelAndViewDataValues();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData, idAttributeDotReplacement: "$$");
var attributes = new Dictionary<string, object> { { "data-test", "val" } };
// Act
var result = helper.Password(expression, value: null, htmlAttributes: attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(HtmlAttributeData))]
public void PasswordForWithAttributes_GeneratesExpectedValue(object htmlAttributes)
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
@"test-key=""HtmlEncode[[test-value]]"" type=""HtmlEncode[[password]]"" " +
@"value=""HtmlEncode[[attribute-value]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewData.Model.Property1 = "test";
// Act
var result = helper.PasswordFor(m => m.Property1, htmlAttributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void PasswordForWithPrefix_GeneratesExpectedValue()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[MyPrefix_Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[password]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
// Act
var result = helper.PasswordFor(m => m.Property1, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void PasswordFor_UsesModelStateErrors_ButDoesNotUseModelOrViewDataOrModelStateForValueAttribute()
{
// Arrange
var expected = @"<input baz=""HtmlEncode[[BazValue]]"" class=""HtmlEncode[[some-class input-validation-error]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[password]]"" />";
var vdd = GetViewDataWithErrors();
vdd.Model.Property1 = "prop1-value";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(vdd);
var attributes = new Dictionary<string, object>
{
{ "baz", "BazValue" },
{ "class", "some-class"}
};
// Act
var result = helper.PasswordFor(m => m.Property1, attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void PasswordFor_GeneratesUnobtrusiveValidationAttributes()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property2");
var expected =
$@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[password]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors());
// Act
var result = helper.PasswordFor(m => m.Property2, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
public static TheoryData PasswordFor_WithComplexExpressionsData
{
get
{
return new TheoryData<Expression<Func<PasswordModel, string>>, string>
{
{
model => model.Property3["key"],
@"<input data-val=""HtmlEncode[[true]]"" id=""HtmlEncode[[pre_Property3_key_]]"" name=""HtmlEncode[[pre.Property3[key]]]"" " +
@"type=""HtmlEncode[[password]]"" value=""HtmlEncode[[attr-value]]"" />"
},
{
model => model.Property4.Property5,
@"<input data-val=""HtmlEncode[[true]]"" id=""HtmlEncode[[pre_Property4_Property5]]"" name=""HtmlEncode[[pre.Property4.Property5]]"" " +
@"type=""HtmlEncode[[password]]"" value=""HtmlEncode[[attr-value]]"" />"
},
{
model => model.Property4.Property6[0],
@"<input data-val=""HtmlEncode[[true]]"" id=""HtmlEncode[[pre_Property4_Property6_0_]]"" " +
@"name=""HtmlEncode[[pre.Property4.Property6[0]]]"" type=""HtmlEncode[[password]]"" value=""HtmlEncode[[attr-value]]"" />"
}
};
}
}
[Theory]
[MemberData(nameof(PasswordFor_WithComplexExpressionsData))]
public void PasswordFor_WithComplexExpressionsAndFieldPrefix_UsesAttributeValueIfSpecified(
Expression<Func<PasswordModel, string>> expression,
string expected)
{
// Arrange
var viewData = GetViewDataWithModelStateAndModelAndViewDataValues();
viewData.ModelState.SetModelValue("pre.Property3[key]", "Property3Val", "Property3Val");
viewData.ModelState.SetModelValue("pre.Property4.Property5", "Property5Val", "Property5Val");
viewData.ModelState.SetModelValue("pre.Property4.Property6[0]", "Property6Val", "Property6Val");
viewData["pre.Property3[key]"] = "vdd-value1";
viewData["pre.Property4.Property5"] = "vdd-value2";
viewData["pre.Property4.Property6[0]"] = "vdd-value3";
viewData.Model.Property3["key"] = "prop-value1";
viewData.Model.Property4.Property5 = "prop-value2";
viewData.Model.Property4.Property6.Add("prop-value3");
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
viewData.TemplateInfo.HtmlFieldPrefix = "pre";
var attributes = new { data_val = "true", value = "attr-value" };
// Act
var result = helper.PasswordFor(expression, attributes);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void Password_UsesSpecifiedExpressionForNames_IgnoresExpressionValue()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var passwordResult = helper.Password("Property1");
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[password]]\" />",
HtmlContentUtilities.HtmlContentToString(passwordResult));
}
[Fact]
public void PasswordFor_UsesSpecifiedExpressionForNames_IgnoresExpressionValue()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var passwordForResult = helper.PasswordFor(m => m.Property1);
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[password]]\" />",
HtmlContentUtilities.HtmlContentToString(passwordForResult));
}
[Fact]
public void Password_UsesSpecifiedValue()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var passwordResult = helper.Password("Property1", value: "myvalue");
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[password]]\" value=\"HtmlEncode[[myvalue]]\" />",
HtmlContentUtilities.HtmlContentToString(passwordResult));
}
[Fact]
public void PasswordFor_GeneratesPlaceholderAttribute_WhenDisplayAttributePromptIsSet()
{
// Arrange
var expected = @"<input id=""HtmlEncode[[Property7]]"" name=""HtmlEncode[[Property7]]"" placeholder=""HtmlEncode[[placeholder]]"" type=""HtmlEncode[[password]]"" />";
var model = new PasswordModel();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model);
// Act
var result = helper.PasswordFor(m => m.Property7, htmlAttributes: null);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
private static ViewDataDictionary<PasswordModel> GetViewDataWithNullModelAndNonEmptyViewData()
{
return new ViewDataDictionary<PasswordModel>(new EmptyModelMetadataProvider())
{
["Property1"] = "view-data-val",
};
}
private static ViewDataDictionary<PasswordModel> GetViewDataWithModelStateAndModelAndViewDataValues()
{
var viewData = GetViewDataWithNullModelAndNonEmptyViewData();
viewData.Model = new PasswordModel();
viewData.ModelState.SetModelValue("Property1", "ModelStateValue", "ModelStateValue");
return viewData;
}
private static ViewDataDictionary<PasswordModel> GetViewDataWithErrors()
{
var viewData = GetViewDataWithModelStateAndModelAndViewDataValues();
viewData.ModelState.AddModelError("Property1", "error 1");
viewData.ModelState.AddModelError("Property1", "error 2");
return viewData;
}
public static TheoryData PasswordFor_IgnoresExpressionValueForComplexExpressionsData
{
get
{
return new TheoryData<Expression<Func<PasswordModel, string>>, string>
{
{
model => model.Property3["key"],
@"<input id=""HtmlEncode[[pre_Property3_key_]]"" name=""HtmlEncode[[pre.Property3[key]]]"" " +
@"type=""HtmlEncode[[password]]"" />"
},
{
model => model.Property4.Property5,
@"<input id=""HtmlEncode[[pre_Property4_Property5]]"" name=""HtmlEncode[[pre.Property4.Property5]]"" " +
@"type=""HtmlEncode[[password]]"" />"
},
{
model => model.Property4.Property6[0],
@"<input id=""HtmlEncode[[pre_Property4_Property6_0_]]"" " +
@"name=""HtmlEncode[[pre.Property4.Property6[0]]]"" type=""HtmlEncode[[password]]"" />"
}
};
}
}
[Theory]
[MemberData(nameof(PasswordFor_IgnoresExpressionValueForComplexExpressionsData))]
public void PasswordFor_ComplexExpressions_IgnoresValueFromViewDataModelStateAndModel(
Expression<Func<PasswordModel, string>> expression,
string expected)
{
// Arrange
var model = new PasswordModel();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model);
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "pre";
helper.ViewData.ModelState.SetModelValue("pre.Property3[key]", "MProp3Val", "MProp3Val");
helper.ViewData.ModelState.SetModelValue("pre.Property4.Property5", "MProp5Val", "MProp5Val");
helper.ViewData.ModelState.SetModelValue("pre.Property4.Property6[0]", "MProp6Val", "MProp6Val");
helper.ViewData["pre.Property3[key]"] = "VDProp3Val";
helper.ViewData["pre.Property4.Property5"] = "VDProp5Val";
helper.ViewData["pre.Property4.Property6"] = "VDProp6Val";
helper.ViewData.Model.Property3["key"] = "Prop3Val";
helper.ViewData.Model.Property4.Property5 = "Prop5Val";
helper.ViewData.Model.Property4.Property6.Add("Prop6Val");
// Act
var result = helper.PasswordFor(expression);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
public class PasswordModel
{
public string Property1 { get; set; }
[Required]
public string Property2 { get; set; }
public Dictionary<string, string> Property3 { get; } = new Dictionary<string, string>();
public NestedClass Property4 { get; } = new NestedClass();
[Display(Prompt = "placeholder")]
public string Property7 { get; set; }
}
public class NestedClass
{
public string Property5 { get; set; }
public List<string> Property6 { get; } = new List<string>();
}
private class TestModel
{
public string Property1 { get; set; }
}
}
}
| |
//
// Preferences.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Stephane Delcroix <stephane@delcroix.org>
// Larry Ewing <lewing@novell.com>
//
// Copyright (C) 2005-2010 Novell, Inc.
// Copyright (C) 2007, 2010 Ruben Vermeersch
// Copyright (C) 2006-2009 Stephane Delcroix
// Copyright (C) 2005-2006 Larry Ewing
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using FSpot.Core;
using FSpot.Platform;
using Hyena;
namespace FSpot
{
public class Preferences
{
public const string APP_FSPOT = "/apps/f-spot/";
public const string APP_FSPOT_EXPORT = APP_FSPOT + "export/";
public const string APP_FSPOT_EXPORT_TOKENS = APP_FSPOT_EXPORT + "tokens/";
public const string GTK_RC = APP_FSPOT + "ui/gtkrc";
public const string MAIN_WINDOW_MAXIMIZED = APP_FSPOT + "ui/maximized";
public const string MAIN_WINDOW_X = APP_FSPOT + "ui/main_window_x";
public const string MAIN_WINDOW_Y = APP_FSPOT + "ui/main_window_y";
public const string MAIN_WINDOW_WIDTH = APP_FSPOT + "ui/main_window_width";
public const string MAIN_WINDOW_HEIGHT = APP_FSPOT + "ui/main_window_height";
public const string IMPORT_WINDOW_WIDTH = APP_FSPOT + "ui/import_window_width";
public const string IMPORT_WINDOW_HEIGHT = APP_FSPOT + "ui/import_window_height";
public const string IMPORT_WINDOW_PANE_POSITION = APP_FSPOT + "ui/import_window_pane_position";
public const string IMPORT_COPY_FILES = "/apps/f-spot/import/copy_files";
public const string IMPORT_INCLUDE_SUBFOLDERS = "/apps/f-spot/import/include_subfolders";
public const string IMPORT_CHECK_DUPLICATES = "/apps/f-spot/import/check_duplicates";
public const string IMPORT_REMOVE_ORIGINALS = "/apps/f-spot/import/remove_originals";
public const string VIEWER_WIDTH = APP_FSPOT + "ui/viewer_width";
public const string VIEWER_HEIGHT = APP_FSPOT + "ui/viewer_height";
public const string VIEWER_MAXIMIZED = APP_FSPOT + "ui/viewer_maximized";
public const string VIEWER_SHOW_TOOLBAR = APP_FSPOT + "ui/viewer_show_toolbar";
public const string VIEWER_SHOW_FILENAMES = APP_FSPOT + "ui/viewer_show_filenames";
public const string VIEWER_INTERPOLATION = APP_FSPOT + "viewer/interpolation";
public const string VIEWER_TRANS_COLOR = APP_FSPOT + "viewer/trans_color";
public const string VIEWER_TRANSPARENCY = APP_FSPOT + "viewer/transparency";
public const string CUSTOM_CROP_RATIOS = APP_FSPOT + "viewer/custom_crop_ratios";
public const string COLOR_MANAGEMENT_DISPLAY_PROFILE = APP_FSPOT + "ui/color_management_display_profile";
public const string COLOR_MANAGEMENT_OUTPUT_PROFILE = APP_FSPOT + "ui/color_management_output_profile";
public const string SHOW_TOOLBAR = APP_FSPOT + "ui/show_toolbar";
public const string SHOW_SIDEBAR = APP_FSPOT + "ui/show_sidebar";
public const string SHOW_TIMELINE = APP_FSPOT + "ui/show_timeline";
public const string SHOW_FILMSTRIP = APP_FSPOT + "ui/show_filmstrip";
public const string FILMSTRIP_ORIENTATION = APP_FSPOT + "ui/filmstrip_orientation";
public const string SHOW_TAGS = APP_FSPOT + "ui/show_tags";
public const string SHOW_DATES = APP_FSPOT + "ui/show_dates";
public const string EXPANDED_TAGS = APP_FSPOT + "ui/expanded_tags";
public const string SHOW_RATINGS = APP_FSPOT + "ui/show_ratings";
public const string TAG_ICON_SIZE = APP_FSPOT + "ui/tag_icon_size";
public const string TAG_ICON_AUTOMATIC = APP_FSPOT + "ui/tag_icon_automatic";
public const string GLASS_POSITION = APP_FSPOT + "ui/glass_position";
public const string GROUP_ADAPTOR_ORDER_ASC = APP_FSPOT + "ui/group_adaptor_sort_asc";
public const string SIDEBAR_POSITION = APP_FSPOT + "ui/sidebar_size";
public const string ZOOM = APP_FSPOT + "ui/zoom";
public const string EXPORT_EMAIL_SIZE = APP_FSPOT + "export/email/size";
public const string EXPORT_EMAIL_ROTATE = APP_FSPOT + "export/email/auto_rotate";
public const string IMPORT_GUI_ROLL_HISTORY = APP_FSPOT + "import/gui_roll_history";
public const string SCREENSAVER_TAG = APP_FSPOT + "screensaver/tag_id";
public const string SCREENSAVER_DELAY = APP_FSPOT + "screensaver/delay";
public const string STORAGE_PATH = APP_FSPOT + "import/storage_path";
public const string METADATA_EMBED_IN_IMAGE = APP_FSPOT + "metadata/embed_in_image";
public const string METADATA_ALWAYS_USE_SIDECAR = APP_FSPOT + "metadata/always_use_sidecar";
public const string EDIT_REDEYE_THRESHOLD = APP_FSPOT + "edit/redeye_threshold";
public const string EDIT_CREATE_XCF_VERSION = APP_FSPOT + "edit/create_xcf";
public const string GNOME_MAILTO = "/desktop/gnome/url-handlers/mailto/";
public const string GNOME_MAILTO_COMMAND = GNOME_MAILTO + "command";
public const string GNOME_MAILTO_ENABLED = GNOME_MAILTO + "enabled";
public const string GSD_THUMBS_MAX_AGE = "/desktop/gnome/thumbnail_cache/maximum_age";
public const string GSD_THUMBS_MAX_SIZE = "/desktop/gnome/thumbnail_cache/maximum_size";
private static PreferenceBackend backend;
private static EventHandler<NotifyEventArgs> changed_handler;
private static PreferenceBackend Backend {
get {
if (backend == null) {
backend = new PreferenceBackend ();
changed_handler = new EventHandler<NotifyEventArgs> (OnSettingChanged);
backend.AddNotify (APP_FSPOT, changed_handler);
backend.AddNotify (GNOME_MAILTO, changed_handler);
}
return backend;
}
}
private static Dictionary<string, object> cache = new Dictionary<string, object>();
static object GetDefault (string key)
{
switch (key) {
case MAIN_WINDOW_X:
case MAIN_WINDOW_Y:
case MAIN_WINDOW_HEIGHT:
case MAIN_WINDOW_WIDTH:
case IMPORT_WINDOW_HEIGHT:
case IMPORT_WINDOW_WIDTH:
case IMPORT_WINDOW_PANE_POSITION:
case FILMSTRIP_ORIENTATION:
return 0;
case METADATA_EMBED_IN_IMAGE:
case METADATA_ALWAYS_USE_SIDECAR:
case MAIN_WINDOW_MAXIMIZED:
case GROUP_ADAPTOR_ORDER_ASC:
case IMPORT_REMOVE_ORIGINALS:
return false;
case GLASS_POSITION:
return null;
case SHOW_TOOLBAR:
case SHOW_SIDEBAR:
case SHOW_TIMELINE:
case SHOW_FILMSTRIP:
case SHOW_TAGS:
case SHOW_DATES:
case SHOW_RATINGS:
case VIEWER_SHOW_FILENAMES:
return true;
case TAG_ICON_SIZE:
return (int) Tag.IconSize.Medium;
case TAG_ICON_AUTOMATIC:
return true;
case SIDEBAR_POSITION:
return 130;
case ZOOM:
return null;
case IMPORT_GUI_ROLL_HISTORY:
return 10;
case SCREENSAVER_TAG:
return 1;
case SCREENSAVER_DELAY:
return 4.0;
case STORAGE_PATH:
return System.IO.Path.Combine (Global.HomeDirectory, Catalog.GetString("Photos"));
case EXPORT_EMAIL_SIZE:
return 3; // medium size 640px
case EXPORT_EMAIL_ROTATE:
case VIEWER_INTERPOLATION:
return true;
case VIEWER_TRANSPARENCY:
return "NONE";
case VIEWER_TRANS_COLOR:
return "#000000";
case EDIT_REDEYE_THRESHOLD:
return -15;
case GTK_RC:
case COLOR_MANAGEMENT_DISPLAY_PROFILE:
case COLOR_MANAGEMENT_OUTPUT_PROFILE:
return String.Empty;
case IMPORT_CHECK_DUPLICATES:
case IMPORT_COPY_FILES:
case IMPORT_INCLUDE_SUBFOLDERS:
return true;
default:
return null;
}
}
//return true if the key exists in the backend
public static bool TryGet<T> (string key, out T value)
{
lock (cache) {
value = default (T);
object o;
if (cache.TryGetValue (key, out o)) {
value = (T)o;
return true;
}
try {
value = (T) Backend.Get (key);
} catch { //catching NoSuchKeyException
return false;
}
cache.Add (key, value);
return true;
}
}
public static T Get<T> (string key)
{
T val;
if (TryGet (key, out val))
return val;
try {
return (T) GetDefault (key);
} catch { //catching InvalidCastException
return default (T);
}
}
public static void Set (string key, object value)
{
lock (cache) {
try {
cache [key] = value;
Backend.Set (key, value);
} catch (Exception e){
Log.Exception ("Unable to set this :"+key, e);
}
}
}
public static event EventHandler<NotifyEventArgs> SettingChanged;
static void OnSettingChanged (object sender, NotifyEventArgs args)
{
lock (cache) {
if (cache.ContainsKey (args.Key)) {
cache [args.Key] = args.Value;
}
}
if (SettingChanged != null)
SettingChanged (sender, args);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Runtime.ExceptionServices;
using Microsoft.DebugEngineHost;
using MICore;
namespace Microsoft.MIDebugEngine
{
public delegate void Operation();
public delegate Task AsyncOperation();
public delegate Task AsyncProgressOperation(HostWaitLoop waitLoop);
/// <summary>
/// Worker thread used to process MI Debugger output and used to process AD7 commands
/// </summary>
internal class WorkerThread : IDisposable
{
private readonly AutoResetEvent _opSet;
private readonly ManualResetEvent _runningOpCompleteEvent; // fired when either m_syncOp finishes, or the kick off of m_async
private readonly Queue<Operation> _postedOperations; // queue of fire-and-forget operations
public event EventHandler<Exception> PostedOperationErrorEvent;
private class OperationDescriptor
{
/// <summary>
/// Delegate that was added via 'RunOperation'. Is of type 'Operation' or 'AsyncOperation'
/// </summary>
public readonly Delegate Target;
public ExceptionDispatchInfo ExceptionDispatchInfo;
public Task Task;
private bool _isStarted;
private bool _isComplete;
public OperationDescriptor(Delegate target)
{
this.Target = target;
}
public bool IsComplete
{
get { return _isComplete; }
}
public void MarkComplete()
{
Debug.Assert(_isStarted == true, "MarkComplete called before MarkStarted?");
Debug.Assert(_isComplete == false, "MarkComplete called more than once??");
_isComplete = true;
}
public bool IsStarted
{
get { return _isStarted; }
}
public void MarkStarted()
{
Debug.Assert(_isStarted == false, "MarkStarted called more than once??");
_isStarted = true;
}
}
private OperationDescriptor _runningOp;
private Thread _thread;
private volatile bool _isClosed;
public Logger Logger { get; private set; }
public WorkerThread(Logger logger)
{
Logger = logger;
_opSet = new AutoResetEvent(false);
_runningOpCompleteEvent = new ManualResetEvent(true);
_postedOperations = new Queue<Operation>();
_thread = new Thread(new ThreadStart(ThreadFunc));
_thread.Name = "MIDebugger.PollThread";
_thread.Start();
}
/// <summary>
/// Send an operation to the worker thread, and block for it to finish. This is used for implementing
/// most AD7 interfaces. This will wait for other 'RunOperation' calls to finish before starting.
/// </summary>
/// <param name="op">Delegate for the code to run on the worker thread</param>
public void RunOperation(Operation op)
{
if (op == null)
throw new ArgumentNullException();
SetOperationInternal(op);
}
/// <summary>
/// Send an operation to the worker thread, and block for it to finish (task returns complete). This is used for implementing
/// most AD7 interfaces. This will wait for other 'RunOperation' calls to finish before starting.
/// </summary>
/// <param name="op">Delegate for the code to run on the worker thread. This returns a Task that we wait on.</param>
public void RunOperation(AsyncOperation op)
{
if (op == null)
throw new ArgumentNullException();
SetOperationInternal(op);
}
public void RunOperation(string text, CancellationTokenSource canTokenSource, AsyncProgressOperation op)
{
if (op == null)
throw new ArgumentNullException();
SetOperationInternalWithProgress(op, text, canTokenSource);
}
public void Close()
{
if (_isClosed)
return;
// block out posting any more operations
lock (_postedOperations)
{
if (_isClosed)
return;
_isClosed = true;
// Wait for any pending running operations to finish
while (true)
{
_runningOpCompleteEvent.WaitOne();
lock (_runningOpCompleteEvent)
{
if (_runningOp == null)
{
_opSet.Set();
break;
}
}
}
}
}
internal void SetOperationInternal(Delegate op)
{
// If this is called on the Worker thread it will deadlock
Debug.Assert(!IsPollThread());
while (true)
{
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
_runningOpCompleteEvent.WaitOne();
if (TrySetOperationInternal(op))
{
return;
}
}
}
internal void SetOperationInternalWithProgress(AsyncProgressOperation op, string text, CancellationTokenSource canTokenSource)
{
// If this is called on the Worker thread it will deadlock
Debug.Assert(!IsPollThread());
while (true)
{
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
_runningOpCompleteEvent.WaitOne();
if (TrySetOperationInternalWithProgress(op, text, canTokenSource))
{
return;
}
}
}
public void PostOperation(Operation op)
{
if (op == null)
throw new ArgumentNullException();
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
lock (_postedOperations)
{
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
_postedOperations.Enqueue(op);
if (_postedOperations.Count == 1)
{
_opSet.Set();
}
}
}
private bool TrySetOperationInternal(Delegate op)
{
lock (_runningOpCompleteEvent)
{
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
if (_runningOp == null)
{
_runningOpCompleteEvent.Reset();
OperationDescriptor runningOp = new OperationDescriptor(op);
_runningOp = runningOp;
_opSet.Set();
_runningOpCompleteEvent.WaitOne();
Debug.Assert(runningOp.IsComplete, "Why isn't the running op complete?");
if (runningOp.ExceptionDispatchInfo != null)
{
runningOp.ExceptionDispatchInfo.Throw();
}
return true;
}
}
return false;
}
private bool TrySetOperationInternalWithProgress(AsyncProgressOperation op, string text, CancellationTokenSource canTokenSource)
{
var waitLoop = new HostWaitLoop(text);
lock (_runningOpCompleteEvent)
{
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
if (_runningOp == null)
{
_runningOpCompleteEvent.Reset();
OperationDescriptor runningOp = new OperationDescriptor(new AsyncOperation(() => { return op(waitLoop); }));
_runningOp = runningOp;
_opSet.Set();
waitLoop.Wait(_runningOpCompleteEvent, canTokenSource);
Debug.Assert(runningOp.IsComplete, "Why isn't the running op complete?");
if (runningOp.ExceptionDispatchInfo != null)
{
runningOp.ExceptionDispatchInfo.Throw();
}
return true;
}
}
return false;
}
// Thread routine for the poll loop. It handles calls coming in from the debug engine as well as polling for debug events.
private void ThreadFunc()
{
while (!_isClosed)
{
// Wait for an operation to be set
_opSet.WaitOne();
// Run until we go through a loop where there was nothing to do
bool ranOperation;
do
{
ranOperation = false;
OperationDescriptor runningOp = _runningOp;
if (runningOp != null && !runningOp.IsStarted)
{
runningOp.MarkStarted();
ranOperation = true;
bool completeAsync = false;
Operation syncOp = runningOp.Target as Operation;
if (syncOp != null)
{
try
{
syncOp();
}
catch (Exception opException) when (ExceptionHelper.BeforeCatch(opException, Logger, reportOnlyCorrupting: true))
{
runningOp.ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(opException);
}
}
else
{
AsyncOperation asyncOp = (AsyncOperation)runningOp.Target;
try
{
runningOp.Task = asyncOp();
}
catch (Exception opException) when (ExceptionHelper.BeforeCatch(opException, Logger, reportOnlyCorrupting: true))
{
runningOp.ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(opException);
}
if (runningOp.Task != null)
{
runningOp.Task.ContinueWith(OnAsyncRunningOpComplete, TaskContinuationOptions.ExecuteSynchronously);
completeAsync = true;
}
}
if (!completeAsync)
{
runningOp.MarkComplete();
Debug.Assert(_runningOp == runningOp, "How did m_runningOp change?");
_runningOp = null;
_runningOpCompleteEvent.Set();
}
}
Operation postedOperation = null;
lock (_postedOperations)
{
if (_postedOperations.Count > 0)
{
postedOperation = _postedOperations.Dequeue();
}
}
if (postedOperation != null)
{
ranOperation = true;
try
{
postedOperation();
}
catch (Exception e) when (ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: false))
{
if (PostedOperationErrorEvent != null)
{
PostedOperationErrorEvent(this, e);
}
}
}
}
while (ranOperation);
}
}
internal void OnAsyncRunningOpComplete(Task t)
{
Debug.Assert(_runningOp != null, "How did m_runningOp get cleared?");
Debug.Assert(t == _runningOp.Task, "Why is a different task completing?");
if (t.Exception != null)
{
if (t.Exception.InnerException != null)
{
_runningOp.ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(t.Exception.InnerException);
}
else
{
_runningOp.ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(t.Exception);
}
}
_runningOp.MarkComplete();
_runningOp = null;
_runningOpCompleteEvent.Set();
}
internal bool IsPollThread()
{
return Thread.CurrentThread == _thread;
}
void IDisposable.Dispose()
{
Close();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class OpenSsl
{
private static Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate;
#region internal methods
internal static SafeChannelBindingHandle QueryChannelBinding(SafeSslHandle context, ChannelBindingKind bindingType)
{
SafeChannelBindingHandle bindingHandle;
switch (bindingType)
{
case ChannelBindingKind.Endpoint:
bindingHandle = new SafeChannelBindingHandle(bindingType);
QueryEndPointChannelBinding(context, bindingHandle);
break;
case ChannelBindingKind.Unique:
bindingHandle = new SafeChannelBindingHandle(bindingType);
QueryUniqueChannelBinding(context, bindingHandle);
break;
default:
// Keeping parity with windows, we should return null in this case.
bindingHandle = null;
break;
}
return bindingHandle;
}
internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, bool isServer, bool remoteCertRequired)
{
SafeSslHandle context = null;
IntPtr method = GetSslMethod(protocols);
using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(method))
{
if (innerContext.IsInvalid)
{
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
Ssl.SetProtocolOptions(innerContext, protocols);
// The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet
// shutdown (we aren't negotating for session close to enable later session
// restoration).
//
// If you find yourself wanting to remove this line to enable bidirectional
// close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect().
// https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html
Ssl.SslCtxSetQuietShutdown(innerContext);
Ssl.SetEncryptionPolicy(innerContext, policy);
if (certHandle != null && certKeyHandle != null)
{
SetSslCertificate(innerContext, certHandle, certKeyHandle);
}
if (remoteCertRequired)
{
Debug.Assert(isServer, "isServer flag should be true");
Ssl.SslCtxSetVerify(innerContext,
s_verifyClientCertificate);
//update the client CA list
UpdateCAListFromRootStore(innerContext);
}
context = SafeSslHandle.Create(innerContext, isServer);
Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create");
if (context.IsInvalid)
{
context.Dispose();
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
}
return context;
}
internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount)
{
sendBuf = null;
sendCount = 0;
if ((recvBuf != null) && (recvCount > 0))
{
BioWrite(context.InputBio, recvBuf, recvOffset, recvCount);
}
int retVal = Ssl.SslDoHandshake(context);
if (retVal != 1)
{
Exception innerError;
Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError);
if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ))
{
throw new SslException(SR.Format(SR.net_ssl_handshake_failed_error, error), innerError);
}
}
sendCount = Crypto.BioCtrlPending(context.OutputBio);
if (sendCount > 0)
{
sendBuf = new byte[sendCount];
try
{
sendCount = BioRead(context.OutputBio, sendBuf, sendCount);
}
finally
{
if (sendCount <= 0)
{
sendBuf = null;
sendCount = 0;
}
}
}
bool stateOk = Ssl.IsSslStateOK(context);
if (stateOk)
{
context.MarkHandshakeCompleted();
}
return stateOk;
}
internal static int Encrypt(SafeSslHandle context, byte[] buffer, int offset, int count, out Ssl.SslErrorCode errorCode)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal;
unsafe
{
fixed (byte* fixedBuffer = buffer)
{
retVal = Ssl.SslWrite(context, fixedBuffer + offset, count);
}
}
if (retVal != count)
{
Exception innerError;
errorCode = GetSslError(context, retVal, out innerError);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
break;
default:
throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
}
}
else
{
int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);
Debug.Assert(buffer.Length >= capacityNeeded, "Input buffer of size " + buffer.Length +
" bytes is insufficient since encryption needs " + capacityNeeded + " bytes.");
retVal = BioRead(context.OutputBio, buffer, capacityNeeded);
}
return retVal;
}
internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int count, out Ssl.SslErrorCode errorCode)
{
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal = BioWrite(context.InputBio, outBuffer, 0, count);
if (retVal == count)
{
retVal = Ssl.SslRead(context, outBuffer, outBuffer.Length);
if (retVal > 0)
{
count = retVal;
}
}
if (retVal != count)
{
Exception innerError;
errorCode = GetSslError(context, retVal, out innerError);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
break;
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
// update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ
errorCode = Ssl.IsSslRenegotiatePending(context) ?
Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE :
Ssl.SslErrorCode.SSL_ERROR_WANT_READ;
break;
default:
throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError);
}
}
return retVal;
}
internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context)
{
return Ssl.SslGetPeerCertificate(context);
}
internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context)
{
return Ssl.SslGetPeerCertChain(context);
}
#endregion
#region private methods
private static void QueryEndPointChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
{
using (SafeX509Handle certSafeHandle = GetPeerCertificate(context))
{
if (certSafeHandle == null || certSafeHandle.IsInvalid)
{
throw CreateSslException(SR.net_ssl_invalid_certificate);
}
bool gotReference = false;
try
{
certSafeHandle.DangerousAddRef(ref gotReference);
using (X509Certificate2 cert = new X509Certificate2(certSafeHandle.DangerousGetHandle()))
using (HashAlgorithm hashAlgo = GetHashForChannelBinding(cert))
{
byte[] bindingHash = hashAlgo.ComputeHash(cert.RawData);
bindingHandle.SetCertHash(bindingHash);
}
}
finally
{
if (gotReference)
{
certSafeHandle.DangerousRelease();
}
}
}
}
private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
{
bool sessionReused = Ssl.SslSessionReused(context);
int certHashLength = context.IsServer ^ sessionReused ?
Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) :
Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length);
if (0 == certHashLength)
{
throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed);
}
bindingHandle.SetCertHashLength(certHashLength);
}
private static IntPtr GetSslMethod(SslProtocols protocols)
{
Debug.Assert(protocols != SslProtocols.None, "All protocols are disabled");
bool ssl2 = (protocols & SslProtocols.Ssl2) == SslProtocols.Ssl2;
bool ssl3 = (protocols & SslProtocols.Ssl3) == SslProtocols.Ssl3;
bool tls10 = (protocols & SslProtocols.Tls) == SslProtocols.Tls;
bool tls11 = (protocols & SslProtocols.Tls11) == SslProtocols.Tls11;
bool tls12 = (protocols & SslProtocols.Tls12) == SslProtocols.Tls12;
IntPtr method = Ssl.SslMethods.SSLv23_method; // default
string methodName = "SSLv23_method";
if (!ssl2)
{
if (!ssl3)
{
if (!tls11 && !tls12)
{
method = Ssl.SslMethods.TLSv1_method;
methodName = "TLSv1_method";
}
else if (!tls10 && !tls12)
{
method = Ssl.SslMethods.TLSv1_1_method;
methodName = "TLSv1_1_method";
}
else if (!tls10 && !tls11)
{
method = Ssl.SslMethods.TLSv1_2_method;
methodName = "TLSv1_2_method";
}
}
else if (!tls10 && !tls11 && !tls12)
{
method = Ssl.SslMethods.SSLv3_method;
methodName = "SSLv3_method";
}
}
if (IntPtr.Zero == method)
{
throw new SslException(SR.Format(SR.net_get_ssl_method_failed, methodName));
}
return method;
}
private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr)
{
// Full validation is handled after the handshake in VerifyCertificateProperties and the
// user callback. It's also up to those handlers to decide if a null certificate
// is appropriate. So just return success to tell OpenSSL that the cert is acceptable,
// we'll process it after the handshake finishes.
const int OpenSslSuccess = 1;
return OpenSslSuccess;
}
private static void UpdateCAListFromRootStore(SafeSslContextHandle context)
{
using (SafeX509NameStackHandle nameStack = Crypto.NewX509NameStack())
{
//maintaining the HashSet of Certificate's issuer name to keep track of duplicates
HashSet<string> issuerNameHashSet = new HashSet<string>();
//Enumerate Certificates from LocalMachine and CurrentUser root store
AddX509Names(nameStack, StoreLocation.LocalMachine, issuerNameHashSet);
AddX509Names(nameStack, StoreLocation.CurrentUser, issuerNameHashSet);
Ssl.SslCtxSetClientCAList(context, nameStack);
// The handle ownership has been transferred into the CTX.
nameStack.SetHandleAsInvalid();
}
}
private static void AddX509Names(SafeX509NameStackHandle nameStack, StoreLocation storeLocation, HashSet<string> issuerNameHashSet)
{
using (var store = new X509Store(StoreName.Root, storeLocation))
{
store.Open(OpenFlags.ReadOnly);
foreach (var certificate in store.Certificates)
{
//Check if issuer name is already present
//Avoiding duplicate names
if (!issuerNameHashSet.Add(certificate.Issuer))
{
continue;
}
using (SafeX509Handle certHandle = Crypto.X509Duplicate(certificate.Handle))
{
using (SafeX509NameHandle nameHandle = Crypto.DuplicateX509Name(Crypto.X509GetIssuerName(certHandle)))
{
if (Crypto.PushX509NameStackField(nameStack, nameHandle))
{
// The handle ownership has been transferred into the STACK_OF(X509_NAME).
nameHandle.SetHandleAsInvalid();
}
else
{
throw new CryptographicException(SR.net_ssl_x509Name_push_failed_error);
}
}
}
}
}
}
private static int BioRead(SafeBioHandle bio, byte[] buffer, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= count);
int bytes = Crypto.BioRead(bio, buffer, count);
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_read_bio_failed_error);
}
return bytes;
}
private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
int bytes;
unsafe
{
fixed (byte* bufPtr = buffer)
{
bytes = Ssl.BioWrite(bio, bufPtr + offset, count);
}
}
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_write_bio_failed_error);
}
return bytes;
}
private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception innerError)
{
ErrorInfo lastErrno = Sys.GetLastErrorInfo(); // cache it before we make more P/Invoke calls, just in case we need it
Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result);
switch (retVal)
{
case Ssl.SslErrorCode.SSL_ERROR_SYSCALL:
// Some I/O error occurred
innerError =
Crypto.ErrPeekError() != 0 ? Crypto.CreateOpenSslCryptographicException() : // crypto error queue not empty
result == 0 ? new EndOfStreamException() : // end of file that violates protocol
result == -1 && lastErrno.Error != Error.SUCCESS ? new IOException(lastErrno.GetErrorMessage(), lastErrno.RawErrno) : // underlying I/O error
null; // no additional info available
break;
case Ssl.SslErrorCode.SSL_ERROR_SSL:
// OpenSSL failure occurred. The error queue contains more details.
innerError = Interop.Crypto.CreateOpenSslCryptographicException();
break;
default:
// No additional info available.
innerError = null;
break;
}
return retVal;
}
private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr)
{
Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid");
Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid");
int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_cert_failed);
}
retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_private_key_failed);
}
//check private key
retVal = Ssl.SslCtxCheckPrivateKey(contextPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_check_private_key_failed);
}
}
internal static SslException CreateSslException(string message)
{
ulong errorVal = Crypto.ErrGetError();
string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal)));
return new SslException(msg, (int)errorVal);
}
#endregion
#region Internal class
internal sealed class SslException : Exception
{
public SslException(string inputMessage)
: base(inputMessage)
{
}
public SslException(string inputMessage, Exception ex)
: base(inputMessage, ex)
{
}
public SslException(string inputMessage, int error)
: this(inputMessage)
{
HResult = error;
}
public SslException(int error)
: this(SR.Format(SR.net_generic_operation_failed, error))
{
HResult = error;
}
}
#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.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableSortedSetTest : ImmutableSetTest
{
private enum Operation
{
Add,
Union,
Remove,
Except,
Last,
}
protected override bool IncludesGetHashCodeDerivative
{
get { return false; }
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedSet<int>();
var actual = ImmutableSortedSet<int>.Empty;
int seed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Debug.WriteLine("Adding \"{0}\" to the set.", value);
expected.Add(value);
actual = actual.Add(value);
break;
case Operation.Union:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Debug.WriteLine("Adding {0} elements to the set.", inputLength);
expected.UnionWith(values);
actual = actual.Union(values);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
int element = expected.Skip(position).First();
Debug.WriteLine("Removing element \"{0}\" from the set.", element);
Assert.True(expected.Remove(element));
actual = actual.Remove(element);
}
break;
case Operation.Except:
var elements = expected.Where(el => random.Next(2) == 0).ToArray();
Debug.WriteLine("Removing {0} elements from the set.", elements.Length);
expected.ExceptWith(elements);
actual = actual.Except(elements);
break;
}
Assert.Equal<int>(expected.ToList(), actual.ToList());
}
}
[Fact]
public void EmptyTest()
{
this.EmptyTestHelper(Empty<int>(), 5, null);
this.EmptyTestHelper(Empty<string>().ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.Ordinal),
true,
new[] { "apple", "APPLE" },
new[] { "APPLE", "apple" });
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase),
true,
new[] { "apple", "APPLE" },
new[] { "apple" });
}
[Fact]
public void ChangeSortComparer()
{
var ordinalSet = ImmutableSortedSet<string>.Empty
.WithComparer(StringComparer.Ordinal)
.Add("apple")
.Add("APPLE");
Assert.Equal(2, ordinalSet.Count); // claimed count
Assert.False(ordinalSet.Contains("aPpLe"));
var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, ignoreCaseSet.Count);
Assert.True(ignoreCaseSet.Contains("aPpLe"));
}
[Fact]
public void ToUnorderedTest()
{
var result = ImmutableSortedSet<int>.Empty.Add(3).ToImmutableHashSet();
Assert.True(result.Contains(3));
}
[Fact]
public void ToImmutableSortedSetFromArrayTest()
{
var set = new[] { 1, 2, 2 }.ToImmutableSortedSet();
Assert.Same(Comparer<int>.Default, set.KeyComparer);
Assert.Equal(2, set.Count);
}
[Theory]
[InlineData(new int[] { }, new int[] { })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })]
[InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })]
public void ToImmutableSortedSetFromEnumerableTest(int[] input, int[] expectedOutput)
{
IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces
var set = enumerableInput.ToImmutableSortedSet();
Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray());
}
[Theory]
[InlineData(new int[] { }, new int[] { 1 })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })]
[InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })]
public void UnionWithEnumerableTest(int[] input, int[] expectedOutput)
{
IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces
var set = ImmutableSortedSet.Create(1).Union(enumerableInput);
Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray());
}
[Fact]
public void IndexOfTest()
{
var set = ImmutableSortedSet<int>.Empty;
Assert.Equal(~0, set.IndexOf(5));
set = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
Assert.Equal(0, set.IndexOf(10));
Assert.Equal(1, set.IndexOf(20));
Assert.Equal(4, set.IndexOf(50));
Assert.Equal(8, set.IndexOf(90));
Assert.Equal(9, set.IndexOf(100));
Assert.Equal(~0, set.IndexOf(5));
Assert.Equal(~1, set.IndexOf(15));
Assert.Equal(~2, set.IndexOf(25));
Assert.Equal(~5, set.IndexOf(55));
Assert.Equal(~9, set.IndexOf(95));
Assert.Equal(~10, set.IndexOf(105));
}
[Fact]
public void IndexGetTest()
{
var set = ImmutableSortedSet<int>.Empty
.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
int i = 0;
foreach (var item in set)
{
AssertAreSame(item, set[i++]);
}
Assert.Throws<ArgumentOutOfRangeException>("index", () => set[-1]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => set[set.Count]);
}
[Fact]
public void ReverseTest()
{
var range = Enumerable.Range(1, 10);
var set = ImmutableSortedSet<int>.Empty.Union(range);
var expected = range.Reverse().ToList();
var actual = set.Reverse().ToList();
Assert.Equal<int>(expected, actual);
}
[Fact]
public void MaxTest()
{
Assert.Equal(5, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Max);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Max);
}
[Fact]
public void MinTest()
{
Assert.Equal(1, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Min);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Min);
}
[Fact]
public void InitialBulkAdd()
{
Assert.Equal(1, Empty<int>().Union(new[] { 1, 1 }).Count);
Assert.Equal(2, Empty<int>().Union(new[] { 1, 2 }).Count);
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> set = ImmutableSortedSet.Create<string>();
Assert.Throws<NotSupportedException>(() => set.Add("a"));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove("a"));
Assert.True(set.IsReadOnly);
}
[Fact]
public void IListOfTMethods()
{
IList<string> set = ImmutableSortedSet.Create<string>("b");
Assert.Throws<NotSupportedException>(() => set.Insert(0, "a"));
Assert.Throws<NotSupportedException>(() => set.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => set[0] = "a");
Assert.Equal("b", set[0]);
Assert.True(set.IsReadOnly);
}
[Fact]
public void UnionOptimizationsTest()
{
var set = ImmutableSortedSet.Create(1, 2, 3);
var builder = set.ToBuilder();
Assert.Same(set, ImmutableSortedSet.Create<int>().Union(builder));
Assert.Same(set, set.Union(ImmutableSortedSet.Create<int>()));
var smallSet = ImmutableSortedSet.Create(1);
var unionSet = smallSet.Union(set);
Assert.Same(set, unionSet); // adding a larger set to a smaller set is reversed, and then the smaller in this case has nothing unique
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
var set = ImmutableSortedSet.Create<string>();
Assert.Equal(0, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create<string>(comparer);
Assert.Equal(0, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a");
Assert.Equal(1, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a");
Assert.Equal(1, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a", "b");
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a", "b");
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
}
[Fact]
public void IListMethods()
{
IList list = ImmutableSortedSet.Create("a", "b");
Assert.True(list.Contains("a"));
Assert.Equal("a", list[0]);
Assert.Equal("b", list[1]);
Assert.Equal(0, list.IndexOf("a"));
Assert.Equal(1, list.IndexOf("b"));
Assert.Throws<NotSupportedException>(() => list.Add("b"));
Assert.Throws<NotSupportedException>(() => list[3] = "c");
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, "b"));
Assert.Throws<NotSupportedException>(() => list.Remove("a"));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.True(list.IsFixedSize);
Assert.True(list.IsReadOnly);
}
[Fact]
public void TryGetValueTest()
{
this.TryGetValueTestHelper(ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedSet.Create<int>();
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedSet.Create<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableSortedSet.Create<string>("1", "2", "3"));
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSortedSet.Create<object>(), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
}
[Fact]
public void SymmetricExceptWithComparerTests()
{
var set = ImmutableSortedSet.Create<string>("a").WithComparer(StringComparer.OrdinalIgnoreCase);
var otherCollection = new[] {"A"};
var expectedSet = new SortedSet<string>(set, set.KeyComparer);
expectedSet.SymmetricExceptWith(otherCollection);
var actualSet = set.SymmetricExcept(otherCollection);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
}
protected override IImmutableSet<T> Empty<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected ImmutableSortedSet<T> EmptyTyped<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected override ISet<T> EmptyMutable<T>()
{
return new SortedSet<T>();
}
internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
{
return ((ImmutableSortedSet<T>)set).Root;
}
/// <summary>
/// Tests various aspects of a sorted set.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
/// <param name="value">A value that could be placed in the set.</param>
/// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IComparer<T> comparer)
{
Contract.Requires(emptySet != null);
this.EmptyTestHelper(emptySet);
Assert.Same(emptySet, emptySet.ToImmutableSortedSet(comparer));
Assert.Same(comparer ?? Comparer<T>.Default, ((ISortKeyCollection<T>)emptySet).KeyComparer);
var reemptied = emptySet.Add(value).Clear();
Assert.Same(reemptied, reemptied.ToImmutableSortedSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the 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.Net;
using OpenMetaverse;
namespace OpenSim.Region.ClientStack.LindenUDP
{
/// <summary>
/// Special collection that is optimized for tracking unacknowledged packets
/// </summary>
public sealed class UnackedPacketCollection
{
/// <summary>
/// Holds information about a pending acknowledgement
/// </summary>
private struct PendingAck
{
/// <summary>Sequence number of the packet to remove</summary>
public uint SequenceNumber;
/// <summary>Environment.TickCount value when the remove was queued.
/// This is used to update round-trip times for packets</summary>
public int RemoveTime;
/// <summary>Whether or not this acknowledgement was attached to a
/// resent packet. If so, round-trip time will not be calculated</summary>
public bool FromResend;
public PendingAck(uint sequenceNumber, int currentTime, bool fromResend)
{
SequenceNumber = sequenceNumber;
RemoveTime = currentTime;
FromResend = fromResend;
}
}
/// <summary>Holds the actual unacked packet data, sorted by sequence number</summary>
private SortedDictionary<uint, OutgoingPacket> m_packets = new SortedDictionary<uint, OutgoingPacket>();
/// <summary>Holds packets that need to be added to the unacknowledged list</summary>
private OpenSim.Framework.LocklessQueue<OutgoingPacket> m_pendingAdds = new OpenSim.Framework.LocklessQueue<OutgoingPacket>();
/// <summary>Holds information about pending acknowledgements</summary>
private OpenSim.Framework.LocklessQueue<PendingAck> m_pendingRemoves = new OpenSim.Framework.LocklessQueue<PendingAck>();
private OpenMetaverse.Interfaces.IByteBufferPool m_bufferPool;
/// <summary>
/// The highest sequence number that has been acked
/// </summary>
private uint m_highestAck = 0;
/// <summary>
/// The number of acks with a greater sequence number than a suspect packet
/// that we receive before we activate fast retransmit
/// </summary>
private const uint FAST_RETRANSMIT_SEQUENCE_THRESHOLD = 3;
/// <summary>
/// The reason packets are marked as requiring resend
/// </summary>
[Flags]
public enum ResendReason
{
None = 0,
TimeoutExpired = (1 << 0),
FastRetransmit = (1 << 1)
}
public UnackedPacketCollection(OpenMetaverse.Interfaces.IByteBufferPool bufferPool)
{
m_bufferPool = bufferPool;
}
/// <summary>
/// Add an unacked packet to the collection
/// </summary>
/// <param name="packet">Packet that is awaiting acknowledgement</param>
/// <returns>True if the packet was successfully added, false if the
/// packet already existed in the collection</returns>
/// <remarks>This does not immediately add the ACK to the collection,
/// it only queues it so it can be added in a thread-safe way later</remarks>
public void Add(OutgoingPacket packet)
{
packet.AddRef();
m_pendingAdds.Enqueue(packet);
}
/// <summary>
/// Marks a packet as acknowledged
/// </summary>
/// <param name="sequenceNumber">Sequence number of the packet to
/// acknowledge</param>
/// <param name="currentTime">Current value of Environment.TickCount</param>
/// <remarks>This does not immediately acknowledge the packet, it only
/// queues the ack so it can be handled in a thread-safe way later</remarks>
public void Remove(uint sequenceNumber, int currentTime, bool fromResend)
{
m_pendingRemoves.Enqueue(new PendingAck(sequenceNumber, currentTime, fromResend));
}
/// <summary>
/// Returns a list of all of the packets with a TickCount older than
/// the specified timeout
/// </summary>
/// <param name="timeoutMS">Number of ticks (milliseconds) before a
/// packet is considered expired</param>
/// <returns>A list of all expired packets according to the given
/// expiration timeout</returns>
/// <remarks>This function is not thread safe, and cannot be called
/// multiple times concurrently</remarks>
public KeyValuePair<ResendReason, List<OutgoingPacket>> GetExpiredPackets(int timeoutMS)
{
ProcessQueues();
List<OutgoingPacket> expiredPackets = null;
ResendReason reason = ResendReason.None;
if (m_packets.Count > 0)
{
int now = Environment.TickCount & Int32.MaxValue;
foreach (OutgoingPacket packet in m_packets.Values)
{
// TickCount of zero means a packet is in the resend queue
// but hasn't actually been sent over the wire yet
if (packet.TickCount == 0)
continue;
if (packet.ResendCount == 0 &&
packet.SequenceNumber + FAST_RETRANSMIT_SEQUENCE_THRESHOLD <= m_highestAck)
{
//we've gotten acks from other packets with significantly higher sequence numbers
//retransmit this one
if (expiredPackets == null)
expiredPackets = new List<OutgoingPacket>();
// The TickCount will be set to the current time when the packet
// is actually sent out again
packet.TickCount = 0;
reason |= ResendReason.FastRetransmit;
expiredPackets.Add(packet);
}
else if (now - packet.TickCount >= timeoutMS)
{
if (expiredPackets == null)
expiredPackets = new List<OutgoingPacket>();
// The TickCount will be set to the current time when the packet
// is actually sent out again
packet.TickCount = 0;
reason |= ResendReason.TimeoutExpired;
expiredPackets.Add(packet);
}
}
}
return new KeyValuePair<ResendReason, List<OutgoingPacket>>(reason, expiredPackets);
}
private void ProcessQueues()
{
// Process all the pending adds
OutgoingPacket pendingAdd;
while (m_pendingAdds.Dequeue(out pendingAdd))
{
m_packets[pendingAdd.SequenceNumber] = pendingAdd;
}
// Process all the pending removes, including updating statistics and round-trip times
PendingAck pendingRemove;
OutgoingPacket ackedPacket;
while (m_pendingRemoves.Dequeue(out pendingRemove))
{
if (m_packets.TryGetValue(pendingRemove.SequenceNumber, out ackedPacket))
{
m_packets.Remove(pendingRemove.SequenceNumber);
ackedPacket.DecRef(m_bufferPool);
m_highestAck = Math.Max(pendingRemove.SequenceNumber, m_highestAck);
//wrap around (rare)
if (m_highestAck > pendingRemove.SequenceNumber
&& m_highestAck - pendingRemove.SequenceNumber > uint.MaxValue / 2)
{
//reset
m_highestAck = pendingRemove.SequenceNumber;
}
// Update stats
System.Threading.Interlocked.Add(ref ((LLUDPClient)ackedPacket.Client).UnackedBytes, -ackedPacket.DataSize);
if (!pendingRemove.FromResend)
{
// Calculate the round-trip time for this packet and its ACK
int rtt = pendingRemove.RemoveTime - ackedPacket.TickCount;
if (rtt > 0)
((LLUDPClient)ackedPacket.Client).UpdateRoundTrip(rtt);
}
}
}
}
}
}
| |
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Moq;
using NUnit.Framework;
using umbraco.cms.businesslogic.contentitem;
using Umbraco.Core;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
namespace Umbraco.Tests.Persistence.Repositories
{
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture]
public class DomainRepositoryTest : BaseDatabaseFactoryTest
{
private DomainRepository CreateRepository(IDatabaseUnitOfWork unitOfWork, out ContentTypeRepository contentTypeRepository, out ContentRepository contentRepository, out LanguageRepository languageRepository)
{
var templateRepository = new TemplateRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax, Mock.Of<IFileSystem>(), Mock.Of<IFileSystem>(), Mock.Of<ITemplatesSection>());
var tagRepository = new TagRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax);
contentTypeRepository = new ContentTypeRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax, templateRepository);
contentRepository = new ContentRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax, contentTypeRepository, templateRepository, tagRepository, Mock.Of<IContentSection>());
languageRepository = new LanguageRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax);
var domainRepository = new DomainRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax);
return domainRepository;
}
private int CreateTestData(string isoName, out ContentType ct)
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = new Language(isoName);
langRepo.AddOrUpdate(lang);
ct = MockedContentTypes.CreateBasicContentType("test", "Test");
contentTypeRepo.AddOrUpdate(ct);
var content = new Content("test", -1, ct) { CreatorId = 0, WriterId = 0 };
contentRepo.AddOrUpdate(content);
unitOfWork.Commit();
return content.Id;
}
}
[Test]
public void Can_Create_And_Get_By_Id()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
//re-get
domain = repo.Get(domain.Id);
Assert.NotNull(domain);
Assert.IsTrue(domain.HasIdentity);
Assert.Greater(domain.Id, 0);
Assert.AreEqual("test.com", domain.DomainName);
Assert.AreEqual(content.Id, domain.RootContentId);
Assert.AreEqual(lang.Id, domain.LanguageId);
}
}
[Test]
public void Cant_Create_Duplicate_Domain_Name()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
var domain1 = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id };
repo.AddOrUpdate(domain1);
unitOfWork.Commit();
var domain2 = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id };
repo.AddOrUpdate(domain2);
Assert.Throws<DuplicateNameException>(unitOfWork.Commit);
}
}
[Test]
public void Can_Delete()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
repo.Delete(domain);
unitOfWork.Commit();
//re-get
domain = repo.Get(domain.Id);
Assert.IsNull(domain);
}
}
[Test]
public void Can_Update()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId1 = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var content1 = contentRepo.Get(contentId1);
//more test data
var lang1 = langRepo.GetByIsoCode("en-AU");
var lang2 = new Language("es");
langRepo.AddOrUpdate(lang2);
var content2 = new Content("test", -1, ct) { CreatorId = 0, WriterId = 0 };
contentRepo.AddOrUpdate(content2);
unitOfWork.Commit();
var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content1.Id, LanguageId = lang1.Id };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
//re-get
domain = repo.Get(domain.Id);
domain.DomainName = "blah.com";
domain.RootContentId = content2.Id;
domain.LanguageId = lang2.Id;
repo.AddOrUpdate(domain);
unitOfWork.Commit();
//re-get
domain = repo.Get(domain.Id);
Assert.AreEqual("blah.com", domain.DomainName);
Assert.AreEqual(content2.Id, domain.RootContentId);
Assert.AreEqual(lang2.Id, domain.LanguageId);
}
}
[Test]
public void Exists()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain("test" + i + ".com") { RootContentId = content.Id, LanguageId = lang.Id };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var found = repo.Exists("test1.com");
Assert.IsTrue(found);
}
}
[Test]
public void Get_By_Name()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain("test" + i + ".com") { RootContentId = content.Id, LanguageId = lang.Id };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var found = repo.GetByName("test1.com");
Assert.IsNotNull(found);
}
}
[Test]
public void Get_All()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain("test " + i + ".com") { RootContentId = content.Id, LanguageId = lang.Id };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var all = repo.GetAll();
Assert.AreEqual(10, all.Count());
}
}
[Test]
public void Get_All_Ids()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
var ids = new List<int>();
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain("test " + i + ".com") { RootContentId = content.Id, LanguageId = lang.Id };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
ids.Add(domain.Id);
}
var all = repo.GetAll(ids.Take(8).ToArray());
Assert.AreEqual(8, all.Count());
}
}
[Test]
public void Get_All_Without_Wildcards()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain((i % 2 == 0) ? "test " + i + ".com" : ("*" + i))
{
RootContentId = content.Id,
LanguageId = lang.Id
};
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var all = repo.GetAll(false);
Assert.AreEqual(5, all.Count());
}
}
[Test]
public void Get_All_For_Content()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var contentItems = new List<IContent>();
var lang = langRepo.GetByIsoCode("en-AU");
contentItems.Add(contentRepo.Get(contentId));
//more test data (3 content items total)
for (int i = 0; i < 2; i++)
{
var c = new Content("test" + i, -1, ct) { CreatorId = 0, WriterId = 0 };
contentRepo.AddOrUpdate(c);
unitOfWork.Commit();
contentItems.Add(c);
}
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain((i % 2 == 0) ? "test " + i + ".com" : ("*" + i))
{
RootContentId = ((i % 2 == 0) ? contentItems[0] : contentItems[1]).Id,
LanguageId = lang.Id
};
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var all1 = repo.GetAssignedDomains(contentItems[0].Id, true);
Assert.AreEqual(5, all1.Count());
var all2 = repo.GetAssignedDomains(contentItems[1].Id, true);
Assert.AreEqual(5, all2.Count());
var all3 = repo.GetAssignedDomains(contentItems[2].Id, true);
Assert.AreEqual(0, all3.Count());
}
}
[Test]
public void Get_All_For_Content_Without_Wildcards()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var contentItems = new List<IContent>();
var lang = langRepo.GetByIsoCode("en-AU");
contentItems.Add(contentRepo.Get(contentId));
//more test data (3 content items total)
for (int i = 0; i < 2; i++)
{
var c = new Content("test" + i, -1, ct) { CreatorId = 0, WriterId = 0 };
contentRepo.AddOrUpdate(c);
unitOfWork.Commit();
contentItems.Add(c);
}
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain((i % 2 == 0) ? "test " + i + ".com" : ("*" + i))
{
RootContentId = ((i % 2 == 0) ? contentItems[0] : contentItems[1]).Id,
LanguageId = lang.Id
};
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var all1 = repo.GetAssignedDomains(contentItems[0].Id, false);
Assert.AreEqual(5, all1.Count());
var all2 = repo.GetAssignedDomains(contentItems[1].Id, false);
Assert.AreEqual(0, all2.Count());
}
}
}
}
| |
/*
* 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 sqs-2012-11-05.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.SQS.Model;
using Amazon.SQS.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.SQS
{
/// <summary>
/// Implementation for accessing SQS
///
/// Welcome to the <i>Amazon Simple Queue Service API Reference</i>. This section describes
/// who should read this guide, how the guide is organized, and other resources related
/// to the Amazon Simple Queue Service (Amazon SQS).
///
///
/// <para>
/// Amazon SQS offers reliable and scalable hosted queues for storing messages as they
/// travel between computers. By using Amazon SQS, you can move data between distributed
/// components of your applications that perform different tasks without losing messages
/// or requiring each component to be always available.
/// </para>
///
/// <para>
/// Helpful Links: <ul> <li><a href="http://queue.amazonaws.com/doc/2012-11-05/QueueService.wsdl">Current
/// WSDL (2012-11-05)</a></li> <li><a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/MakingRequestsArticle.html">Making
/// API Requests</a></li> <li><a href="http://aws.amazon.com/sqs/">Amazon SQS product
/// page</a></li> <li><a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSMessageAttributes.html">Using
/// Amazon SQS Message Attributes</a></li> <li><a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSDeadLetterQueue.html">Using
/// Amazon SQS Dead Letter Queues</a></li> <li><a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#sqs_region">Regions
/// and Endpoints</a></li> </ul>
/// </para>
///
/// <para>
/// We also provide SDKs that enable you to access Amazon SQS from your preferred programming
/// language. The SDKs contain functionality that automatically takes care of tasks such
/// as:
/// </para>
///
/// <para>
/// <ul> <li>Cryptographically signing your service requests</li> <li>Retrying requests</li>
/// <li>Handling error responses</li> </ul>
/// </para>
///
/// <para>
/// For a list of available SDKs, go to <a href="http://aws.amazon.com/tools/">Tools for
/// Amazon Web Services</a>.
/// </para>
/// </summary>
public partial class AmazonSQSClient : AmazonServiceClient, IAmazonSQS
{
#region Constructors
/// <summary>
/// Constructs AmazonSQSClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonSQSClient(AWSCredentials credentials)
: this(credentials, new AmazonSQSConfig())
{
}
/// <summary>
/// Constructs AmazonSQSClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonSQSClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonSQSConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonSQSClient with AWS Credentials and an
/// AmazonSQSClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonSQSClient Configuration Object</param>
public AmazonSQSClient(AWSCredentials credentials, AmazonSQSConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonSQSClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonSQSClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonSQSConfig())
{
}
/// <summary>
/// Constructs AmazonSQSClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonSQSClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonSQSConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonSQSClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonSQSClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonSQSClient Configuration Object</param>
public AmazonSQSClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonSQSConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonSQSClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonSQSClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSQSConfig())
{
}
/// <summary>
/// Constructs AmazonSQSClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonSQSClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSQSConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonSQSClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonSQSClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonSQSClient Configuration Object</param>
public AmazonSQSClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonSQSConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
protected override void CustomizeRuntimePipeline(RuntimePipeline pipeline)
{
pipeline.AddHandlerAfter<Amazon.Runtime.Internal.Marshaller>(new Amazon.SQS.Internal.ProcessRequestHandler());
pipeline.AddHandlerBefore<Amazon.Runtime.Internal.Unmarshaller>(new Amazon.SQS.Internal.ValidationResponseHandler());
}
#endregion
#region Dispose
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region AddPermission
internal AddPermissionResponse AddPermission(AddPermissionRequest request)
{
var marshaller = new AddPermissionRequestMarshaller();
var unmarshaller = AddPermissionResponseUnmarshaller.Instance;
return Invoke<AddPermissionRequest,AddPermissionResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the AddPermission operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AddPermission operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<AddPermissionResponse> AddPermissionAsync(AddPermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new AddPermissionRequestMarshaller();
var unmarshaller = AddPermissionResponseUnmarshaller.Instance;
return InvokeAsync<AddPermissionRequest,AddPermissionResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ChangeMessageVisibility
internal ChangeMessageVisibilityResponse ChangeMessageVisibility(ChangeMessageVisibilityRequest request)
{
var marshaller = new ChangeMessageVisibilityRequestMarshaller();
var unmarshaller = ChangeMessageVisibilityResponseUnmarshaller.Instance;
return Invoke<ChangeMessageVisibilityRequest,ChangeMessageVisibilityResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ChangeMessageVisibility operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ChangeMessageVisibility operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ChangeMessageVisibilityResponse> ChangeMessageVisibilityAsync(ChangeMessageVisibilityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ChangeMessageVisibilityRequestMarshaller();
var unmarshaller = ChangeMessageVisibilityResponseUnmarshaller.Instance;
return InvokeAsync<ChangeMessageVisibilityRequest,ChangeMessageVisibilityResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ChangeMessageVisibilityBatch
internal ChangeMessageVisibilityBatchResponse ChangeMessageVisibilityBatch(ChangeMessageVisibilityBatchRequest request)
{
var marshaller = new ChangeMessageVisibilityBatchRequestMarshaller();
var unmarshaller = ChangeMessageVisibilityBatchResponseUnmarshaller.Instance;
return Invoke<ChangeMessageVisibilityBatchRequest,ChangeMessageVisibilityBatchResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ChangeMessageVisibilityBatch operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ChangeMessageVisibilityBatch operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ChangeMessageVisibilityBatchResponse> ChangeMessageVisibilityBatchAsync(ChangeMessageVisibilityBatchRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ChangeMessageVisibilityBatchRequestMarshaller();
var unmarshaller = ChangeMessageVisibilityBatchResponseUnmarshaller.Instance;
return InvokeAsync<ChangeMessageVisibilityBatchRequest,ChangeMessageVisibilityBatchResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region CreateQueue
internal CreateQueueResponse CreateQueue(CreateQueueRequest request)
{
var marshaller = new CreateQueueRequestMarshaller();
var unmarshaller = CreateQueueResponseUnmarshaller.Instance;
return Invoke<CreateQueueRequest,CreateQueueResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateQueue operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateQueue operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateQueueResponse> CreateQueueAsync(CreateQueueRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateQueueRequestMarshaller();
var unmarshaller = CreateQueueResponseUnmarshaller.Instance;
return InvokeAsync<CreateQueueRequest,CreateQueueResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteMessage
internal DeleteMessageResponse DeleteMessage(DeleteMessageRequest request)
{
var marshaller = new DeleteMessageRequestMarshaller();
var unmarshaller = DeleteMessageResponseUnmarshaller.Instance;
return Invoke<DeleteMessageRequest,DeleteMessageResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteMessage operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteMessage operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteMessageResponse> DeleteMessageAsync(DeleteMessageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteMessageRequestMarshaller();
var unmarshaller = DeleteMessageResponseUnmarshaller.Instance;
return InvokeAsync<DeleteMessageRequest,DeleteMessageResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteMessageBatch
internal DeleteMessageBatchResponse DeleteMessageBatch(DeleteMessageBatchRequest request)
{
var marshaller = new DeleteMessageBatchRequestMarshaller();
var unmarshaller = DeleteMessageBatchResponseUnmarshaller.Instance;
return Invoke<DeleteMessageBatchRequest,DeleteMessageBatchResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteMessageBatch operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteMessageBatch operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteMessageBatchResponse> DeleteMessageBatchAsync(DeleteMessageBatchRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteMessageBatchRequestMarshaller();
var unmarshaller = DeleteMessageBatchResponseUnmarshaller.Instance;
return InvokeAsync<DeleteMessageBatchRequest,DeleteMessageBatchResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteQueue
internal DeleteQueueResponse DeleteQueue(DeleteQueueRequest request)
{
var marshaller = new DeleteQueueRequestMarshaller();
var unmarshaller = DeleteQueueResponseUnmarshaller.Instance;
return Invoke<DeleteQueueRequest,DeleteQueueResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteQueue operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteQueue operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteQueueResponse> DeleteQueueAsync(DeleteQueueRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteQueueRequestMarshaller();
var unmarshaller = DeleteQueueResponseUnmarshaller.Instance;
return InvokeAsync<DeleteQueueRequest,DeleteQueueResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetQueueAttributes
internal GetQueueAttributesResponse GetQueueAttributes(GetQueueAttributesRequest request)
{
var marshaller = new GetQueueAttributesRequestMarshaller();
var unmarshaller = GetQueueAttributesResponseUnmarshaller.Instance;
return Invoke<GetQueueAttributesRequest,GetQueueAttributesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetQueueAttributes operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetQueueAttributes operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetQueueAttributesResponse> GetQueueAttributesAsync(GetQueueAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetQueueAttributesRequestMarshaller();
var unmarshaller = GetQueueAttributesResponseUnmarshaller.Instance;
return InvokeAsync<GetQueueAttributesRequest,GetQueueAttributesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetQueueUrl
internal GetQueueUrlResponse GetQueueUrl(GetQueueUrlRequest request)
{
var marshaller = new GetQueueUrlRequestMarshaller();
var unmarshaller = GetQueueUrlResponseUnmarshaller.Instance;
return Invoke<GetQueueUrlRequest,GetQueueUrlResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetQueueUrl operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetQueueUrl operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetQueueUrlResponse> GetQueueUrlAsync(GetQueueUrlRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetQueueUrlRequestMarshaller();
var unmarshaller = GetQueueUrlResponseUnmarshaller.Instance;
return InvokeAsync<GetQueueUrlRequest,GetQueueUrlResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ListDeadLetterSourceQueues
internal ListDeadLetterSourceQueuesResponse ListDeadLetterSourceQueues(ListDeadLetterSourceQueuesRequest request)
{
var marshaller = new ListDeadLetterSourceQueuesRequestMarshaller();
var unmarshaller = ListDeadLetterSourceQueuesResponseUnmarshaller.Instance;
return Invoke<ListDeadLetterSourceQueuesRequest,ListDeadLetterSourceQueuesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ListDeadLetterSourceQueues operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListDeadLetterSourceQueues operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ListDeadLetterSourceQueuesResponse> ListDeadLetterSourceQueuesAsync(ListDeadLetterSourceQueuesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ListDeadLetterSourceQueuesRequestMarshaller();
var unmarshaller = ListDeadLetterSourceQueuesResponseUnmarshaller.Instance;
return InvokeAsync<ListDeadLetterSourceQueuesRequest,ListDeadLetterSourceQueuesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ListQueues
internal ListQueuesResponse ListQueues(ListQueuesRequest request)
{
var marshaller = new ListQueuesRequestMarshaller();
var unmarshaller = ListQueuesResponseUnmarshaller.Instance;
return Invoke<ListQueuesRequest,ListQueuesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ListQueues operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListQueues operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ListQueuesResponse> ListQueuesAsync(ListQueuesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ListQueuesRequestMarshaller();
var unmarshaller = ListQueuesResponseUnmarshaller.Instance;
return InvokeAsync<ListQueuesRequest,ListQueuesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region PurgeQueue
internal PurgeQueueResponse PurgeQueue(PurgeQueueRequest request)
{
var marshaller = new PurgeQueueRequestMarshaller();
var unmarshaller = PurgeQueueResponseUnmarshaller.Instance;
return Invoke<PurgeQueueRequest,PurgeQueueResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the PurgeQueue operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PurgeQueue operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<PurgeQueueResponse> PurgeQueueAsync(PurgeQueueRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new PurgeQueueRequestMarshaller();
var unmarshaller = PurgeQueueResponseUnmarshaller.Instance;
return InvokeAsync<PurgeQueueRequest,PurgeQueueResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ReceiveMessage
internal ReceiveMessageResponse ReceiveMessage(ReceiveMessageRequest request)
{
var marshaller = new ReceiveMessageRequestMarshaller();
var unmarshaller = ReceiveMessageResponseUnmarshaller.Instance;
return Invoke<ReceiveMessageRequest,ReceiveMessageResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ReceiveMessage operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ReceiveMessage operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ReceiveMessageResponse> ReceiveMessageAsync(ReceiveMessageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ReceiveMessageRequestMarshaller();
var unmarshaller = ReceiveMessageResponseUnmarshaller.Instance;
return InvokeAsync<ReceiveMessageRequest,ReceiveMessageResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region RemovePermission
internal RemovePermissionResponse RemovePermission(RemovePermissionRequest request)
{
var marshaller = new RemovePermissionRequestMarshaller();
var unmarshaller = RemovePermissionResponseUnmarshaller.Instance;
return Invoke<RemovePermissionRequest,RemovePermissionResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the RemovePermission operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RemovePermission operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<RemovePermissionResponse> RemovePermissionAsync(RemovePermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new RemovePermissionRequestMarshaller();
var unmarshaller = RemovePermissionResponseUnmarshaller.Instance;
return InvokeAsync<RemovePermissionRequest,RemovePermissionResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region SendMessage
internal SendMessageResponse SendMessage(SendMessageRequest request)
{
var marshaller = new SendMessageRequestMarshaller();
var unmarshaller = SendMessageResponseUnmarshaller.Instance;
return Invoke<SendMessageRequest,SendMessageResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the SendMessage operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SendMessage operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<SendMessageResponse> SendMessageAsync(SendMessageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new SendMessageRequestMarshaller();
var unmarshaller = SendMessageResponseUnmarshaller.Instance;
return InvokeAsync<SendMessageRequest,SendMessageResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region SendMessageBatch
internal SendMessageBatchResponse SendMessageBatch(SendMessageBatchRequest request)
{
var marshaller = new SendMessageBatchRequestMarshaller();
var unmarshaller = SendMessageBatchResponseUnmarshaller.Instance;
return Invoke<SendMessageBatchRequest,SendMessageBatchResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the SendMessageBatch operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SendMessageBatch operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<SendMessageBatchResponse> SendMessageBatchAsync(SendMessageBatchRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new SendMessageBatchRequestMarshaller();
var unmarshaller = SendMessageBatchResponseUnmarshaller.Instance;
return InvokeAsync<SendMessageBatchRequest,SendMessageBatchResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region SetQueueAttributes
internal SetQueueAttributesResponse SetQueueAttributes(SetQueueAttributesRequest request)
{
var marshaller = new SetQueueAttributesRequestMarshaller();
var unmarshaller = SetQueueAttributesResponseUnmarshaller.Instance;
return Invoke<SetQueueAttributesRequest,SetQueueAttributesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the SetQueueAttributes operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetQueueAttributes operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<SetQueueAttributesResponse> SetQueueAttributesAsync(SetQueueAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new SetQueueAttributesRequestMarshaller();
var unmarshaller = SetQueueAttributesResponseUnmarshaller.Instance;
return InvokeAsync<SetQueueAttributesRequest,SetQueueAttributesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
}
}
| |
//+-----------------------------------------------------------------------
//
// Microsoft Windows Client Platform
// Copyright (C) Microsoft Corporation, 2002
//
// File: FamilyTypeface.cs
//
// Contents: FamilyTypeface implementation
//
// Spec: http://team/sites/Avalon/Specs/Fonts.htm
//
// Created: 11-11-2003 Tarek Mahmoud Sayed ([....])
//
//------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.ComponentModel;
using System.Windows.Markup; // for XmlLanguage
using MS.Internal.FontFace;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media
{
/// <summary>
/// The FamilyTypeface object specifies the details of a single typeface supported by a
/// FontFamily. There are as many FamilyTypeface objects as there are typefaces supported.
/// </summary>
public class FamilyTypeface : IDeviceFont, ITypefaceMetrics
{
/// <summary>
/// Construct a default family typeface
/// </summary>
public FamilyTypeface()
{}
/// <summary>
/// Construct a read-only FamilyTypeface from a Typeface.
/// </summary>
internal FamilyTypeface(Typeface face)
{
_style = face.Style;
_weight = face.Weight;
_stretch = face.Stretch;
_underlinePosition = face.UnderlinePosition;
_underlineThickness = face.UnderlineThickness;
_strikeThroughPosition = face.StrikethroughPosition;
_strikeThroughThickness = face.StrikethroughThickness;
_capsHeight = face.CapsHeight;
_xHeight = face.XHeight;
_readOnly = true;
}
/// <summary>
/// Typeface style
/// </summary>
public FontStyle Style
{
get { return _style; }
set
{
VerifyChangeable();
_style = value;
}
}
/// <summary>
/// Typeface weight
/// </summary>
public FontWeight Weight
{
get { return _weight; }
set
{
VerifyChangeable();
_weight = value;
}
}
/// <summary>
/// Typeface stretch
/// </summary>
public FontStretch Stretch
{
get { return _stretch; }
set
{
VerifyChangeable();
_stretch = value;
}
}
/// <summary>
/// Typeface underline position in EM relative to baseline
/// </summary>
public double UnderlinePosition
{
get { return _underlinePosition ; }
set
{
CompositeFontParser.VerifyMultiplierOfEm("UnderlinePosition", ref value);
VerifyChangeable();
_underlinePosition = value;
}
}
/// <summary>
/// Typeface underline thickness in EM
/// </summary>
public double UnderlineThickness
{
get { return _underlineThickness; }
set
{
CompositeFontParser.VerifyPositiveMultiplierOfEm("UnderlineThickness", ref value);
VerifyChangeable();
_underlineThickness = value;
}
}
/// <summary>
/// Typeface strikethrough position in EM relative to baseline
/// </summary>
public double StrikethroughPosition
{
get { return _strikeThroughPosition; }
set
{
CompositeFontParser.VerifyMultiplierOfEm("StrikethroughPosition", ref value);
VerifyChangeable();
_strikeThroughPosition = value;
}
}
/// <summary>
/// Typeface strikethrough thickness in EM
/// </summary>
public double StrikethroughThickness
{
get { return _strikeThroughThickness; }
set
{
CompositeFontParser.VerifyPositiveMultiplierOfEm("StrikethroughThickness", ref value);
VerifyChangeable();
_strikeThroughThickness = value;
}
}
/// <summary>
/// Typeface caps height in EM
/// </summary>
public double CapsHeight
{
get { return _capsHeight; }
set
{
CompositeFontParser.VerifyPositiveMultiplierOfEm("CapsHeight", ref value);
VerifyChangeable();
_capsHeight = value;
}
}
/// <summary>
/// Typeface X-height in EM
/// </summary>
public double XHeight
{
get { return _xHeight; }
set
{
CompositeFontParser.VerifyPositiveMultiplierOfEm("XHeight", ref value);
VerifyChangeable();
_xHeight = value;
}
}
/// <summary>
/// Flag indicate whether this is symbol typeface; always false for FamilyTypeface.
/// </summary>
bool ITypefaceMetrics.Symbol
{
get { return false; }
}
/// <summary>
/// Style simulation flags for this typeface.
/// </summary>
StyleSimulations ITypefaceMetrics.StyleSimulations
{
get
{
return StyleSimulations.None;
}
}
/// <summary>
/// Collection of localized face names adjusted by the font differentiator.
/// </summary>
public IDictionary<XmlLanguage, string> AdjustedFaceNames
{
get
{
return FontDifferentiator.ConstructFaceNamesByStyleWeightStretch(_style, _weight, _stretch);
}
}
/// <summary>
/// Compares two typefaces for equality; returns true if the specified typeface
/// is not null and has the same properties as this typeface.
/// </summary>
public bool Equals(FamilyTypeface typeface)
{
if (typeface == null)
return false;
return (
Style == typeface.Style
&& Weight == typeface.Weight
&& Stretch == typeface.Stretch
);
}
/// <summary>
/// Name or unique identifier of a device font.
/// </summary>
public string DeviceFontName
{
get { return _deviceFontName; }
set
{
VerifyChangeable();
_deviceFontName = value;
}
}
/// <summary>
/// Collection of character metrics for a device font.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public CharacterMetricsDictionary DeviceFontCharacterMetrics
{
get
{
if (_characterMetrics == null)
{
_characterMetrics = new CharacterMetricsDictionary();
}
return _characterMetrics;
}
}
/// <summary>
/// <see cref="object.Equals(object)"/>
/// </summary>
public override bool Equals(object o)
{
return Equals(o as FamilyTypeface);
}
/// <summary>
/// <see cref="object.GetHashCode"/>
/// </summary>
public override int GetHashCode()
{
return _style.GetHashCode()
^ _weight.GetHashCode()
^ _stretch.GetHashCode();
}
private void VerifyChangeable()
{
if (_readOnly)
throw new NotSupportedException(SR.Get(SRID.General_ObjectIsReadOnly));
}
string IDeviceFont.Name
{
get { return _deviceFontName; }
}
bool IDeviceFont.ContainsCharacter(int unicodeScalar)
{
return _characterMetrics != null && _characterMetrics.GetValue(unicodeScalar) != null;
}
/// <SecurityNote>
/// Critical - As it uses raw pointers.
/// </SecurityNote>
[SecurityCritical]
unsafe void IDeviceFont.GetAdvanceWidths(
char* characterString,
int characterLength,
double emSize,
int* pAdvances
)
{
unsafe
{
for (int i = 0; i < characterLength; ++i)
{
CharacterMetrics metrics = _characterMetrics.GetValue(characterString[i]);
if (metrics != null)
{
// Side bearings are included in the advance width but are not used as offsets for glyph positioning.
pAdvances[i] = Math.Max(0, (int)((metrics.BlackBoxWidth + metrics.LeftSideBearing + metrics.RightSideBearing) * emSize));
}
else
{
pAdvances[i] = 0;
}
}
}
}
private bool _readOnly;
private FontStyle _style;
private FontWeight _weight;
private FontStretch _stretch;
private double _underlinePosition;
private double _underlineThickness;
private double _strikeThroughPosition;
private double _strikeThroughThickness;
private double _capsHeight;
private double _xHeight;
private string _deviceFontName;
private CharacterMetricsDictionary _characterMetrics;
}
}
| |
//
// DetailsView.cs
//
// Authors:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Collections;
using Hyena.Data.Sqlite;
using Hyena.Data;
using Hyena.Data.Gui;
using Hyena.Widgets;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.Collection.Database;
using Banshee.Configuration;
using Banshee.Database;
using Banshee.Gui;
using Banshee.Library;
using Banshee.MediaEngine;
using Banshee.PlaybackController;
using Banshee.Playlist;
using Banshee.Preferences;
using Banshee.ServiceStack;
using Banshee.Sources;
using IA=InternetArchive;
namespace Banshee.InternetArchive
{
public class DetailsView : Gtk.HBox, Banshee.Sources.Gui.ISourceContents
{
private DetailsSource source;
private IA.Details details;
private Item item;
public DetailsView (DetailsSource source, Item item)
{
this.source = source;
this.item = item;
Spacing = 6;
source.LoadDetails ();
}
private bool gui_built;
public void UpdateDetails ()
{
details = item.Details;
if (!gui_built && details != null) {
gui_built = true;
BuildInfoBox ();
BuildFilesBox ();
ShowAll ();
}
}
#region ISourceContents
public bool SetSource (ISource source)
{
this.source = source as DetailsSource;
return this.source != null;
}
public void ResetSource ()
{
}
public ISource Source { get { return source; } }
public Widget Widget { get { return this; } }
#endregion
private Section CreateSection (string label, Widget child)
{
var section = new Section (label, child);
return section;
}
private class Section : VBox
{
public Section (string label, Widget child)
{
Spacing = 6;
Header = new SectionHeader (label, child);
PackStart (Header, false, false, 0);
PackStart (child, false, false, 0);
}
public SectionHeader Header { get; private set; }
}
private class SectionHeader : EventBox
{
Arrow arrow;
Label label;
Widget child;
public HBox Box { get; private set; }
public SectionHeader (string headerString, Widget child)
{
this.child = child;
AppPaintable = true;
CanFocus = true;
Box = new HBox ();
Box.Spacing = 6;
Box.BorderWidth = 4;
label = new Label ("<b>" + headerString + "</b>") { Xalign = 0f, UseMarkup = true };
arrow = new Arrow (ArrowType.Down, ShadowType.None);
Box.PackStart (arrow, false, false, 0);
Box.PackStart (label, true, true, 0);
this.SetStateFlags (StateFlags.Selected, true);
bool changing_style = false;
StyleUpdated += (o, a) => {
if (!changing_style) {
changing_style = true;
OverrideBackgroundColor (StateFlags.Normal, StyleContext.GetBackgroundColor (StateFlags.Selected));
changing_style = false;
}
};
Child = Box;
ButtonPressEvent += (o, a) => Toggle ();
KeyPressEvent += (o, a) => {
var key = a.Event.Key;
switch (key) {
case Gdk.Key.Return:
case Gdk.Key.KP_Enter:
case Gdk.Key.space:
Toggle ();
a.RetVal = true;
break;
}
};
}
private void Toggle ()
{
Expanded = !Expanded;
}
private bool expanded = true;
private bool Expanded {
get { return expanded; }
set {
arrow.ArrowType = value ? ArrowType.Down : ArrowType.Right;
child.Visible = value;
expanded = value;
}
}
}
private void BuildInfoBox ()
{
var frame = new Hyena.Widgets.RoundedFrame ();
var vbox = new VBox ();
vbox.Spacing = 6;
vbox.BorderWidth = 2;
// Description
var desc = new Hyena.Widgets.WrapLabel () {
Markup = String.Format ("{0}", GLib.Markup.EscapeText (Hyena.StringUtil.RemoveHtml (details.Description)))
};
var desc_expander = CreateSection (Catalog.GetString ("Description"), desc);
// Details
var table = new Banshee.Gui.TrackEditor.StatisticsPage () {
ShadowType = ShadowType.None,
BorderWidth = 0
};
table.NameRenderer.Scale = Pango.Scale.Medium;
table.ValueRenderer.Scale = Pango.Scale.Medium;
// Keep the table from needing to vertically scroll
/*table.Child.SizeRequested += (o, a) => {
table.SetSizeRequest (a.Requisition.Width, a.Requisition.Height);
};*/
AddToTable (table, Catalog.GetString ("Creator:"), details.Creator);
AddToTable (table, Catalog.GetString ("Venue:"), details.Venue);
AddToTable (table, Catalog.GetString ("Location:"), details.Coverage);
if (details.DateCreated != DateTime.MinValue) {
AddToTable (table, Catalog.GetString ("Date:"), details.DateCreated);
} else {
AddToTable (table, Catalog.GetString ("Year:"), details.Year);
}
AddToTable (table, Catalog.GetString ("Publisher:"), details.Publisher);
AddToTable (table, Catalog.GetString ("Keywords:"), details.Subject);
AddToTable (table, Catalog.GetString ("License URL:"), details.LicenseUrl);
AddToTable (table, Catalog.GetString ("Language:"), details.Language);
table.AddSeparator ();
AddToTable (table, Catalog.GetString ("Downloads, overall:"), details.DownloadsAllTime);
AddToTable (table, Catalog.GetString ("Downloads, past month:"), details.DownloadsLastMonth);
AddToTable (table, Catalog.GetString ("Downloads, past week:"), details.DownloadsLastWeek);
table.AddSeparator ();
AddToTable (table, Catalog.GetString ("Added:"), details.DateAdded);
AddToTable (table, Catalog.GetString ("Added by:"), details.AddedBy);
AddToTable (table, Catalog.GetString ("Collections:"), details.Collections);
AddToTable (table, Catalog.GetString ("Source:"), details.Source);
AddToTable (table, Catalog.GetString ("Contributor:"), details.Contributor);
AddToTable (table, Catalog.GetString ("Recorded by:"),details.Taper);
AddToTable (table, Catalog.GetString ("Lineage:"), details.Lineage);
AddToTable (table, Catalog.GetString ("Transferred by:"), details.Transferer);
var details_expander = CreateSection (Catalog.GetString ("Details"), table);
// Reviews
Section reviews = null;
if (details.NumReviews > 0) {
string [] stars = {
"\u2606\u2606\u2606\u2606\u2606",
"\u2605\u2606\u2606\u2606\u2606",
"\u2605\u2605\u2606\u2606\u2606",
"\u2605\u2605\u2605\u2606\u2606",
"\u2605\u2605\u2605\u2605\u2606",
"\u2605\u2605\u2605\u2605\u2605"
};
var reviews_box = new VBox () { Spacing = 12, BorderWidth = 0 };
reviews = CreateSection (Catalog.GetString ("Reviews"), reviews_box);
var avg_label = new Label (String.Format (Catalog.GetPluralString (
// Translators: {0} is the number of reviewers, {1} is the average rating (not really relevant if there's only 1)
"{0} reviewer", "{0} reviewers, avg {1}", details.NumReviews),
details.NumReviews, stars[Math.Max (0, Math.Min (5, (int)Math.Round (details.AvgRating)))]
));
avg_label.TooltipText = String.Format ("{0:N2}", details.AvgRating);
avg_label.Xalign = 1.0f;
reviews.Header.Box.PackEnd (avg_label, false, false, 0);
var sb = new System.Text.StringBuilder ();
foreach (var review in details.Reviews) {
//sb.Append ("<small>");
var review_txt = new Hyena.Widgets.WrapLabel ();
var title = review.Title;
if (title != null) {
sb.AppendFormat ("<b>{0}</b>\n", GLib.Markup.EscapeText (title));
}
// Translators: {0} is the unicode-stars-rating, {1} is the name of a person who reviewed this item, and {1} is a date/time string
sb.AppendFormat (Catalog.GetString ("{0} by {1} on {2}"),
stars[Math.Max (0, Math.Min (5, review.Stars))],
GLib.Markup.EscapeText (review.Reviewer),
GLib.Markup.EscapeText (review.DateReviewed.ToLocalTime ().ToShortDateString ())
);
var body = review.Body;
if (body != null) {
body = body.Replace ("\r\n", "\n");
body = body.Replace ("\n\n", "\n");
sb.Append ("\n");
sb.Append (GLib.Markup.EscapeText (body));
}
//sb.Append ("</small>");
review_txt.Markup = sb.ToString ();
sb.Length = 0;
reviews_box.PackStart (review_txt, false, false, 0);
}
}
// Packing
vbox.PackStart (desc_expander, true, true, 0);
vbox.PackStart (details_expander, true, true, 0);
if (reviews != null) {
vbox.PackStart (reviews, true, true, 0);
}
string write_review_url = String.Format ("http://www.archive.org/write-review.php?identifier={0}", item.Id);
var write_review_button = new LinkButton (write_review_url, Catalog.GetString ("Write your own review"));
write_review_button.Clicked += (o, a) => Banshee.Web.Browser.Open (write_review_url);
write_review_button.Xalign = 0f;
vbox.PackStart (write_review_button, false, false, 0);
var vbox2 = new VBox ();
vbox2.PackStart (vbox, false, false, 0);
var sw = new Gtk.ScrolledWindow () { ShadowType = ShadowType.None };
sw.AddWithViewport (vbox2);
(sw.Child as Viewport).ShadowType = ShadowType.None;
frame.Child = sw;
frame.ShowAll ();
sw.Child.OverrideBackgroundColor (StateFlags.Normal, StyleContext.GetBackgroundColor (StateFlags.Normal));
sw.Child.OverrideColor (StateFlags.Normal, StyleContext.GetColor (StateFlags.Normal));
StyleUpdated += delegate {
sw.Child.OverrideBackgroundColor (StateFlags.Normal, StyleContext.GetBackgroundColor (StateFlags.Normal));
sw.Child.OverrideColor (StateFlags.Normal, StyleContext.GetColor (StateFlags.Normal));
};
PackStart (frame, true, true, 0);
}
private void AddToTable (Banshee.Gui.TrackEditor.StatisticsPage table, string label, object val)
{
if (val != null) {
if (val is long) {
table.AddItem (label, ((long)val).ToString ("N0"));
} else if (val is DateTime) {
var dt = (DateTime)val;
if (dt != DateTime.MinValue) {
var local_dt = dt.ToLocalTime ();
var str = dt.TimeOfDay == TimeSpan.Zero
? local_dt.ToShortDateString ()
: local_dt.ToString ("g");
table.AddItem (label, str);
}
} else {
table.AddItem (label, val.ToString ());
}
}
}
private void BuildFilesBox ()
{
var vbox = new VBox ();
vbox.Spacing = 6;
var file_list = new BaseTrackListView () {
HeaderVisible = true,
IsEverReorderable = false
};
var files_model = source.TrackModel as MemoryTrackListModel;
var columns = new DefaultColumnController ();
columns.TrackColumn.Title = "#";
var file_columns = new ColumnController ();
file_columns.AddRange (
columns.IndicatorColumn,
columns.TrackColumn,
columns.TitleColumn,
columns.DurationColumn,
columns.FileSizeColumn
);
foreach (var col in file_columns) {
col.Visible = true;
}
var file_sw = new Gtk.ScrolledWindow ();
file_sw.Child = file_list;
var tracks = new List<TrackInfo> ();
var files = new List<IA.DetailsFile> (details.Files);
string [] format_blacklist = new string [] { "metadata", "fingerprint", "checksums", "xml", "m3u", "dublin core", "unknown" };
var formats = new List<string> ();
foreach (var f in files) {
var track = new TrackInfo () {
Uri = new SafeUri (f.Location),
FileSize = f.Size,
TrackNumber = f.Track,
ArtistName = f.Creator ?? details.Creator,
AlbumTitle = item.Title,
TrackTitle = f.Title,
BitRate = f.BitRate,
MimeType = f.Format,
Duration = f.Length
};
// Fix up duration/track#/title
if ((f.Length == TimeSpan.Zero || f.Title == null || f.Track == 0) && !f.Location.Contains ("zip") && !f.Location.EndsWith ("m3u")) {
foreach (var b in files) {
if ((f.Title != null && f.Title == b.Title)
|| (f.OriginalFile != null && b.Location != null && b.Location.EndsWith (f.OriginalFile))
|| (f.OriginalFile != null && f.OriginalFile == b.OriginalFile)) {
if (track.Duration == TimeSpan.Zero)
track.Duration = b.Length;
if (track.TrackTitle == null)
track.TrackTitle = b.Title;
if (track.TrackNumber == 0)
track.TrackNumber = b.Track;
if (track.Duration != TimeSpan.Zero && track.TrackTitle != null && track.TrackNumber != 0)
break;
}
}
}
track.TrackTitle = track.TrackTitle ?? System.IO.Path.GetFileName (f.Location);
tracks.Add (track);
if (f.Format != null && !formats.Contains (f.Format)) {
if (!format_blacklist.Any (fmt => f.Format.ToLower ().Contains (fmt))) {
formats.Add (f.Format);
}
}
}
// Order the formats according to the preferences
string format_order = String.Format (", {0}, {1}, {2},", HomeSource.VideoTypes.Get (), HomeSource.AudioTypes.Get (), HomeSource.TextTypes.Get ()).ToLower ();
var sorted_formats = formats.Select (f => new { Format = f, Order = Math.Max (format_order.IndexOf (", " + f.ToLower () + ","), format_order.IndexOf (f.ToLower ())) })
.OrderBy (o => o.Order == -1 ? Int32.MaxValue : o.Order);
// See if all the files contain their track #
bool all_tracks_have_num_in_title = tracks.All (t => t.TrackNumber == 0 || t.TrackTitle.Contains (t.TrackNumber.ToString ()));
// Make these columns snugly fix their data
if (tracks.Count > 0) {
// Mono in openSUSE 11.0 doesn't like this
//SetWidth (columns.TrackColumn, all_tracks_have_num_in_title ? 0 : tracks.Max (f => f.TrackNumber), 0);
int max_track = 0;
long max_size = 0;
foreach (var t in tracks) {
max_track = Math.Max (max_track, t.TrackNumber);
max_size = Math.Max (max_size, t.FileSize);
}
SetWidth (columns.TrackColumn, all_tracks_have_num_in_title ? 0 : max_track, 0);
// Mono in openSUSE 11.0 doesn't like this
//SetWidth (columns.FileSizeColumn, tracks.Max (f => f.FileSize), 0);
SetWidth (columns.FileSizeColumn, max_size, 0);
SetWidth (columns.DurationColumn, tracks.Max (f => f.Duration), TimeSpan.Zero);
}
string max_title = " ";
if (tracks.Count > 0) {
var sorted_by_title = files.Where (t => !t.Location.Contains ("zip"))
.OrderBy (f => f.Title == null ? 0 : f.Title.Length)
.ToList ();
string nine_tenths = sorted_by_title[(int)Math.Floor (.90 * sorted_by_title.Count)].Title ?? "";
string max = sorted_by_title[sorted_by_title.Count - 1].Title ?? "";
max_title = ((double)max.Length >= (double)(1.6 * (double)nine_tenths.Length)) ? nine_tenths : max;
}
(columns.TitleColumn.GetCell (0) as ColumnCellText).SetMinMaxStrings (max_title);
file_list.ColumnController = file_columns;
file_list.SetModel (files_model);
var format_list = new ComboBoxText ();
format_list.RowSeparatorFunc = (model, iter) => {
return (string)model.GetValue (iter, 0) == "---";
};
bool have_sep = false;
int active_format = 0;
foreach (var fmt in sorted_formats) {
if (fmt.Order == -1 && !have_sep) {
have_sep = true;
if (format_list.Model.IterNChildren () > 0) {
format_list.AppendText ("---");
}
}
format_list.AppendText (fmt.Format);
if (active_format == 0 && fmt.Format == item.SelectedFormat) {
active_format = format_list.Model.IterNChildren () - 1;
}
}
format_list.Changed += (o, a) => {
files_model.Clear ();
var selected_fmt = format_list.ActiveText;
foreach (var track in tracks) {
if (track.MimeType == selected_fmt) {
files_model.Add (track);
}
}
files_model.Reload ();
item.SelectedFormat = selected_fmt;
item.Save ();
};
if (formats.Count > 0) {
format_list.Active = active_format;
}
vbox.PackStart (file_sw, true, true, 0);
vbox.PackStart (format_list, false, false, 0);
file_list.SizeAllocated += (o, a) => {
int target_list_width = file_list.MaxWidth;
if (file_sw.VScrollbar != null && file_sw.VScrollbar.IsMapped) {
target_list_width += file_sw.VScrollbar.Allocation.Width + 2;
}
// Don't let the track list be too wide
target_list_width = Math.Min (target_list_width, (int) (0.5 * (double)Allocation.Width));
if (a.Allocation.Width != target_list_width && target_list_width > 0) {
file_sw.SetSizeRequest (target_list_width, -1);
}
};
PackStart (vbox, false, false, 0);
}
private void SetWidth<T> (Column col, T max, T zero)
{
(col.GetCell (0) as ColumnCellText).SetMinMaxStrings (max, max);
if (zero.Equals (max)) {
col.Visible = false;
}
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
//Authors: Roman Ivantsov - initial implementation and some later edits
// Philipp Serr - implementation of advanced features for c#, python, VB
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Diagnostics;
using Irony.Ast;
namespace Irony.Parsing {
using BigInteger = System.Numerics.BigInteger; //Microsoft.Scripting.Math.BigInteger;
using Complex64 = System.Numerics.Complex;
using Irony.Ast; // Microsoft.Scripting.Math.Complex64;
[Flags]
public enum NumberOptions {
None = 0,
Default = None,
AllowStartEndDot = 0x01, //python : http://docs.python.org/ref/floating.html
IntOnly = 0x02,
NoDotAfterInt = 0x04, //for use with IntOnly flag; essentially tells terminal to avoid matching integer if
// it is followed by dot (or exp symbol) - leave to another terminal that will handle float numbers
AllowSign = 0x08,
DisableQuickParse = 0x10,
AllowLetterAfter = 0x20, // allow number be followed by a letter or underscore; by default this flag is not set, so "3a" would not be
// recognized as number followed by an identifier
AllowUnderscore = 0x40, // Ruby allows underscore inside number: 1_234
//The following should be used with base-identifying prefixes
Binary = 0x0100, //e.g. GNU GCC C Extension supports binary number literals
Octal = 0x0200,
Hex = 0x0400,
}
public class NumberLiteral : CompoundTerminalBase {
//Flags for internal use
public enum NumberFlagsInternal : short {
HasDot = 0x1000,
HasExp = 0x2000,
}
//nested helper class
public class ExponentsTable : Dictionary<char, TypeCode> { }
#region Public Consts
//currently using TypeCodes for identifying numeric types
public const TypeCode TypeCodeBigInt = (TypeCode)30;
public const TypeCode TypeCodeImaginary = (TypeCode)31;
#endregion
#region constructors and initialization
public NumberLiteral(string name) : this(name, NumberOptions.Default) {
}
public NumberLiteral(string name, NumberOptions options, Type astNodeType) : this(name, options) {
base.AstConfig.NodeType = astNodeType;
}
public NumberLiteral(string name, NumberOptions options, AstNodeCreator astNodeCreator) : this(name, options) {
base.AstConfig.NodeCreator = astNodeCreator;
}
public NumberLiteral(string name, NumberOptions options) : base(name) {
Options = options;
base.SetFlag(TermFlags.IsLiteral);
}
public void AddPrefix(string prefix, NumberOptions options) {
PrefixFlags.Add(prefix, (short) options);
Prefixes.Add(prefix);
}
public void AddExponentSymbols(string symbols, TypeCode floatType) {
foreach(var exp in symbols)
_exponentsTable[exp] = floatType;
}
#endregion
#region Public fields/properties: ExponentSymbols, Suffixes
public NumberOptions Options;
public char DecimalSeparator = '.';
//Default types are assigned to literals without suffixes; first matching type used
public TypeCode[] DefaultIntTypes = new TypeCode[] { TypeCode.Int32 };
public TypeCode DefaultFloatType = TypeCode.Double;
private readonly ExponentsTable _exponentsTable = new ExponentsTable();
public bool IsSet(NumberOptions option) {
return (Options & option) != 0;
}
#endregion
#region Private fields: _quickParseTerminators
#endregion
#region overrides
public override void Init(GrammarData grammarData) {
base.Init(grammarData);
//Default Exponent symbols if table is empty
if(_exponentsTable.Count == 0 && !IsSet(NumberOptions.IntOnly)) {
_exponentsTable['e'] = DefaultFloatType;
_exponentsTable['E'] = DefaultFloatType;
}
if (this.EditorInfo == null)
this.EditorInfo = new TokenEditorInfo(TokenType.Literal, TokenColor.Number, TokenTriggers.None);
}
public override IList<string> GetFirsts() {
StringList result = new StringList();
result.AddRange(base.Prefixes);
//we assume that prefix is always optional, so number can always start with plain digit
result.AddRange(new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" });
// Python float numbers can start with a dot
if (IsSet(NumberOptions.AllowStartEndDot))
result.Add(DecimalSeparator.ToString());
if (IsSet(NumberOptions.AllowSign))
result.AddRange(new string[] {"-", "+"} );
return result;
}
//Most numbers in source programs are just one-digit instances of 0, 1, 2, and maybe others until 9
// so we try to do a quick parse for these, without starting the whole general process
protected override Token QuickParse(ParsingContext context, ISourceStream source) {
if (IsSet(NumberOptions.DisableQuickParse)) return null;
char current = source.PreviewChar;
//it must be a digit followed by a whitespace or delimiter
if (!char.IsDigit(current)) return null;
if (!Grammar.IsWhitespaceOrDelimiter(source.NextPreviewChar))
return null;
int iValue = current - '0';
object value = null;
switch (DefaultIntTypes[0]) {
case TypeCode.Int32: value = iValue; break;
case TypeCode.UInt32: value = (UInt32)iValue; break;
case TypeCode.Byte: value = (byte)iValue; break;
case TypeCode.SByte: value = (sbyte) iValue; break;
case TypeCode.Int16: value = (Int16)iValue; break;
case TypeCode.UInt16: value = (UInt16)iValue; break;
default: return null;
}
source.PreviewPosition++;
return source.CreateToken(this.OutputTerminal, value);
}
protected override void InitDetails(ParsingContext context, CompoundTokenDetails details) {
base.InitDetails(context, details);
details.Flags = (short) this.Options;
}
protected override void ReadPrefix(ISourceStream source, CompoundTokenDetails details) {
//check that is not a 0 followed by dot;
//this may happen in Python for number "0.123" - we can mistakenly take "0" as octal prefix
if (source.PreviewChar == '0' && source.NextPreviewChar == '.') return;
base.ReadPrefix(source, details);
}//method
protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details) {
//remember start - it may be different from source.TokenStart, we may have skipped prefix
int start = source.PreviewPosition;
char current = source.PreviewChar;
if (IsSet(NumberOptions.AllowSign) && (current == '-' || current == '+')) {
details.Sign = current.ToString();
source.PreviewPosition++;
}
//Figure out digits set
string digits = GetDigits(details);
bool isDecimal = !details.IsSet((short) (NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex));
bool allowFloat = !IsSet(NumberOptions.IntOnly);
bool foundDigits = false;
while (!source.EOF()) {
current = source.PreviewChar;
//1. If it is a digit, just continue going; the same for '_' if it is allowed
if (digits.IndexOf(current) >= 0 || IsSet(NumberOptions.AllowUnderscore) && current == '_') {
source.PreviewPosition++;
foundDigits = true;
continue;
}
//2. Check if it is a dot in float number
bool isDot = current == DecimalSeparator;
if (allowFloat && isDot) {
//If we had seen already a dot or exponent, don't accept this one;
bool hasDotOrExp = details.IsSet((short) (NumberFlagsInternal.HasDot | NumberFlagsInternal.HasExp));
if (hasDotOrExp) break; //from while loop
//In python number literals (NumberAllowPointFloat) a point can be the first and last character,
//We accept dot only if it is followed by a digit
if (digits.IndexOf(source.NextPreviewChar) < 0 && !IsSet(NumberOptions.AllowStartEndDot))
break; //from while loop
details.Flags |= (int) NumberFlagsInternal.HasDot;
source.PreviewPosition++;
continue;
}
//3. Check if it is int number followed by dot or exp symbol
bool isExpSymbol = (details.ExponentSymbol == null) && _exponentsTable.ContainsKey(current);
if (!allowFloat && foundDigits && (isDot || isExpSymbol)) {
//If no partial float allowed then return false - it is not integer, let float terminal recognize it as float
if (IsSet(NumberOptions.NoDotAfterInt)) return false;
//otherwise break, it is integer and we're done reading digits
break;
}
//4. Only for decimals - check if it is (the first) exponent symbol
if (allowFloat && isDecimal && isExpSymbol) {
char next = source.NextPreviewChar;
bool nextIsSign = next == '-' || next == '+';
bool nextIsDigit = digits.IndexOf(next) >= 0;
if (!nextIsSign && !nextIsDigit)
break; //Exponent should be followed by either sign or digit
//ok, we've got real exponent
details.ExponentSymbol = current.ToString(); //remember the exp char
details.Flags |= (int) NumberFlagsInternal.HasExp;
source.PreviewPosition++;
if (nextIsSign)
source.PreviewPosition++; //skip +/- explicitly so we don't have to deal with them on the next iteration
continue;
}
//4. It is something else (not digit, not dot or exponent) - we're done
break; //from while loop
}//while
int end = source.PreviewPosition;
if (!foundDigits)
return false;
details.Body = source.Text.Substring(start, end - start);
return true;
}
protected internal override void OnValidateToken(ParsingContext context) {
if (!IsSet(NumberOptions.AllowLetterAfter)) {
var current = context.Source.PreviewChar;
if(char.IsLetter(current) || current == '_') {
context.CurrentToken = context.CreateErrorToken(Resources.ErrNoLetterAfterNum); // "Number cannot be followed by a letter."
}
}
base.OnValidateToken(context);
}
protected override bool ConvertValue(CompoundTokenDetails details) {
if (String.IsNullOrEmpty(details.Body)) {
details.Error = Resources.ErrInvNumber; // "Invalid number.";
return false;
}
AssignTypeCodes(details);
//check for underscore
if (IsSet(NumberOptions.AllowUnderscore) && details.Body.Contains("_"))
details.Body = details.Body.Replace("_", string.Empty);
//Try quick paths
switch (details.TypeCodes[0]) {
case TypeCode.Int32:
if (QuickConvertToInt32(details)) return true;
break;
case TypeCode.Double:
if (QuickConvertToDouble(details)) return true;
break;
}
//Go full cycle
details.Value = null;
foreach (TypeCode typeCode in details.TypeCodes) {
switch (typeCode) {
case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: case TypeCodeImaginary:
return ConvertToFloat(typeCode, details);
case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16:
case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64:
if (details.Value == null) //if it is not done yet
TryConvertToLong(details, typeCode == TypeCode.UInt64); //try to convert to Long/Ulong and place the result into details.Value field;
if(TryCastToIntegerType(typeCode, details)) //now try to cast the ULong value to the target type
return true;
break;
case TypeCodeBigInt:
if (ConvertToBigInteger(details)) return true;
break;
}//switch
}
return false;
}//method
private void AssignTypeCodes(CompoundTokenDetails details) {
//Type could be assigned when we read suffix; if so, just exit
if (details.TypeCodes != null) return;
//Decide on float types
var hasDot = details.IsSet((short)(NumberFlagsInternal.HasDot));
var hasExp = details.IsSet((short)(NumberFlagsInternal.HasExp));
var isFloat = (hasDot || hasExp);
if (!isFloat) {
details.TypeCodes = DefaultIntTypes;
return;
}
//so we have a float. If we have exponent symbol then use it to select type
if (hasExp) {
TypeCode code;
if (_exponentsTable.TryGetValue(details.ExponentSymbol[0], out code)) {
details.TypeCodes = new TypeCode[] {code};
return;
}
}//if hasExp
//Finally assign default float type
details.TypeCodes = new TypeCode[] {DefaultFloatType};
}
#endregion
#region private utilities
private static bool QuickConvertToInt32(CompoundTokenDetails details) {
int radix = GetRadix(details);
if (radix == 10 && details.Body.Length > 10) return false; //10 digits is maximum for int32; int32.MaxValue = 2 147 483 647
try {
//workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
int iValue = 0;
if (radix == 10)
iValue = Convert.ToInt32(details.Body, CultureInfo.InvariantCulture);
else
iValue = Convert.ToInt32(details.Body, radix);
details.Value = iValue;
return true;
} catch {
return false;
}
}//method
private bool QuickConvertToDouble(CompoundTokenDetails details) {
if (details.IsSet((short)(NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex))) return false;
if (details.IsSet((short)(NumberFlagsInternal.HasExp))) return false;
if (DecimalSeparator != '.') return false;
double dvalue;
if (!double.TryParse(details.Body, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out dvalue)) return false;
details.Value = dvalue;
return true;
}
private bool ConvertToFloat(TypeCode typeCode, CompoundTokenDetails details) {
//only decimal numbers can be fractions
if (details.IsSet((short)(NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex))) {
details.Error = Resources.ErrInvNumber; // "Invalid number.";
return false;
}
string body = details.Body;
//Some languages allow exp symbols other than E. Check if it is the case, and change it to E
// - otherwise .NET conversion methods may fail
if (details.IsSet((short)NumberFlagsInternal.HasExp) && details.ExponentSymbol.ToUpper() != "E")
body = body.Replace(details.ExponentSymbol, "E");
//'.' decimal seperator required by invariant culture
if (details.IsSet((short)NumberFlagsInternal.HasDot) && DecimalSeparator != '.')
body = body.Replace(DecimalSeparator, '.');
switch (typeCode) {
case TypeCode.Double:
case TypeCodeImaginary:
double dValue;
if (!Double.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out dValue)) return false;
if (typeCode == TypeCodeImaginary)
details.Value = new Complex64(0, dValue);
else
details.Value = dValue;
return true;
case TypeCode.Single:
float fValue;
if (!Single.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out fValue)) return false;
details.Value = fValue;
return true;
case TypeCode.Decimal:
decimal decValue;
if (!Decimal.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out decValue)) return false;
details.Value = decValue;
return true;
}//switch
return false;
}
private static bool TryCastToIntegerType(TypeCode typeCode, CompoundTokenDetails details) {
if (details.Value == null) return false;
try {
if (typeCode != TypeCode.UInt64)
details.Value = Convert.ChangeType(details.Value, typeCode, CultureInfo.InvariantCulture);
return true;
} catch (Exception) {
details.Error = string.Format(Resources.ErrCannotConvertValueToType, details.Value, typeCode.ToString());
return false;
}
}//method
private static bool TryConvertToLong(CompoundTokenDetails details, bool useULong) {
try {
int radix = GetRadix(details);
//workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
if (radix == 10)
if (useULong)
details.Value = Convert.ToUInt64(details.Body, CultureInfo.InvariantCulture);
else
details.Value = Convert.ToInt64(details.Body, CultureInfo.InvariantCulture);
else
if (useULong)
details.Value = Convert.ToUInt64(details.Body, radix);
else
details.Value = Convert.ToInt64(details.Body, radix);
return true;
} catch(OverflowException) {
details.Error = string.Format(Resources.ErrCannotConvertValueToType, details.Value, TypeCode.Int64.ToString());
return false;
}
}
private static bool ConvertToBigInteger(CompoundTokenDetails details) {
//ignore leading zeros and sign
details.Body = details.Body.TrimStart('+').TrimStart('-').TrimStart('0');
if (string.IsNullOrEmpty(details.Body))
details.Body = "0";
int bodyLength = details.Body.Length;
int radix = GetRadix(details);
int wordLength = GetSafeWordLength(details);
int sectionCount = GetSectionCount(bodyLength, wordLength);
ulong[] numberSections = new ulong[sectionCount]; //big endian
try {
int startIndex = details.Body.Length - wordLength;
for (int sectionIndex = sectionCount - 1; sectionIndex >= 0; sectionIndex--) {
if (startIndex < 0) {
wordLength += startIndex;
startIndex = 0;
}
//workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
if (radix == 10)
numberSections[sectionIndex] = Convert.ToUInt64(details.Body.Substring(startIndex, wordLength));
else
numberSections[sectionIndex] = Convert.ToUInt64(details.Body.Substring(startIndex, wordLength), radix);
startIndex -= wordLength;
}
} catch {
details.Error = Resources.ErrInvNumber;// "Invalid number.";
return false;
}
//produce big integer
ulong safeWordRadix = GetSafeWordRadix(details);
BigInteger bigIntegerValue = numberSections[0];
for (int i = 1; i < sectionCount; i++)
bigIntegerValue = checked(bigIntegerValue * safeWordRadix + numberSections[i]);
if (details.Sign == "-")
bigIntegerValue = -bigIntegerValue;
details.Value = bigIntegerValue;
return true;
}
private static int GetRadix(CompoundTokenDetails details) {
if (details.IsSet((short)NumberOptions.Hex))
return 16;
if (details.IsSet((short)NumberOptions.Octal))
return 8;
if (details.IsSet((short)NumberOptions.Binary))
return 2;
return 10;
}
private static string GetDigits(CompoundTokenDetails details) {
if (details.IsSet((short)NumberOptions.Hex))
return Strings.HexDigits;
if (details.IsSet((short)NumberOptions.Octal))
return Strings.OctalDigits;
if (details.IsSet((short)NumberOptions.Binary))
return Strings.BinaryDigits;
return Strings.DecimalDigits;
}
private static int GetSafeWordLength(CompoundTokenDetails details) {
if (details.IsSet((short)NumberOptions.Hex))
return 15;
if (details.IsSet((short)NumberOptions.Octal))
return 21; //maxWordLength 22
if (details.IsSet((short)NumberOptions.Binary))
return 63;
return 19; //maxWordLength 20
}
private static int GetSectionCount(int stringLength, int safeWordLength) {
int quotient = stringLength / safeWordLength;
int remainder = stringLength - quotient * safeWordLength;
return remainder == 0 ? quotient : quotient + 1;
}
//radix^safeWordLength
private static ulong GetSafeWordRadix(CompoundTokenDetails details) {
if (details.IsSet((short)NumberOptions.Hex))
return 1152921504606846976;
if (details.IsSet((short)NumberOptions.Octal))
return 9223372036854775808;
if (details.IsSet((short) NumberOptions.Binary))
return 9223372036854775808;
return 10000000000000000000;
}
private static bool IsIntegerCode(TypeCode code) {
return (code >= TypeCode.SByte && code <= TypeCode.UInt64);
}
#endregion
}//class
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace LocationApplication.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2007 Roger Hill
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;
namespace DAL.Core
{
public sealed class Database : IDatabase
{
private const string EMPTY_QUERY_STRING = "Query string is null or empty";
private const string EMPTY_CONNECTION_STRING = "Connection string is null or empty";
private const string NULL_PROCESSOR_METHOD = "Processor method is null";
private const string DEFAULT_CONNECTION_STRING = "Data Source=Localhost;Initial Catalog=Master;Integrated Security=SSPI;Connect Timeout=1;";
private const string EXCEPTION_SQL_PREFIX = "Sql.Parameter";
private const string EXCEPTION_KEY_QUERY = "Sql.Query";
private const string EXCEPTION_KEY_CONNECTION = "Sql.ConnectionString";
private readonly string _Connection;
private readonly bool _LogConnection;
private readonly bool _LogParameters;
private readonly bool _ThrowUnmappedFieldsError;
public Database() : this(DEFAULT_CONNECTION_STRING) { }
/// <summary>
/// CTOR for Database object
/// </summary>
/// <param name="connection">A sql connection string.</param>
/// <param name="logConnection">Allow connection string to be included in thrown exceptions. Defaults to false.</param>
/// <param name="logParameters">Allow query parameters to be included in thrown exceptions. Defaults to false.</param>
public Database(string connection, bool logConnection = false, bool logParameters = false, bool throwUnmappedFieldsError = true)
{
if (string.IsNullOrWhiteSpace(connection))
throw new ArgumentNullException(EMPTY_CONNECTION_STRING);
_Connection = connection;
_LogConnection = logConnection;
_LogParameters = logParameters;
_ThrowUnmappedFieldsError = throwUnmappedFieldsError;
}
public DataTable ExecuteQuery(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteQuery(sqlQuery, parameters, _Connection, false);
}
public DataTable ExecuteQuerySp(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteQuery(sqlQuery, parameters, _Connection, true);
}
public List<T> ExecuteQuery<T>(string sqlQuery, IList<SqlParameter> parameters) where T : class, new()
{
return ExecuteQuery<T>(sqlQuery, parameters, _Connection, false);
}
public T ExecuteQuery<T>(string sqlQuery, IList<SqlParameter> parameters, Func<SqlDataReader, T> processor)
{
return ExecuteQuery<T>(sqlQuery, parameters, _Connection, false, processor);
}
public List<T> ExecuteQuerySp<T>(string sqlQuery, IList<SqlParameter> parameters) where T : class, new()
{
return ExecuteQuery<T>(sqlQuery, parameters, _Connection, true);
}
public T ExecuteQuerySp<T>(string sqlQuery, IList<SqlParameter> parameters, Func<SqlDataReader, T> processor)
{
return ExecuteQuery<T>(sqlQuery, parameters, _Connection, true, processor);
}
public int ExecuteNonQuery(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteNonQuery(sqlQuery, parameters, _Connection, false);
}
public int ExecuteNonQuerySp(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteNonQuery(sqlQuery, parameters, _Connection, true);
}
public T ExecuteScalar<T>(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteScalar<T>(sqlQuery, parameters, _Connection, false);
}
public T ExecuteScalarSp<T>(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteScalar<T>(sqlQuery, parameters, _Connection, true);
}
public DataTable GetSchema()
{
using (SqlConnection conn = new SqlConnection(_Connection))
{
DataTable dt = null;
conn.Open();
dt = conn.GetSchema("Databases");
conn.Close();
return dt;
}
}
private DataTable ExecuteQuery(string sqlQuery, IList<SqlParameter> parameters, string connection, bool storedProcedure)
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
try
{
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
cmd.CommandType = (storedProcedure) ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
cmd.Parameters.Add(parameter);
}
#if (DEBUG)
string SqlDebugString = GenerateSqlDebugString(sqlQuery, parameters);
#endif
var dt = new DataTable();
conn.Open();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
conn.Close();
if (parameters != null)
{
for (int i = 0; i < cmd.Parameters.Count; i++)
parameters[i].Value = cmd.Parameters[i].Value;
}
return dt;
}
}
}
}
catch (Exception ex)
{
ex.Data.Add(EXCEPTION_KEY_QUERY, sqlQuery);
if (_LogConnection)
ex.Data.Add(EXCEPTION_KEY_CONNECTION, connection);
if (_LogParameters && parameters != null)
{
for (int i = 0; i < parameters.Count; i++)
ex.Data.Add($"{EXCEPTION_SQL_PREFIX}{i + 1}", $"{parameters[i].ParameterName} = {parameters[i].Value}");
}
throw ex;
}
}
private List<T> ExecuteQuery<T>(string sqlQuery, IList<SqlParameter> parameters, string connection, bool storedProcedure) where T : class, new()
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
try
{
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
cmd.CommandType = (storedProcedure) ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
cmd.Parameters.Add(parameter);
}
#if (DEBUG)
string SqlDebugString = GenerateSqlDebugString(sqlQuery, parameters);
#endif
conn.Open();
using (SqlDataReader data_reader = cmd.ExecuteReader())
{
var output = ParseDatareaderResult<T>(data_reader, _ThrowUnmappedFieldsError);
if (parameters != null)
{
for (int i = 0; i < cmd.Parameters.Count; i++)
parameters[i].Value = cmd.Parameters[i].Value;
}
data_reader.Close();
conn.Close();
return output;
}
}
}
}
catch (Exception ex)
{
ex.Data.Add(EXCEPTION_KEY_QUERY, sqlQuery);
if (_LogConnection)
ex.Data.Add(EXCEPTION_KEY_CONNECTION, connection);
if (_LogParameters && parameters != null)
{
for (int i = 0; i < parameters.Count; i++)
ex.Data.Add($"{EXCEPTION_SQL_PREFIX}{i + 1}", $"{parameters[i].ParameterName} = {parameters[i].Value}");
}
throw ex;
}
}
private T ExecuteQuery<T>(string sqlQuery, IList<SqlParameter> parameters, string connection, bool storedProcedure, Func<SqlDataReader, T> processor)
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
if (processor == null)
throw new ArgumentNullException(NULL_PROCESSOR_METHOD);
try
{
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
cmd.CommandType = (storedProcedure) ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
cmd.Parameters.Add(parameter);
}
#if (DEBUG)
string SqlDebugString = GenerateSqlDebugString(sqlQuery, parameters);
#endif
conn.Open();
using (SqlDataReader data_reader = cmd.ExecuteReader())
{
var output = processor.Invoke(data_reader);
if (parameters != null)
{
for (int i = 0; i < cmd.Parameters.Count; i++)
parameters[i].Value = cmd.Parameters[i].Value;
}
data_reader.Close();
conn.Close();
return output;
}
}
}
}
catch (Exception ex)
{
ex.Data.Add(EXCEPTION_KEY_QUERY, sqlQuery);
if (_LogConnection)
ex.Data.Add(EXCEPTION_KEY_CONNECTION, connection);
if (_LogParameters && parameters != null)
{
for (int i = 0; i < parameters.Count; i++)
ex.Data.Add($"{EXCEPTION_SQL_PREFIX}{i + 1}", $"{parameters[i].ParameterName} = {parameters[i].Value}");
}
throw ex;
}
}
private int ExecuteNonQuery(string sqlQuery, IList<SqlParameter> parameters, string connection, bool storedProcedure)
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
if (string.IsNullOrWhiteSpace(connection))
throw new ArgumentNullException(EMPTY_CONNECTION_STRING);
try
{
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
cmd.CommandType = (storedProcedure) ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
cmd.Parameters.Add(parameter);
}
#if (DEBUG)
string SqlDebugString = GenerateSqlDebugString(sqlQuery, parameters);
#endif
conn.Open();
int results = cmd.ExecuteNonQuery();
conn.Close();
if (parameters != null)
{
for (int i = 0; i < cmd.Parameters.Count; i++)
parameters[i].Value = cmd.Parameters[i].Value;
}
return results;
}
}
}
catch (Exception ex)
{
ex.Data.Add(EXCEPTION_KEY_QUERY, sqlQuery);
if (_LogConnection)
ex.Data.Add(EXCEPTION_KEY_CONNECTION, connection);
if (_LogParameters && parameters != null)
{
for (int i = 0; i < parameters.Count; i++)
ex.Data.Add($"{EXCEPTION_SQL_PREFIX}{i + 1}", $"{parameters[i].ParameterName} = {parameters[i].Value}");
}
throw ex;
}
}
private T ExecuteScalar<T>(string sqlQuery, IList<SqlParameter> parameters, string connection, bool storedProcedure)
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
try
{
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
T results = default;
cmd.CommandType = (storedProcedure) ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
cmd.Parameters.Add(parameter);
}
#if (DEBUG)
string SqlDebugString = GenerateSqlDebugString(sqlQuery, parameters);
#endif
conn.Open();
object buffer = cmd.ExecuteScalar();
if (buffer == null)
{
results = default;
}
else
{
if (buffer.GetType() == typeof(DBNull))
results = default;
else if (buffer is T)
return (T)buffer;
else
return (T)Convert.ChangeType(buffer, typeof(T));
}
conn.Close();
if (parameters != null)
{
for (int i = 0; i < cmd.Parameters.Count; i++)
parameters[i].Value = cmd.Parameters[i].Value;
}
return results;
}
}
}
catch (Exception ex)
{
ex.Data.Add(EXCEPTION_KEY_QUERY, sqlQuery);
if (_LogConnection)
ex.Data.Add(EXCEPTION_KEY_CONNECTION, connection);
if (_LogParameters && parameters != null)
{
for (int i = 0; i < parameters.Count; i++)
ex.Data.Add($"{EXCEPTION_SQL_PREFIX}{i + 1}", $"{parameters[i].ParameterName} = {parameters[i].Value}");
}
throw ex;
}
}
/// <summary>
/// Converts a list of IEnumerable objects to a string of comma delimited items. If a quote_character
/// is defined, this will wrap each item with the character(s) passed.
/// </summary>
public static string GenericListToStringList<T>(IEnumerable<T> list, string quoteCharacter = null, string quoteEscapeCharacter = null)
{
if (list == null)
throw new ArgumentNullException("Cannot convert a null IEnumerable object");
var sb = new StringBuilder();
bool firstFlag = true;
foreach (T item in list)
{
if (firstFlag)
firstFlag = false;
else
sb.Append(",");
if (item == null)
{
sb.Append("null");
}
else
{
string buffer = item.ToString();
if (!string.IsNullOrWhiteSpace(quoteEscapeCharacter))
buffer = buffer.Replace(quoteCharacter, quoteEscapeCharacter);
if (!string.IsNullOrWhiteSpace(quoteCharacter))
sb.Append(quoteCharacter + buffer + quoteCharacter);
else
sb.Append(buffer);
}
}
return sb.ToString();
}
/// <summary>
/// Method creates sql debugging strings with parameterized argument lists
/// </summary>
private string GenerateSqlDebugString(string sqlQuery, IList<SqlParameter> parameterList)
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
if (parameterList == null || parameterList.Count == 0)
return sqlQuery;
var value_list = new List<string>();
foreach (var item in parameterList)
{
if (item.Direction == ParameterDirection.ReturnValue)
continue;
if (item.IsNullable)
{
value_list.Add($"{item.ParameterName} = null");
}
else
{
switch (item.SqlDbType)
{
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.Text:
case SqlDbType.NText:
case SqlDbType.NVarChar:
case SqlDbType.VarChar:
case SqlDbType.UniqueIdentifier:
case SqlDbType.DateTime:
case SqlDbType.Date:
case SqlDbType.Time:
case SqlDbType.DateTime2:
value_list.Add($"@{item.ParameterName} = '{item.Value}'");
break;
default:
value_list.Add($"@{item.ParameterName} = {item.Value}");
break;
}
}
}
return $"{sqlQuery} {GenericListToStringList(value_list, null, null)}";
}
/// <summary>
/// This method performs automatic mapping between a data reader and a POCO object, mapping any values that
/// have properties names that match column names. It can be configured to throw exceptions if there isn't a 1:1 mapping.
/// </summary>
/// <returns></returns>
private List<T> ParseDatareaderResult<T>(SqlDataReader reader, bool throwUnmappedFieldsError) where T : class, new()
{
var outputType = typeof(T);
var results = new List<T>();
var propertyLookup = new Dictionary<string, PropertyInfo>();
foreach (var propertyInfo in outputType.GetProperties())
propertyLookup.Add(propertyInfo.Name, propertyInfo);
T new_object;
object fieldValue;
while (reader.Read())
{
new_object = new T();
for (int i = 0; i < reader.FieldCount; i++)
{
string columnName = reader.GetName(i);
if (propertyLookup.TryGetValue(columnName, out PropertyInfo propertyInfo))
{
Type propertyType = propertyInfo.PropertyType;
string propertyName = propertyInfo.PropertyType.FullName;
// in the event that we are looking at a nullable type, we need to look at the underlying type.
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyName = Nullable.GetUnderlyingType(propertyType).ToString();
propertyType = Nullable.GetUnderlyingType(propertyType);
}
switch (propertyName)
{
case "System.Int32":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as int? ?? null;
else
fieldValue = (int)reader[columnName];
break;
case "System.String":
if (reader[i] == DBNull.Value)
fieldValue = null;
else
fieldValue = (string)reader[columnName];
break;
case "System.Double":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as double? ?? null;
else
fieldValue = (double)reader[columnName];
break;
case "System.Float":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as float? ?? null;
else
fieldValue = (float)reader[columnName];
break;
case "System.Boolean":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as bool? ?? null;
else
fieldValue = (bool)reader[columnName];
break;
case "System.Boolean[]":
if (reader[i] == DBNull.Value)
{
fieldValue = null;
}
else
{
// inline conversion, blech. improve later.
var byteArray = (byte[])reader[i];
var boolArray = new bool[byteArray.Length];
for (int index = 0; index < byteArray.Length; index++)
boolArray[index] = Convert.ToBoolean(byteArray[index]);
fieldValue = boolArray;
}
break;
case "System.DateTime":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as DateTime? ?? null;
else
fieldValue = DateTime.Parse(reader[columnName].ToString());
break;
case "System.Guid":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as Guid? ?? null;
else
fieldValue = (Guid)reader[columnName];
break;
case "System.Single":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as float? ?? null;
else
fieldValue = float.Parse(reader[columnName].ToString());
break;
case "System.Decimal":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as decimal? ?? null;
else
fieldValue = (decimal)reader[columnName];
break;
case "System.Byte":
if (reader[i] == DBNull.Value)
fieldValue = null;
else
fieldValue = (byte)reader[columnName];
break;
case "System.Byte[]":
if (reader[i] == DBNull.Value)
{
fieldValue = null;
}
else
{
string byteArray = reader[columnName].ToString();
byte[] bytes = new byte[byteArray.Length * sizeof(char)];
Buffer.BlockCopy(byteArray.ToCharArray(), 0, bytes, 0, bytes.Length);
fieldValue = bytes;
}
break;
case "System.SByte":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as sbyte? ?? null;
else
fieldValue = (sbyte)reader[columnName];
break;
case "System.Char":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as char? ?? null;
else
fieldValue = (char)reader[columnName];
break;
case "System.UInt32":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as uint? ?? null;
else
fieldValue = (uint)reader[columnName];
break;
case "System.Int64":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as long? ?? null;
else
fieldValue = (long)reader[columnName];
break;
case "System.UInt64":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as ulong? ?? null;
else
fieldValue = (ulong)reader[columnName];
break;
case "System.Object":
if (reader[i] == DBNull.Value)
fieldValue = null;
else
fieldValue = reader[columnName];
break;
case "System.Int16":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as short? ?? null;
else
fieldValue = (short)reader[columnName];
break;
case "System.UInt16":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as ushort? ?? null;
else
fieldValue = (ushort)reader[columnName];
break;
case "System.Udt":
// no idea how to handle a custom type
throw new NotImplementedException("System.Udt is an unsupported datatype");
case "Microsoft.SqlServer.Types.SqlGeometry":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as Microsoft.SqlServer.Types.SqlGeometry ?? null;
else
fieldValue = (Microsoft.SqlServer.Types.SqlGeometry)reader[columnName];
break;
case "Microsoft.SqlServer.Types.SqlGeography":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as Microsoft.SqlServer.Types.SqlGeography ?? null;
else
fieldValue = (Microsoft.SqlServer.Types.SqlGeography)reader[columnName];
break;
default:
if (propertyType.IsEnum)
{
// enums are common, but don't fit into the above buckets.
if (reader[i] == DBNull.Value)
fieldValue = null;
else
fieldValue = Enum.ToObject(propertyType, reader[columnName]);
break;
}
else
{
throw new Exception($"Column '{propertyLookup[columnName]}' has an unknown data type: '{propertyLookup[columnName].PropertyType.FullName}'.");
}
}
propertyLookup[columnName].SetValue(new_object, fieldValue, null);
}
else
{
// found a row in data reader that cannot be mapped to a property in object.
// might be an error, but it is dependent on the specific use case.
if (throwUnmappedFieldsError)
{
throw new Exception($"Cannot map datareader field '{columnName}' to object property on object '{outputType}'");
}
}
}
results.Add(new_object);
}
return results;
}
private DataTable ConvertObjectToDataTable<T>(IEnumerable<T> input)
{
var dt = new DataTable();
var outputType = typeof(T);
var object_properties = outputType.GetProperties();
foreach (var propertyInfo in object_properties)
dt.Columns.Add(propertyInfo.Name);
foreach (var item in input)
{
var dr = dt.NewRow();
foreach (var property in object_properties)
dr[property.Name] = outputType.GetProperty(property.Name).GetValue(item, null);
dt.Rows.Add(dr);
}
return dt;
}
/// <summary>
/// Generates a SqlParameter object from a generic object list. This allows you to pass in a list of N
/// objects into a stored procedure as a single argument. The sqlTypeName type needs to exist in the db
/// however, and be of the correct type.
///
/// Sample: ConvertObjectCollectionToParameter("@Foo", "dbo.SomeUserType", a_generic_object_collection);
/// </summary>
public SqlParameter ConvertObjectCollectionToParameter<T>(string parameterName, string sqlTypeName, IEnumerable<T> input)
{
DataTable dt = ConvertObjectToDataTable(input);
var sql_parameter = new SqlParameter(parameterName, dt)
{
SqlDbType = SqlDbType.Structured,
TypeName = sqlTypeName
};
return sql_parameter;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Gaming.V1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedGameServerClustersServiceClientSnippets
{
/// <summary>Snippet for ListGameServerClusters</summary>
public void ListGameServerClustersRequestObject()
{
// Snippet: ListGameServerClusters(ListGameServerClustersRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
ListGameServerClustersRequest request = new ListGameServerClustersRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
Filter = "",
OrderBy = "",
View = GameServerClusterView.Unspecified,
};
// Make the request
PagedEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClusters(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (GameServerCluster item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGameServerClustersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerClustersAsync</summary>
public async Task ListGameServerClustersRequestObjectAsync()
{
// Snippet: ListGameServerClustersAsync(ListGameServerClustersRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
ListGameServerClustersRequest request = new ListGameServerClustersRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
Filter = "",
OrderBy = "",
View = GameServerClusterView.Unspecified,
};
// Make the request
PagedAsyncEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClustersAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((GameServerCluster item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGameServerClustersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerClusters</summary>
public void ListGameServerClusters()
{
// Snippet: ListGameServerClusters(string, string, int?, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
// Make the request
PagedEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClusters(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (GameServerCluster item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGameServerClustersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerClustersAsync</summary>
public async Task ListGameServerClustersAsync()
{
// Snippet: ListGameServerClustersAsync(string, string, int?, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
// Make the request
PagedAsyncEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClustersAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((GameServerCluster item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGameServerClustersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerClusters</summary>
public void ListGameServerClustersResourceNames()
{
// Snippet: ListGameServerClusters(RealmName, string, int?, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
RealmName parent = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
// Make the request
PagedEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClusters(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (GameServerCluster item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGameServerClustersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerClustersAsync</summary>
public async Task ListGameServerClustersResourceNamesAsync()
{
// Snippet: ListGameServerClustersAsync(RealmName, string, int?, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
RealmName parent = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
// Make the request
PagedAsyncEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClustersAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((GameServerCluster item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGameServerClustersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetGameServerCluster</summary>
public void GetGameServerClusterRequestObject()
{
// Snippet: GetGameServerCluster(GetGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
GetGameServerClusterRequest request = new GetGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
View = GameServerClusterView.Unspecified,
};
// Make the request
GameServerCluster response = gameServerClustersServiceClient.GetGameServerCluster(request);
// End snippet
}
/// <summary>Snippet for GetGameServerClusterAsync</summary>
public async Task GetGameServerClusterRequestObjectAsync()
{
// Snippet: GetGameServerClusterAsync(GetGameServerClusterRequest, CallSettings)
// Additional: GetGameServerClusterAsync(GetGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
GetGameServerClusterRequest request = new GetGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
View = GameServerClusterView.Unspecified,
};
// Make the request
GameServerCluster response = await gameServerClustersServiceClient.GetGameServerClusterAsync(request);
// End snippet
}
/// <summary>Snippet for GetGameServerCluster</summary>
public void GetGameServerCluster()
{
// Snippet: GetGameServerCluster(string, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]/gameServerClusters/[CLUSTER]";
// Make the request
GameServerCluster response = gameServerClustersServiceClient.GetGameServerCluster(name);
// End snippet
}
/// <summary>Snippet for GetGameServerClusterAsync</summary>
public async Task GetGameServerClusterAsync()
{
// Snippet: GetGameServerClusterAsync(string, CallSettings)
// Additional: GetGameServerClusterAsync(string, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]/gameServerClusters/[CLUSTER]";
// Make the request
GameServerCluster response = await gameServerClustersServiceClient.GetGameServerClusterAsync(name);
// End snippet
}
/// <summary>Snippet for GetGameServerCluster</summary>
public void GetGameServerClusterResourceNames()
{
// Snippet: GetGameServerCluster(GameServerClusterName, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
GameServerClusterName name = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]");
// Make the request
GameServerCluster response = gameServerClustersServiceClient.GetGameServerCluster(name);
// End snippet
}
/// <summary>Snippet for GetGameServerClusterAsync</summary>
public async Task GetGameServerClusterResourceNamesAsync()
{
// Snippet: GetGameServerClusterAsync(GameServerClusterName, CallSettings)
// Additional: GetGameServerClusterAsync(GameServerClusterName, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerClusterName name = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]");
// Make the request
GameServerCluster response = await gameServerClustersServiceClient.GetGameServerClusterAsync(name);
// End snippet
}
/// <summary>Snippet for CreateGameServerCluster</summary>
public void CreateGameServerClusterRequestObject()
{
// Snippet: CreateGameServerCluster(CreateGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
CreateGameServerClusterRequest request = new CreateGameServerClusterRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
GameServerClusterId = "",
GameServerCluster = new GameServerCluster(),
};
// Make the request
Operation<GameServerCluster, OperationMetadata> response = gameServerClustersServiceClient.CreateGameServerCluster(request);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceCreateGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerClusterAsync</summary>
public async Task CreateGameServerClusterRequestObjectAsync()
{
// Snippet: CreateGameServerClusterAsync(CreateGameServerClusterRequest, CallSettings)
// Additional: CreateGameServerClusterAsync(CreateGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
CreateGameServerClusterRequest request = new CreateGameServerClusterRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
GameServerClusterId = "",
GameServerCluster = new GameServerCluster(),
};
// Make the request
Operation<GameServerCluster, OperationMetadata> response = await gameServerClustersServiceClient.CreateGameServerClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceCreateGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerCluster</summary>
public void CreateGameServerCluster()
{
// Snippet: CreateGameServerCluster(string, GameServerCluster, string, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
GameServerCluster gameServerCluster = new GameServerCluster();
string gameServerClusterId = "";
// Make the request
Operation<GameServerCluster, OperationMetadata> response = gameServerClustersServiceClient.CreateGameServerCluster(parent, gameServerCluster, gameServerClusterId);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceCreateGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerClusterAsync</summary>
public async Task CreateGameServerClusterAsync()
{
// Snippet: CreateGameServerClusterAsync(string, GameServerCluster, string, CallSettings)
// Additional: CreateGameServerClusterAsync(string, GameServerCluster, string, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
GameServerCluster gameServerCluster = new GameServerCluster();
string gameServerClusterId = "";
// Make the request
Operation<GameServerCluster, OperationMetadata> response = await gameServerClustersServiceClient.CreateGameServerClusterAsync(parent, gameServerCluster, gameServerClusterId);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceCreateGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerCluster</summary>
public void CreateGameServerClusterResourceNames()
{
// Snippet: CreateGameServerCluster(RealmName, GameServerCluster, string, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
RealmName parent = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
GameServerCluster gameServerCluster = new GameServerCluster();
string gameServerClusterId = "";
// Make the request
Operation<GameServerCluster, OperationMetadata> response = gameServerClustersServiceClient.CreateGameServerCluster(parent, gameServerCluster, gameServerClusterId);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceCreateGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerClusterAsync</summary>
public async Task CreateGameServerClusterResourceNamesAsync()
{
// Snippet: CreateGameServerClusterAsync(RealmName, GameServerCluster, string, CallSettings)
// Additional: CreateGameServerClusterAsync(RealmName, GameServerCluster, string, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
RealmName parent = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
GameServerCluster gameServerCluster = new GameServerCluster();
string gameServerClusterId = "";
// Make the request
Operation<GameServerCluster, OperationMetadata> response = await gameServerClustersServiceClient.CreateGameServerClusterAsync(parent, gameServerCluster, gameServerClusterId);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceCreateGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PreviewCreateGameServerCluster</summary>
public void PreviewCreateGameServerClusterRequestObject()
{
// Snippet: PreviewCreateGameServerCluster(PreviewCreateGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
PreviewCreateGameServerClusterRequest request = new PreviewCreateGameServerClusterRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
GameServerClusterId = "",
GameServerCluster = new GameServerCluster(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewCreateGameServerClusterResponse response = gameServerClustersServiceClient.PreviewCreateGameServerCluster(request);
// End snippet
}
/// <summary>Snippet for PreviewCreateGameServerClusterAsync</summary>
public async Task PreviewCreateGameServerClusterRequestObjectAsync()
{
// Snippet: PreviewCreateGameServerClusterAsync(PreviewCreateGameServerClusterRequest, CallSettings)
// Additional: PreviewCreateGameServerClusterAsync(PreviewCreateGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
PreviewCreateGameServerClusterRequest request = new PreviewCreateGameServerClusterRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
GameServerClusterId = "",
GameServerCluster = new GameServerCluster(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewCreateGameServerClusterResponse response = await gameServerClustersServiceClient.PreviewCreateGameServerClusterAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteGameServerCluster</summary>
public void DeleteGameServerClusterRequestObject()
{
// Snippet: DeleteGameServerCluster(DeleteGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
DeleteGameServerClusterRequest request = new DeleteGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = gameServerClustersServiceClient.DeleteGameServerCluster(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceDeleteGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerClusterAsync</summary>
public async Task DeleteGameServerClusterRequestObjectAsync()
{
// Snippet: DeleteGameServerClusterAsync(DeleteGameServerClusterRequest, CallSettings)
// Additional: DeleteGameServerClusterAsync(DeleteGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteGameServerClusterRequest request = new DeleteGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = await gameServerClustersServiceClient.DeleteGameServerClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceDeleteGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerCluster</summary>
public void DeleteGameServerCluster()
{
// Snippet: DeleteGameServerCluster(string, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]/gameServerClusters/[CLUSTER]";
// Make the request
Operation<Empty, OperationMetadata> response = gameServerClustersServiceClient.DeleteGameServerCluster(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceDeleteGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerClusterAsync</summary>
public async Task DeleteGameServerClusterAsync()
{
// Snippet: DeleteGameServerClusterAsync(string, CallSettings)
// Additional: DeleteGameServerClusterAsync(string, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]/gameServerClusters/[CLUSTER]";
// Make the request
Operation<Empty, OperationMetadata> response = await gameServerClustersServiceClient.DeleteGameServerClusterAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceDeleteGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerCluster</summary>
public void DeleteGameServerClusterResourceNames()
{
// Snippet: DeleteGameServerCluster(GameServerClusterName, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
GameServerClusterName name = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]");
// Make the request
Operation<Empty, OperationMetadata> response = gameServerClustersServiceClient.DeleteGameServerCluster(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceDeleteGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerClusterAsync</summary>
public async Task DeleteGameServerClusterResourceNamesAsync()
{
// Snippet: DeleteGameServerClusterAsync(GameServerClusterName, CallSettings)
// Additional: DeleteGameServerClusterAsync(GameServerClusterName, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerClusterName name = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]");
// Make the request
Operation<Empty, OperationMetadata> response = await gameServerClustersServiceClient.DeleteGameServerClusterAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceDeleteGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PreviewDeleteGameServerCluster</summary>
public void PreviewDeleteGameServerClusterRequestObject()
{
// Snippet: PreviewDeleteGameServerCluster(PreviewDeleteGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
PreviewDeleteGameServerClusterRequest request = new PreviewDeleteGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewDeleteGameServerClusterResponse response = gameServerClustersServiceClient.PreviewDeleteGameServerCluster(request);
// End snippet
}
/// <summary>Snippet for PreviewDeleteGameServerClusterAsync</summary>
public async Task PreviewDeleteGameServerClusterRequestObjectAsync()
{
// Snippet: PreviewDeleteGameServerClusterAsync(PreviewDeleteGameServerClusterRequest, CallSettings)
// Additional: PreviewDeleteGameServerClusterAsync(PreviewDeleteGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
PreviewDeleteGameServerClusterRequest request = new PreviewDeleteGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewDeleteGameServerClusterResponse response = await gameServerClustersServiceClient.PreviewDeleteGameServerClusterAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateGameServerCluster</summary>
public void UpdateGameServerClusterRequestObject()
{
// Snippet: UpdateGameServerCluster(UpdateGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
UpdateGameServerClusterRequest request = new UpdateGameServerClusterRequest
{
GameServerCluster = new GameServerCluster(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<GameServerCluster, OperationMetadata> response = gameServerClustersServiceClient.UpdateGameServerCluster(request);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceUpdateGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerClusterAsync</summary>
public async Task UpdateGameServerClusterRequestObjectAsync()
{
// Snippet: UpdateGameServerClusterAsync(UpdateGameServerClusterRequest, CallSettings)
// Additional: UpdateGameServerClusterAsync(UpdateGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateGameServerClusterRequest request = new UpdateGameServerClusterRequest
{
GameServerCluster = new GameServerCluster(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<GameServerCluster, OperationMetadata> response = await gameServerClustersServiceClient.UpdateGameServerClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceUpdateGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerCluster</summary>
public void UpdateGameServerCluster()
{
// Snippet: UpdateGameServerCluster(GameServerCluster, FieldMask, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
GameServerCluster gameServerCluster = new GameServerCluster();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<GameServerCluster, OperationMetadata> response = gameServerClustersServiceClient.UpdateGameServerCluster(gameServerCluster, updateMask);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceUpdateGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerClusterAsync</summary>
public async Task UpdateGameServerClusterAsync()
{
// Snippet: UpdateGameServerClusterAsync(GameServerCluster, FieldMask, CallSettings)
// Additional: UpdateGameServerClusterAsync(GameServerCluster, FieldMask, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerCluster gameServerCluster = new GameServerCluster();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<GameServerCluster, OperationMetadata> response = await gameServerClustersServiceClient.UpdateGameServerClusterAsync(gameServerCluster, updateMask);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceUpdateGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PreviewUpdateGameServerCluster</summary>
public void PreviewUpdateGameServerClusterRequestObject()
{
// Snippet: PreviewUpdateGameServerCluster(PreviewUpdateGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
PreviewUpdateGameServerClusterRequest request = new PreviewUpdateGameServerClusterRequest
{
GameServerCluster = new GameServerCluster(),
UpdateMask = new FieldMask(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewUpdateGameServerClusterResponse response = gameServerClustersServiceClient.PreviewUpdateGameServerCluster(request);
// End snippet
}
/// <summary>Snippet for PreviewUpdateGameServerClusterAsync</summary>
public async Task PreviewUpdateGameServerClusterRequestObjectAsync()
{
// Snippet: PreviewUpdateGameServerClusterAsync(PreviewUpdateGameServerClusterRequest, CallSettings)
// Additional: PreviewUpdateGameServerClusterAsync(PreviewUpdateGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
PreviewUpdateGameServerClusterRequest request = new PreviewUpdateGameServerClusterRequest
{
GameServerCluster = new GameServerCluster(),
UpdateMask = new FieldMask(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewUpdateGameServerClusterResponse response = await gameServerClustersServiceClient.PreviewUpdateGameServerClusterAsync(request);
// End snippet
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function initializeRiverEditor()
{
echo(" % - Initializing River Editor");
exec( "./riverEditor.cs" );
exec( "./riverEditorGui.gui" );
exec( "./riverEditorToolbar.gui" );
exec( "./riverEditorGui.cs" );
// Add ourselves to EditorGui, where all the other tools reside
RiverEditorGui.setVisible( false );
RiverEditorToolbar.setVisible(false);
RiverEditorOptionsWindow.setVisible( false );
RiverEditorTreeWindow.setVisible( false );
EditorGui.add( RiverEditorGui );
EditorGui.add( RiverEditorToolbar );
EditorGui.add( RiverEditorOptionsWindow );
EditorGui.add( RiverEditorTreeWindow );
new ScriptObject( RiverEditorPlugin )
{
superClass = "EditorPlugin";
editorGui = RiverEditorGui;
};
%map = new ActionMap();
%map.bindCmd( keyboard, "backspace", "RiverEditorGui.deleteNode();", "" );
%map.bindCmd( keyboard, "1", "RiverEditorGui.prepSelectionMode();", "" );
%map.bindCmd( keyboard, "2", "ToolsPaletteArray->RiverEditorMoveMode.performClick();", "" );
%map.bindCmd( keyboard, "3", "ToolsPaletteArray->RiverEditorRotateMode.performClick();", "" );
%map.bindCmd( keyboard, "4", "ToolsPaletteArray->RiverEditorScaleMode.performClick();", "" );
%map.bindCmd( keyboard, "5", "ToolsPaletteArray->RiverEditorAddRiverMode.performClick();", "" );
%map.bindCmd( keyboard, "=", "ToolsPaletteArray->RiverEditorInsertPointMode.performClick();", "" );
%map.bindCmd( keyboard, "numpadadd", "ToolsPaletteArray->RiverEditorInsertPointMode.performClick();", "" );
%map.bindCmd( keyboard, "-", "ToolsPaletteArray->RiverEditorRemovePointMode.performClick();", "" );
%map.bindCmd( keyboard, "numpadminus", "ToolsPaletteArray->RiverEditorRemovePointMode.performClick();", "" );
%map.bindCmd( keyboard, "z", "RiverEditorShowSplineBtn.performClick();", "" );
%map.bindCmd( keyboard, "x", "RiverEditorWireframeBtn.performClick();", "" );
%map.bindCmd( keyboard, "v", "RiverEditorShowRoadBtn.performClick();", "" );
RiverEditorPlugin.map = %map;
RiverEditorPlugin.initSettings();
}
function destroyRiverEditor()
{
}
function RiverEditorPlugin::onWorldEditorStartup( %this )
{
// Add ourselves to the window menu.
%accel = EditorGui.addToEditorsMenu( "River Editor", "", RiverEditorPlugin );
// Add ourselves to the ToolsToolbar
%tooltip = "River Editor (" @ %accel @ ")";
EditorGui.addToToolsToolbar( "RiverEditorPlugin", "RiverEditorPalette", expandFilename("tools/worldEditor/images/toolbar/river-editor"), %tooltip );
//connect editor windows
GuiWindowCtrl::attach( RiverEditorOptionsWindow, RiverEditorTreeWindow);
// Add ourselves to the Editor Settings window
exec( "./RiverEditorSettingsTab.gui" );
ESettingsWindow.addTabPage( ERiverEditorSettingsPage );
}
function RiverEditorPlugin::onActivated( %this )
{
%this.readSettings();
$River::EditorOpen = true;
ToolsPaletteArray->RiverEditorAddRiverMode.performClick();
EditorGui.bringToFront( RiverEditorGui );
RiverEditorGui.setVisible(true);
RiverEditorGui.makeFirstResponder( true );
RiverEditorToolbar.setVisible(true);
RiverEditorOptionsWindow.setVisible( true );
RiverEditorTreeWindow.setVisible( true );
RiverTreeView.open(ServerRiverSet,true);
%this.map.push();
// Store this on a dynamic field
// in order to restore whatever setting
// the user had before.
%this.prevGizmoAlignment = GlobalGizmoProfile.alignment;
// The DecalEditor always uses Object alignment.
GlobalGizmoProfile.alignment = "Object";
// Set the status bar here until all tool have been hooked up
EditorGuiStatusBar.setInfo("River editor.");
EditorGuiStatusBar.setSelection("");
// Allow the Gui to setup.
RiverEditorGui.onEditorActivated();
Parent::onActivated(%this);
}
function RiverEditorPlugin::onDeactivated( %this )
{
%this.writeSettings();
$River::EditorOpen = false;
RiverEditorGui.setVisible(false);
RiverEditorToolbar.setVisible(false);
RiverEditorOptionsWindow.setVisible( false );
RiverEditorTreeWindow.setVisible( false );
%this.map.pop();
// Restore the previous Gizmo
// alignment settings.
GlobalGizmoProfile.alignment = %this.prevGizmoAlignment;
// Allow the Gui to cleanup.
RiverEditorGui.onEditorDeactivated();
Parent::onDeactivated(%this);
}
function RiverEditorPlugin::onEditMenuSelect( %this, %editMenu )
{
%hasSelection = false;
if( isObject( RiverEditorGui.river ) )
%hasSelection = true;
%editMenu.enableItem( 3, false ); // Cut
%editMenu.enableItem( 4, false ); // Copy
%editMenu.enableItem( 5, false ); // Paste
%editMenu.enableItem( 6, %hasSelection ); // Delete
%editMenu.enableItem( 8, false ); // Deselect
}
function RiverEditorPlugin::handleDelete( %this )
{
RiverEditorGui.deleteNode();
}
function RiverEditorPlugin::handleEscape( %this )
{
return RiverEditorGui.onEscapePressed();
}
function RiverEditorPlugin::isDirty( %this )
{
return RiverEditorGui.isDirty;
}
function RiverEditorPlugin::onSaveMission( %this, %missionFile )
{
if( RiverEditorGui.isDirty )
{
$MissionGroup.save( %missionFile );
RiverEditorGui.isDirty = false;
}
}
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
function RiverEditorPlugin::initSettings( %this )
{
EditorSettings.beginGroup( "RiverEditor", true );
EditorSettings.setDefaultValue( "DefaultWidth", "10" );
EditorSettings.setDefaultValue( "DefaultDepth", "5" );
EditorSettings.setDefaultValue( "DefaultNormal", "0 0 1" );
EditorSettings.setDefaultValue( "HoverSplineColor", "255 0 0 255" );
EditorSettings.setDefaultValue( "SelectedSplineColor", "0 255 0 255" );
EditorSettings.setDefaultValue( "HoverNodeColor", "255 255 255 255" ); //<-- Not currently used
EditorSettings.endGroup();
}
function RiverEditorPlugin::readSettings( %this )
{
EditorSettings.beginGroup( "RiverEditor", true );
RiverEditorGui.DefaultWidth = EditorSettings.value("DefaultWidth");
RiverEditorGui.DefaultDepth = EditorSettings.value("DefaultDepth");
RiverEditorGui.DefaultNormal = EditorSettings.value("DefaultNormal");
RiverEditorGui.HoverSplineColor = EditorSettings.value("HoverSplineColor");
RiverEditorGui.SelectedSplineColor = EditorSettings.value("SelectedSplineColor");
RiverEditorGui.HoverNodeColor = EditorSettings.value("HoverNodeColor");
EditorSettings.endGroup();
}
function RiverEditorPlugin::writeSettings( %this )
{
EditorSettings.beginGroup( "RiverEditor", true );
EditorSettings.setValue( "DefaultWidth", RiverEditorGui.DefaultWidth );
EditorSettings.setValue( "DefaultDepth", RiverEditorGui.DefaultDepth );
EditorSettings.setValue( "DefaultNormal", RiverEditorGui.DefaultNormal );
EditorSettings.setValue( "HoverSplineColor", RiverEditorGui.HoverSplineColor );
EditorSettings.setValue( "SelectedSplineColor", RiverEditorGui.SelectedSplineColor );
EditorSettings.setValue( "HoverNodeColor", RiverEditorGui.HoverNodeColor );
EditorSettings.endGroup();
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Collections.Generic;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Abstract class front end to <see cref="SharpDX.Direct3D11.Texture2D"/>.
/// </summary>
public abstract class Texture2DBase : Texture
{
protected readonly new Direct3D11.Texture2D Resource;
private DXGI.Surface dxgiSurface;
/// <summary>
/// Initializes a new instance of the <see cref="Texture2DBase" /> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description2D">The description.</param>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
protected internal Texture2DBase(GraphicsDevice device, Texture2DDescription description2D)
: base(device, description2D)
{
Resource = new Direct3D11.Texture2D(device, description2D);
}
/// <summary>
/// Initializes a new instance of the <see cref="Texture2DBase" /> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description2D">The description.</param>
/// <param name="dataBoxes">A variable-length parameters list containing data rectangles.</param>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
protected internal Texture2DBase(GraphicsDevice device, Texture2DDescription description2D, DataBox[] dataBoxes)
: base(device ,description2D)
{
Resource = new Direct3D11.Texture2D(device, description2D, dataBoxes);
}
/// <summary>
/// Specialised constructor for use only by derived classes.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="texture">The texture.</param>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
protected internal Texture2DBase(GraphicsDevice device, Direct3D11.Texture2D texture)
: base(device, texture.Description)
{
Resource = texture;
}
/// <summary>
/// Return an equivalent staging texture CPU read-writable from this instance.
/// </summary>
/// <returns></returns>
public override Texture ToStaging()
{
return new Texture2D(this.GraphicsDevice, this.Description.ToStagingDescription());
}
protected virtual DXGI.Format GetDefaultViewFormat()
{
return this.Description.Format;
}
internal override TextureView GetShaderResourceView(Format viewFormat, ViewType viewType, int arrayOrDepthSlice, int mipIndex)
{
if ((this.Description.BindFlags & BindFlags.ShaderResource) == 0)
return null;
int arrayCount;
int mipCount;
GetViewSliceBounds(viewType, ref arrayOrDepthSlice, ref mipIndex, out arrayCount, out mipCount);
var textureViewKey = new TextureViewKey(viewFormat, viewType, arrayOrDepthSlice, mipIndex);
lock (this.shaderResourceViews)
{
TextureView srv;
// Creates the shader resource view
if (!shaderResourceViews.TryGetValue(textureViewKey, out srv))
{
// Create the view
var srvDescription = new ShaderResourceViewDescription() { Format = viewFormat };
// Initialize for texture arrays or texture cube
if (this.Description.ArraySize > 1)
{
// If texture cube
if ((this.Description.OptionFlags & ResourceOptionFlags.TextureCube) != 0)
{
srvDescription.Dimension = ShaderResourceViewDimension.TextureCube;
srvDescription.TextureCube.MipLevels = mipCount;
srvDescription.TextureCube.MostDetailedMip = mipIndex;
}
else
{
// Else regular Texture2D
srvDescription.Dimension = this.Description.SampleDescription.Count > 1 ? ShaderResourceViewDimension.Texture2DMultisampledArray : ShaderResourceViewDimension.Texture2DArray;
// Multisample?
if (this.Description.SampleDescription.Count > 1)
{
srvDescription.Texture2DMSArray.ArraySize = arrayCount;
srvDescription.Texture2DMSArray.FirstArraySlice = arrayOrDepthSlice;
}
else
{
srvDescription.Texture2DArray.ArraySize = arrayCount;
srvDescription.Texture2DArray.FirstArraySlice = arrayOrDepthSlice;
srvDescription.Texture2DArray.MipLevels = mipCount;
srvDescription.Texture2DArray.MostDetailedMip = mipIndex;
}
}
}
else
{
srvDescription.Dimension = this.Description.SampleDescription.Count > 1 ? ShaderResourceViewDimension.Texture2DMultisampled : ShaderResourceViewDimension.Texture2D;
if (this.Description.SampleDescription.Count <= 1)
{
srvDescription.Texture2D.MipLevels = mipCount;
srvDescription.Texture2D.MostDetailedMip = mipIndex;
}
}
srv = new TextureView(this, new ShaderResourceView(this.GraphicsDevice, this.Resource, srvDescription));
this.shaderResourceViews.Add(textureViewKey, ToDispose(srv));
}
return srv;
}
}
internal override UnorderedAccessView GetUnorderedAccessView(int arrayOrDepthSlice, int mipIndex)
{
if ((this.Description.BindFlags & BindFlags.UnorderedAccess) == 0)
return null;
int arrayCount = 1;
// Use Full although we are binding to a single array/mimap slice, just to get the correct index
var uavIndex = GetViewIndex(ViewType.Full, arrayOrDepthSlice, mipIndex);
lock (this.unorderedAccessViews)
{
var uav = this.unorderedAccessViews[uavIndex];
// Creates the unordered access view
if (uav == null)
{
var uavDescription = new UnorderedAccessViewDescription() {
Format = this.Description.Format,
Dimension = this.Description.ArraySize > 1 ? UnorderedAccessViewDimension.Texture2DArray : UnorderedAccessViewDimension.Texture2D
};
if (this.Description.ArraySize > 1)
{
uavDescription.Texture2DArray.ArraySize = arrayCount;
uavDescription.Texture2DArray.FirstArraySlice = arrayOrDepthSlice;
uavDescription.Texture2DArray.MipSlice = mipIndex;
}
else
{
uavDescription.Texture2D.MipSlice = mipIndex;
}
uav = new UnorderedAccessView(GraphicsDevice, Resource, uavDescription) { Tag = this };
this.unorderedAccessViews[uavIndex] = ToDispose(uav);
}
return uav;
}
}
/// <summary>
/// <see cref="SharpDX.DXGI.Surface"/> casting operator.
/// </summary>
/// <param name="from">From the Texture1D.</param>
public static implicit operator SharpDX.DXGI.Surface(Texture2DBase from)
{
// Don't bother with multithreading here
return from == null ? null : from.dxgiSurface ?? (from.dxgiSurface = from.ToDispose(from.Resource.QueryInterface<DXGI.Surface>()));
}
protected override void InitializeViews()
{
// Creates the shader resource view
if ((this.Description.BindFlags & BindFlags.ShaderResource) != 0)
{
this.shaderResourceViews = new Dictionary<TextureViewKey, TextureView>();
// Pre initialize by default the view on the first array/mipmap
var viewFormat = GetDefaultViewFormat();
if(!FormatHelper.IsTypeless(viewFormat))
{
// Only valid for non-typeless viewformat
defaultShaderResourceView = GetShaderResourceView(viewFormat, ViewType.Full, 0, 0);
}
}
// Creates the unordered access view
if ((this.Description.BindFlags & BindFlags.UnorderedAccess) != 0)
{
// Initialize the unordered access views
this.unorderedAccessViews = new UnorderedAccessView[GetViewCount()];
// Pre initialize by default the view on the first array/mipmap
GetUnorderedAccessView(0, 0);
}
}
protected static Texture2DDescription NewDescription(int width, int height, PixelFormat format, TextureFlags textureFlags, int mipCount, int arraySize, ResourceUsage usage)
{
if ((textureFlags & TextureFlags.UnorderedAccess) != 0)
usage = ResourceUsage.Default;
var desc = new Texture2DDescription()
{
Width = width,
Height = height,
ArraySize = arraySize,
SampleDescription = new DXGI.SampleDescription(1, 0),
BindFlags = GetBindFlagsFromTextureFlags(textureFlags),
Format = format,
MipLevels = CalculateMipMapCount(mipCount, width, height),
Usage = usage,
CpuAccessFlags = GetCpuAccessFlagsFromUsage(usage),
OptionFlags = ResourceOptionFlags.None
};
// If the texture is a RenderTarget + ShaderResource + MipLevels > 1, then allow for GenerateMipMaps method
if ((desc.BindFlags & BindFlags.RenderTarget) != 0 && (desc.BindFlags & BindFlags.ShaderResource) != 0 && desc.MipLevels > 1)
{
desc.OptionFlags |= ResourceOptionFlags.GenerateMipMaps;
}
return desc;
}
}
}
| |
#region License
/*
* WebSocketServiceManager.cs
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* 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.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
namespace WebSocketSharp.Server
{
/// <summary>
/// Manages the WebSocket services provided by the <see cref="HttpServer"/> or
/// <see cref="WebSocketServer"/>.
/// </summary>
public class WebSocketServiceManager
{
#region Private Fields
private volatile bool _clean;
private Dictionary<string, WebSocketServiceHost> _hosts;
private Logger _logger;
private volatile ServerState _state;
private object _sync;
private TimeSpan _waitTime;
#endregion
#region Internal Constructors
internal WebSocketServiceManager ()
: this (new Logger ())
{
}
internal WebSocketServiceManager (Logger logger)
{
_logger = logger;
_clean = true;
_hosts = new Dictionary<string, WebSocketServiceHost> ();
_state = ServerState.Ready;
_sync = ((ICollection) _hosts).SyncRoot;
_waitTime = TimeSpan.FromSeconds (1);
}
#endregion
#region Public Properties
/// <summary>
/// Gets the number of the WebSocket services.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of the services.
/// </value>
public int Count {
get {
lock (_sync)
return _hosts.Count;
}
}
/// <summary>
/// Gets the host instances for the Websocket services.
/// </summary>
/// <value>
/// An <c>IEnumerable<WebSocketServiceHost></c> instance that provides an enumerator
/// which supports the iteration over the collection of the host instances for the services.
/// </value>
public IEnumerable<WebSocketServiceHost> Hosts {
get {
lock (_sync)
return _hosts.Values.ToList ();
}
}
/// <summary>
/// Gets the WebSocket service host with the specified <paramref name="path"/>.
/// </summary>
/// <value>
/// A <see cref="WebSocketServiceHost"/> instance that provides the access to
/// the information in the service, or <see langword="null"/> if it's not found.
/// </value>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to find.
/// </param>
public WebSocketServiceHost this[string path] {
get {
WebSocketServiceHost host;
TryGetServiceHost (path, out host);
return host;
}
}
/// <summary>
/// Gets a value indicating whether the manager cleans up the inactive sessions
/// in the WebSocket services periodically.
/// </summary>
/// <value>
/// <c>true</c> if the manager cleans up the inactive sessions every 60 seconds;
/// otherwise, <c>false</c>.
/// </value>
public bool KeepClean {
get {
return _clean;
}
internal set {
lock (_sync) {
if (!(value ^ _clean))
return;
_clean = value;
foreach (var host in _hosts.Values)
host.KeepClean = value;
}
}
}
/// <summary>
/// Gets the paths for the WebSocket services.
/// </summary>
/// <value>
/// An <c>IEnumerable<string></c> instance that provides an enumerator which supports
/// the iteration over the collection of the paths for the services.
/// </value>
public IEnumerable<string> Paths {
get {
lock (_sync)
return _hosts.Keys.ToList ();
}
}
/// <summary>
/// Gets the total number of the sessions in the WebSocket services.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the total number of the sessions in the services.
/// </value>
public int SessionCount {
get {
var cnt = 0;
foreach (var host in Hosts) {
if (_state != ServerState.Start)
break;
cnt += host.Sessions.Count;
}
return cnt;
}
}
/// <summary>
/// Gets the wait time for the response to the WebSocket Ping or Close.
/// </summary>
/// <value>
/// A <see cref="TimeSpan"/> that represents the wait time.
/// </value>
public TimeSpan WaitTime {
get {
return _waitTime;
}
internal set {
lock (_sync) {
if (value == _waitTime)
return;
_waitTime = value;
foreach (var host in _hosts.Values)
host.WaitTime = value;
}
}
}
#endregion
#region Private Methods
private void broadcast (Opcode opcode, byte[] data, Action completed)
{
var cache = new Dictionary<CompressionMethod, byte[]> ();
try {
foreach (var host in Hosts) {
if (_state != ServerState.Start)
break;
host.Sessions.Broadcast (opcode, data, cache);
}
if (completed != null)
completed ();
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
}
finally {
cache.Clear ();
}
}
private void broadcast (Opcode opcode, Stream stream, Action completed)
{
var cache = new Dictionary<CompressionMethod, Stream> ();
try {
foreach (var host in Hosts) {
if (_state != ServerState.Start)
break;
host.Sessions.Broadcast (opcode, stream, cache);
}
if (completed != null)
completed ();
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
}
finally {
foreach (var cached in cache.Values)
cached.Dispose ();
cache.Clear ();
}
}
private void broadcastAsync (Opcode opcode, byte[] data, Action completed)
{
ThreadPool.QueueUserWorkItem (state => broadcast (opcode, data, completed));
}
private void broadcastAsync (Opcode opcode, Stream stream, Action completed)
{
ThreadPool.QueueUserWorkItem (state => broadcast (opcode, stream, completed));
}
private Dictionary<string, Dictionary<string, bool>> broadping (
byte[] frameAsBytes, TimeSpan timeout)
{
var ret = new Dictionary<string, Dictionary<string, bool>> ();
foreach (var host in Hosts) {
if (_state != ServerState.Start)
break;
ret.Add (host.Path, host.Sessions.Broadping (frameAsBytes, timeout));
}
return ret;
}
#endregion
#region Internal Methods
internal void Add<TBehavior> (string path, Func<TBehavior> initializer)
where TBehavior : WebSocketBehavior
{
lock (_sync) {
path = HttpUtility.UrlDecode (path).TrimEndSlash ();
WebSocketServiceHost host;
if (_hosts.TryGetValue (path, out host)) {
_logger.Error (
"A WebSocket service with the specified path already exists:\n path: " + path);
return;
}
host = new WebSocketServiceHost<TBehavior> (path, initializer, _logger);
if (!_clean)
host.KeepClean = false;
if (_waitTime != host.WaitTime)
host.WaitTime = _waitTime;
if (_state == ServerState.Start)
host.Start ();
_hosts.Add (path, host);
}
}
internal bool InternalTryGetServiceHost (string path, out WebSocketServiceHost host)
{
bool ret;
lock (_sync) {
path = HttpUtility.UrlDecode (path).TrimEndSlash ();
ret = _hosts.TryGetValue (path, out host);
}
if (!ret)
_logger.Error (
"A WebSocket service with the specified path isn't found:\n path: " + path);
return ret;
}
internal bool Remove (string path)
{
WebSocketServiceHost host;
lock (_sync) {
path = HttpUtility.UrlDecode (path).TrimEndSlash ();
if (!_hosts.TryGetValue (path, out host)) {
_logger.Error (
"A WebSocket service with the specified path isn't found:\n path: " + path);
return false;
}
_hosts.Remove (path);
}
if (host.State == ServerState.Start)
host.Stop ((ushort) CloseStatusCode.Away, null);
return true;
}
internal void Start ()
{
lock (_sync) {
foreach (var host in _hosts.Values)
host.Start ();
_state = ServerState.Start;
}
}
internal void Stop (CloseEventArgs e, bool send, bool wait)
{
lock (_sync) {
_state = ServerState.ShuttingDown;
var bytes = send
? WebSocketFrame.CreateCloseFrame (e.PayloadData, false).ToByteArray ()
: null;
var timeout = wait ? _waitTime : TimeSpan.Zero;
foreach (var host in _hosts.Values)
host.Sessions.Stop (e, bytes, timeout);
_hosts.Clear ();
_state = ServerState.Stop;
}
}
#endregion
#region Public Methods
/// <summary>
/// Sends binary <paramref name="data"/> to every client in the WebSocket services.
/// </summary>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
public void Broadcast (byte[] data)
{
var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData ();
if (msg != null) {
_logger.Error (msg);
return;
}
if (data.LongLength <= WebSocket.FragmentLength)
broadcast (Opcode.Binary, data, null);
else
broadcast (Opcode.Binary, new MemoryStream (data), null);
}
/// <summary>
/// Sends text <paramref name="data"/> to every client in the WebSocket services.
/// </summary>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
public void Broadcast (string data)
{
var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData ();
if (msg != null) {
_logger.Error (msg);
return;
}
var bytes = Encoding.UTF8.GetBytes (data);
if (bytes.LongLength <= WebSocket.FragmentLength)
broadcast (Opcode.Text, bytes, null);
else
broadcast (Opcode.Text, new MemoryStream (bytes), null);
}
/// <summary>
/// Sends binary <paramref name="data"/> asynchronously to every client in
/// the WebSocket services.
/// </summary>
/// <remarks>
/// This method doesn't wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
/// <param name="completed">
/// An <see cref="Action"/> delegate that references the method(s) called when
/// the send is complete.
/// </param>
public void BroadcastAsync (byte[] data, Action completed)
{
var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData ();
if (msg != null) {
_logger.Error (msg);
return;
}
if (data.LongLength <= WebSocket.FragmentLength)
broadcastAsync (Opcode.Binary, data, completed);
else
broadcastAsync (Opcode.Binary, new MemoryStream (data), completed);
}
/// <summary>
/// Sends text <paramref name="data"/> asynchronously to every client in
/// the WebSocket services.
/// </summary>
/// <remarks>
/// This method doesn't wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
/// <param name="completed">
/// An <see cref="Action"/> delegate that references the method(s) called when
/// the send is complete.
/// </param>
public void BroadcastAsync (string data, Action completed)
{
var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData ();
if (msg != null) {
_logger.Error (msg);
return;
}
var bytes = Encoding.UTF8.GetBytes (data);
if (bytes.LongLength <= WebSocket.FragmentLength)
broadcastAsync (Opcode.Text, bytes, completed);
else
broadcastAsync (Opcode.Text, new MemoryStream (bytes), completed);
}
/// <summary>
/// Sends binary data from the specified <see cref="Stream"/> asynchronously to
/// every client in the WebSocket services.
/// </summary>
/// <remarks>
/// This method doesn't wait for the send to be complete.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> from which contains the binary data to send.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that represents the number of bytes to send.
/// </param>
/// <param name="completed">
/// An <see cref="Action"/> delegate that references the method(s) called when
/// the send is complete.
/// </param>
public void BroadcastAsync (Stream stream, int length, Action completed)
{
var msg = _state.CheckIfStart () ??
stream.CheckIfCanRead () ??
(length < 1 ? "'length' is less than 1." : null);
if (msg != null) {
_logger.Error (msg);
return;
}
stream.ReadBytesAsync (
length,
data => {
var len = data.Length;
if (len == 0) {
_logger.Error ("The data cannot be read from 'stream'.");
return;
}
if (len < length)
_logger.Warn (
String.Format (
"The data with 'length' cannot be read from 'stream':\n expected: {0}\n actual: {1}",
length,
len));
if (len <= WebSocket.FragmentLength)
broadcast (Opcode.Binary, data, completed);
else
broadcast (Opcode.Binary, new MemoryStream (data), completed);
},
ex => _logger.Fatal (ex.ToString ()));
}
/// <summary>
/// Sends a Ping to every client in the WebSocket services.
/// </summary>
/// <returns>
/// A <c>Dictionary<string, Dictionary<string, bool>></c> that contains
/// a collection of pairs of a service path and a collection of pairs of a session ID
/// and a value indicating whether the manager received a Pong from each client in a time,
/// or <see langword="null"/> if this method isn't available.
/// </returns>
public Dictionary<string, Dictionary<string, bool>> Broadping ()
{
var msg = _state.CheckIfStart ();
if (msg != null) {
_logger.Error (msg);
return null;
}
return broadping (WebSocketFrame.EmptyUnmaskPingBytes, _waitTime);
}
/// <summary>
/// Sends a Ping with the specified <paramref name="message"/> to every client in
/// the WebSocket services.
/// </summary>
/// <returns>
/// A <c>Dictionary<string, Dictionary<string, bool>></c> that contains
/// a collection of pairs of a service path and a collection of pairs of a session ID
/// and a value indicating whether the manager received a Pong from each client in a time,
/// or <see langword="null"/> if this method isn't available or <paramref name="message"/>
/// is invalid.
/// </returns>
/// <param name="message">
/// A <see cref="string"/> that represents the message to send.
/// </param>
public Dictionary<string, Dictionary<string, bool>> Broadping (string message)
{
if (message == null || message.Length == 0)
return Broadping ();
byte[] data = null;
var msg = _state.CheckIfStart () ?? WebSocket.CheckPingParameter (message, out data);
if (msg != null) {
_logger.Error (msg);
return null;
}
return broadping (WebSocketFrame.CreatePingFrame (data, false).ToByteArray (), _waitTime);
}
/// <summary>
/// Tries to get the WebSocket service host with the specified <paramref name="path"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the service is successfully found; otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to find.
/// </param>
/// <param name="host">
/// When this method returns, a <see cref="WebSocketServiceHost"/> instance that
/// provides the access to the information in the service, or <see langword="null"/>
/// if it's not found. This parameter is passed uninitialized.
/// </param>
public bool TryGetServiceHost (string path, out WebSocketServiceHost host)
{
var msg = _state.CheckIfStart () ?? path.CheckIfValidServicePath ();
if (msg != null) {
_logger.Error (msg);
host = null;
return false;
}
return InternalTryGetServiceHost (path, out host);
}
#endregion
}
}
| |
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Threading.Tasks;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Tests.Integ.Framework;
using Telegram.Bot.Types;
using Xunit;
namespace Telegram.Bot.Tests.Integ.Admin_Bot
{
[Collection(Constants.TestCollections.SupergroupAdminBots)]
[TestCaseOrderer(Constants.TestCaseOrderer, Constants.AssemblyName)]
public class SupergroupAdminBotTests : IClassFixture<AdminBotTestFixture>
{
private readonly AdminBotTestFixture _classFixture;
private readonly TestsFixture _fixture;
private ITelegramBotClient BotClient => _fixture.BotClient;
public SupergroupAdminBotTests(TestsFixture testsFixture, AdminBotTestFixture classFixture)
{
_fixture = testsFixture;
_classFixture = classFixture;
_classFixture.Chat = _fixture.SupergroupChat;
}
#region 1. Changing Chat Title
[OrderedFact(DisplayName = FactTitles.ShouldSetChatTitle)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SetChatTitle)]
public async Task Should_Set_Chat_Title()
{
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldSetChatTitle);
await BotClient.SetChatTitleAsync(
chatId: _classFixture.Chat.Id,
title: _classFixture.ChatTitle
);
}
#endregion
#region 2. Changing Chat Description
[OrderedFact(DisplayName = FactTitles.ShouldSetChatDescription)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SetChatDescription)]
public async Task Should_Set_Chat_Description()
{
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldSetChatDescription);
await BotClient.SetChatDescriptionAsync(
chatId: _classFixture.Chat.Id,
description: "Test Chat Description"
);
}
[OrderedFact(DisplayName = FactTitles.ShouldDeleteChatDescription)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SetChatDescription)]
public async Task Should_Delete_Chat_Description()
{
// ToDo: exception Bad Request: chat description is not modified
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldDeleteChatDescription);
await BotClient.SetChatDescriptionAsync(
chatId: _classFixture.Chat.Id
);
}
#endregion
#region 3. Pinning Chat Description
[OrderedFact(DisplayName = FactTitles.ShouldPinMessage)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.PinChatMessage)]
public async Task Should_Pin_Message()
{
Message msg = await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldPinMessage);
await BotClient.PinChatMessageAsync(
chatId: _classFixture.Chat.Id,
messageId: msg.MessageId,
disableNotification: true
);
_classFixture.PinnedMessage = msg;
}
[OrderedFact(DisplayName = FactTitles.ShouldGetChatPinnedMessage)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.GetChat)]
public async Task Should_Get_Chat_Pinned_Message()
{
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldGetChatPinnedMessage);
Message pinnedMsg = _classFixture.PinnedMessage;
Chat chat = await BotClient.GetChatAsync(_classFixture.Chat.Id);
Assert.True(JToken.DeepEquals(
JToken.FromObject(pinnedMsg), JToken.FromObject(chat.PinnedMessage)
));
}
[OrderedFact(DisplayName = FactTitles.ShouldUnpinMessage)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.UnpinChatMessage)]
public async Task Should_Unpin_Message()
{
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldUnpinMessage);
await BotClient.UnpinChatMessageAsync(_classFixture.Chat.Id);
}
[OrderedFact(DisplayName = FactTitles.ShouldGetChatWithNoPinnedMessage)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.GetChat)]
public async Task Should_Get_Chat_With_No_Pinned_Message()
{
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldGetChatWithNoPinnedMessage);
Chat chat = await BotClient.GetChatAsync(_classFixture.Chat.Id);
Assert.Null(chat.PinnedMessage);
}
#endregion
#region 4. Changing Chat Photo
[OrderedFact(DisplayName = FactTitles.ShouldSetChatPhoto)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SetChatPhoto)]
public async Task Should_Set_Chat_Photo()
{
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldSetChatPhoto);
using (Stream stream = System.IO.File.OpenRead(Constants.FileNames.Photos.Logo))
{
await BotClient.SetChatPhotoAsync(
chatId: _classFixture.Chat.Id,
photo: stream
);
}
}
[OrderedFact(DisplayName = FactTitles.ShouldDeleteChatPhoto)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.DeleteChatPhoto)]
public async Task Should_Delete_Chat_Photo()
{
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldDeleteChatPhoto);
await BotClient.DeleteChatPhotoAsync(_classFixture.Chat.Id);
}
[OrderedFact(DisplayName = FactTitles.ShouldThrowOnDeletingChatDeletedPhoto)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.DeleteChatPhoto)]
public async Task Should_Throw_On_Deleting_Chat_Deleted_Photo()
{
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowOnDeletingChatDeletedPhoto);
Exception e = await Assert.ThrowsAnyAsync<Exception>(() =>
BotClient.DeleteChatPhotoAsync(_classFixture.Chat.Id));
// ToDo: Create exception type
Assert.IsType<ApiRequestException>(e);
Assert.Equal("Bad Request: CHAT_NOT_MODIFIED", e.Message);
}
/// <summary>
/// If chat had a photo before, reset the photo back.
/// </summary>
[OrderedFact(DisplayName = FactTitles.ShouldResetOldChatPhoto)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SetChatPhoto)]
public async Task Should_Reset_Old_Chat_Photo_If_Existed()
{
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldResetOldChatPhoto);
// "Chat.Photo" might be null if there is no photo currently set
string previousChatPhotoId = _classFixture.Chat.Photo?.BigFileId;
if (previousChatPhotoId == default)
{
// chat didn't have a photo
return;
}
using (Stream photoStream = new MemoryStream())
{
// pass photo's file_id, prepare file for download, and download the file into memroy
await BotClient.GetInfoAndDownloadFileAsync(previousChatPhotoId, photoStream);
// need to set position of memory stream back to its start so next method reads photo stream from the beginning
photoStream.Position = 0;
await BotClient.SetChatPhotoAsync(
chatId: _classFixture.Chat.Id,
photo: photoStream
);
}
}
#endregion
#region 5. Chat Sticker Set
[OrderedFact(DisplayName = FactTitles.ShouldThrowOnSettingChatStickerSet)]
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SetChatStickerSet)]
public async Task Should_Throw_On_Setting_Chat_Sticker_Set()
{
await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowOnSettingChatStickerSet);
const string setName = "EvilMinds";
ApiRequestException exception = await Assert.ThrowsAnyAsync<ApiRequestException>(() =>
_fixture.BotClient.SetChatStickerSetAsync(_classFixture.Chat.Id, setName)
);
// ToDo: Create exception type
Assert.Equal(400, exception.ErrorCode);
Assert.Equal("Bad Request: can't set supergroup sticker set", exception.Message);
}
#endregion
private static class FactTitles
{
public const string ShouldSetChatTitle = "Should set chat title";
public const string ShouldSetChatDescription = "Should set chat description";
public const string ShouldDeleteChatDescription = "Should delete chat description";
public const string ShouldPinMessage = "Should pin chat message";
public const string ShouldGetChatPinnedMessage = "Should get chat's pinned message";
public const string ShouldUnpinMessage = "Should unpin chat message";
public const string ShouldGetChatWithNoPinnedMessage = "Should get the chat info without a pinned message";
public const string ShouldSetChatPhoto = "Should set chat photo";
public const string ShouldDeleteChatPhoto = "Should delete chat photo";
public const string ShouldThrowOnDeletingChatDeletedPhoto =
"Should throw exception in deleting chat photo with no photo currently set";
public const string ShouldResetOldChatPhoto = "Should reset the same old chat photo if existed";
public const string ShouldThrowOnSettingChatStickerSet =
"Should throw exception when trying to set sticker set for a chat with less than 100 members";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Http.Headers;
using Xunit;
namespace System.Net.Http.Tests
{
public class StringWithQualityHeaderValueTest
{
[Fact]
public void Ctor_StringOnlyOverload_MatchExpectation()
{
StringWithQualityHeaderValue value = new StringWithQualityHeaderValue("token");
Assert.Equal("token", value.Value);
Assert.Null(value.Quality);
AssertExtensions.Throws<ArgumentException>("value", () => { new StringWithQualityHeaderValue(null); });
AssertExtensions.Throws<ArgumentException>("value", () => { new StringWithQualityHeaderValue(""); });
Assert.Throws<FormatException>(() => { new StringWithQualityHeaderValue("in valid"); });
}
[Fact]
public void Ctor_StringWithQualityOverload_MatchExpectation()
{
StringWithQualityHeaderValue value = new StringWithQualityHeaderValue("token", 0.5);
Assert.Equal("token", value.Value);
Assert.Equal(0.5, value.Quality);
AssertExtensions.Throws<ArgumentException>("value", () => { new StringWithQualityHeaderValue(null, 0.1); });
AssertExtensions.Throws<ArgumentException>("value", () => { new StringWithQualityHeaderValue("", 0.1); });
Assert.Throws<FormatException>(() => { new StringWithQualityHeaderValue("in valid", 0.1); });
Assert.Throws<ArgumentOutOfRangeException>(() => { new StringWithQualityHeaderValue("t", 1.1); });
Assert.Throws<ArgumentOutOfRangeException>(() => { new StringWithQualityHeaderValue("t", -0.1); });
}
[Fact]
public void ToString_UseDifferentValues_AllSerializedCorrectly()
{
StringWithQualityHeaderValue value = new StringWithQualityHeaderValue("token");
Assert.Equal("token", value.ToString());
value = new StringWithQualityHeaderValue("token", 0.1);
Assert.Equal("token; q=0.1", value.ToString());
value = new StringWithQualityHeaderValue("token", 0);
Assert.Equal("token; q=0.0", value.ToString());
value = new StringWithQualityHeaderValue("token", 1);
Assert.Equal("token; q=1.0", value.ToString());
// Note that the quality value gets rounded
value = new StringWithQualityHeaderValue("token", 0.56789);
Assert.Equal("token; q=0.568", value.ToString());
}
[Fact]
public void GetHashCode_UseSameAndDifferentValues_SameOrDifferentHashCodes()
{
StringWithQualityHeaderValue value1 = new StringWithQualityHeaderValue("t", 0.123);
StringWithQualityHeaderValue value2 = new StringWithQualityHeaderValue("t", 0.123);
StringWithQualityHeaderValue value3 = new StringWithQualityHeaderValue("T", 0.123);
StringWithQualityHeaderValue value4 = new StringWithQualityHeaderValue("t");
StringWithQualityHeaderValue value5 = new StringWithQualityHeaderValue("x", 0.123);
StringWithQualityHeaderValue value6 = new StringWithQualityHeaderValue("t", 0.5);
StringWithQualityHeaderValue value7 = new StringWithQualityHeaderValue("t", 0.1234);
StringWithQualityHeaderValue value8 = new StringWithQualityHeaderValue("T");
StringWithQualityHeaderValue value9 = new StringWithQualityHeaderValue("x");
Assert.Equal(value1.GetHashCode(), value2.GetHashCode());
Assert.Equal(value1.GetHashCode(), value3.GetHashCode());
Assert.NotEqual(value1.GetHashCode(), value4.GetHashCode());
Assert.NotEqual(value1.GetHashCode(), value5.GetHashCode());
Assert.NotEqual(value1.GetHashCode(), value6.GetHashCode());
Assert.NotEqual(value1.GetHashCode(), value7.GetHashCode());
Assert.Equal(value4.GetHashCode(), value8.GetHashCode());
Assert.NotEqual(value4.GetHashCode(), value9.GetHashCode());
}
[Fact]
public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions()
{
StringWithQualityHeaderValue value1 = new StringWithQualityHeaderValue("t", 0.123);
StringWithQualityHeaderValue value2 = new StringWithQualityHeaderValue("t", 0.123);
StringWithQualityHeaderValue value3 = new StringWithQualityHeaderValue("T", 0.123);
StringWithQualityHeaderValue value4 = new StringWithQualityHeaderValue("t");
StringWithQualityHeaderValue value5 = new StringWithQualityHeaderValue("x", 0.123);
StringWithQualityHeaderValue value6 = new StringWithQualityHeaderValue("t", 0.5);
StringWithQualityHeaderValue value7 = new StringWithQualityHeaderValue("t", 0.1234);
StringWithQualityHeaderValue value8 = new StringWithQualityHeaderValue("T");
StringWithQualityHeaderValue value9 = new StringWithQualityHeaderValue("x");
Assert.False(value1.Equals(null), "t; q=0.123 vs. <null>");
Assert.True(value1.Equals(value2), "t; q=0.123 vs. t; q=0.123");
Assert.True(value1.Equals(value3), "t; q=0.123 vs. T; q=0.123");
Assert.False(value1.Equals(value4), "t; q=0.123 vs. t");
Assert.False(value4.Equals(value1), "t vs. t; q=0.123");
Assert.False(value1.Equals(value5), "t; q=0.123 vs. x; q=0.123");
Assert.False(value1.Equals(value6), "t; q=0.123 vs. t; q=0.5");
Assert.False(value1.Equals(value7), "t; q=0.123 vs. t; q=0.1234");
Assert.True(value4.Equals(value8), "t vs. T");
Assert.False(value4.Equals(value9), "t vs. T");
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
StringWithQualityHeaderValue source = new StringWithQualityHeaderValue("token", 0.123);
StringWithQualityHeaderValue clone = (StringWithQualityHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Value, clone.Value);
Assert.Equal(source.Quality, clone.Quality);
source = new StringWithQualityHeaderValue("token");
clone = (StringWithQualityHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Value, clone.Value);
Assert.Null(source.Quality);
}
[Fact]
public void GetStringWithQualityLength_DifferentValidScenarios_AllReturnNonZero()
{
StringWithQualityHeaderValue result = null;
CallGetStringWithQualityLength(" token ; q = 0.123 ,", 1, 18, out result);
Assert.Equal("token", result.Value);
Assert.Equal(0.123, result.Quality);
CallGetStringWithQualityLength("token;q=1 , x", 0, 10, out result);
Assert.Equal("token", result.Value);
Assert.Equal(1, result.Quality);
CallGetStringWithQualityLength("*", 0, 1, out result);
Assert.Equal("*", result.Value);
Assert.Null(result.Quality);
CallGetStringWithQualityLength("t;q=0.", 0, 6, out result);
Assert.Equal("t", result.Value);
Assert.Equal(0, result.Quality);
CallGetStringWithQualityLength("t;q=1.,", 0, 6, out result);
Assert.Equal("t", result.Value);
Assert.Equal(1, result.Quality);
CallGetStringWithQualityLength("t ; q = 0X", 0, 13, out result);
Assert.Equal("t", result.Value);
Assert.Equal(0, result.Quality);
CallGetStringWithQualityLength("t ; q = 0,", 0, 13, out result);
Assert.Equal("t", result.Value);
Assert.Equal(0, result.Quality);
}
[Fact]
public void GetStringWithQualityLength_DifferentInvalidScenarios_AllReturnZero()
{
CheckInvalidGetStringWithQualityLength(" t", 0); // no leading whitespace allowed
CheckInvalidGetStringWithQualityLength("t;q=", 0);
CheckInvalidGetStringWithQualityLength("t;q=-1", 0);
CheckInvalidGetStringWithQualityLength("t;q=1.00001", 0);
CheckInvalidGetStringWithQualityLength("t;q", 0);
CheckInvalidGetStringWithQualityLength("t;", 0);
CheckInvalidGetStringWithQualityLength("t;;q=1", 0);
CheckInvalidGetStringWithQualityLength("t;q=a", 0);
CheckInvalidGetStringWithQualityLength("t;qa", 0);
CheckInvalidGetStringWithQualityLength("t;q1", 0);
CheckInvalidGetStringWithQualityLength("", 0);
CheckInvalidGetStringWithQualityLength(null, 0);
}
[Fact]
public void Parse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidParse("text", new StringWithQualityHeaderValue("text"));
CheckValidParse("text;q=0.5", new StringWithQualityHeaderValue("text", 0.5));
CheckValidParse("text ; q = 0.5", new StringWithQualityHeaderValue("text", 0.5));
CheckValidParse("\r\n text ; q = 0.5 ", new StringWithQualityHeaderValue("text", 0.5));
CheckValidParse(" text ", new StringWithQualityHeaderValue("text"));
CheckValidParse(" \r\n text \r\n ; \r\n q = 0.123", new StringWithQualityHeaderValue("text", 0.123));
}
[Fact]
public void Parse_SetOfInvalidValueStrings_Throws()
{
CheckInvalidParse("text,");
CheckInvalidParse("\r\n text ; q = 0.5, next_text ");
CheckInvalidParse(" text,next_text ");
CheckInvalidParse(" ,, text, , ,next");
CheckInvalidParse(" ,, text, , ,");
CheckInvalidParse(", \r\n text \r\n ; \r\n q = 0.123");
CheckInvalidParse("te\u00E4xt");
CheckInvalidParse("text\u4F1A");
CheckInvalidParse("\u4F1A");
CheckInvalidParse("t;q=\u4F1A");
CheckInvalidParse("t;q=");
CheckInvalidParse("t;q");
CheckInvalidParse("t;\u4F1A=1");
CheckInvalidParse("t;q\u4F1A=1");
CheckInvalidParse("t y");
CheckInvalidParse("t;q=1 y");
CheckInvalidParse(null);
CheckInvalidParse(string.Empty);
CheckInvalidParse(" ");
CheckInvalidParse(" ,,");
}
[Fact]
public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidTryParse("text", new StringWithQualityHeaderValue("text"));
CheckValidTryParse("text;q=0.5", new StringWithQualityHeaderValue("text", 0.5));
CheckValidTryParse("text ; q = 0.5", new StringWithQualityHeaderValue("text", 0.5));
CheckValidTryParse("\r\n text ; q = 0.5 ", new StringWithQualityHeaderValue("text", 0.5));
CheckValidTryParse(" text ", new StringWithQualityHeaderValue("text"));
CheckValidTryParse(" \r\n text \r\n ; \r\n q = 0.123", new StringWithQualityHeaderValue("text", 0.123));
}
[Fact]
public void TryParse_SetOfInvalidValueStrings_ReturnsFalse()
{
CheckInvalidTryParse("text,");
CheckInvalidTryParse("\r\n text ; q = 0.5, next_text ");
CheckInvalidTryParse(" text,next_text ");
CheckInvalidTryParse(" ,, text, , ,next");
CheckInvalidTryParse(" ,, text, , ,");
CheckInvalidTryParse(", \r\n text \r\n ; \r\n q = 0.123");
CheckInvalidTryParse("te\u00E4xt");
CheckInvalidTryParse("text\u4F1A");
CheckInvalidTryParse("\u4F1A");
CheckInvalidTryParse("t;q=\u4F1A");
CheckInvalidTryParse("t;q=");
CheckInvalidTryParse("t;q");
CheckInvalidTryParse("t;\u4F1A=1");
CheckInvalidTryParse("t;q\u4F1A=1");
CheckInvalidTryParse("t y");
CheckInvalidTryParse("t;q=1 y");
CheckInvalidTryParse(null);
CheckInvalidTryParse(string.Empty);
CheckInvalidTryParse(" ");
CheckInvalidTryParse(" ,,");
}
#region Helper methods
private void CheckValidParse(string input, StringWithQualityHeaderValue expectedResult)
{
StringWithQualityHeaderValue result = StringWithQualityHeaderValue.Parse(input);
Assert.Equal(expectedResult, result);
}
private void CheckInvalidParse(string input)
{
Assert.Throws<FormatException>(() => { StringWithQualityHeaderValue.Parse(input); });
}
private void CheckValidTryParse(string input, StringWithQualityHeaderValue expectedResult)
{
StringWithQualityHeaderValue result = null;
Assert.True(StringWithQualityHeaderValue.TryParse(input, out result));
Assert.Equal(expectedResult, result);
}
private void CheckInvalidTryParse(string input)
{
StringWithQualityHeaderValue result = null;
Assert.False(StringWithQualityHeaderValue.TryParse(input, out result));
Assert.Null(result);
}
private static void CallGetStringWithQualityLength(string input, int startIndex, int expectedLength,
out StringWithQualityHeaderValue result)
{
object temp = null;
Assert.Equal(expectedLength, StringWithQualityHeaderValue.GetStringWithQualityLength(input,
startIndex, out temp));
result = temp as StringWithQualityHeaderValue;
}
private static void CheckInvalidGetStringWithQualityLength(string input, int startIndex)
{
object result = null;
Assert.Equal(0, StringWithQualityHeaderValue.GetStringWithQualityLength(input, startIndex, out result));
Assert.Null(result);
}
#endregion
}
}
| |
/*
* DataGridColumnStyle.cs - Implementation of "System.Windows.Forms.DataGridColumnStyle"
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
* Copyright (C) 2004 Free Software Foundation, Inc.
* Copyright (C) 2005 Boris Manojlovic.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Windows.Forms
{
using System.Drawing;
using System.Text;
using System.ComponentModel;
using System.Reflection;
public abstract class DataGridColumnStyle : Component, IDataGridColumnStyleEditingNotificationService
{
[TODO]
public DataGridColumnStyle()
{
throw new NotImplementedException(".ctor");
}
[TODO]
public DataGridColumnStyle(System.ComponentModel.PropertyDescriptor prop)
{
throw new NotImplementedException(".ctor");
}
protected internal abstract void Abort(int rowNum);
[TODO]
protected void BeginUpdate()
{
throw new NotImplementedException("BeginUpdate");
}
[TODO]
protected void CheckValidDataSource(CurrencyManager value)
{
throw new NotImplementedException("CheckValidDataSource");
}
[TODO]
public virtual void ColumnStartedEditing(Control editingControl)
{
throw new NotImplementedException("ColumnStartedEditing");
}
protected internal abstract bool Commit(CurrencyManager dataSource, int rowNum);
[TODO]
protected internal virtual void ConcedeFocus()
{
throw new NotImplementedException("ConcedeFocus");
}
[TODO]
protected virtual AccessibleObject CreateHeaderAccessibleObject()
{
throw new NotImplementedException("CreateHeaderAccessibleObject");
}
[TODO]
protected internal virtual void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly)
{
throw new NotImplementedException("Edit");
}
[TODO]
protected internal virtual void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, System.String instantText)
{
throw new NotImplementedException("Edit");
}
protected internal abstract void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, System.String instantText, bool cellIsVisible);
[TODO]
protected void EndUpdate()
{
throw new NotImplementedException("EndUpdate");
}
[TODO]
protected internal virtual void EnterNullValue()
{
throw new NotImplementedException("EnterNullValue");
}
[TODO]
protected internal virtual System.Object GetColumnValueAtRow(CurrencyManager source, int rowNum)
{
throw new NotImplementedException("GetColumnValueAtRow");
}
protected internal abstract int GetMinimumHeight();
protected internal abstract int GetPreferredHeight(Graphics g, System.Object value);
protected internal abstract System.Drawing.Size GetPreferredSize(System.Drawing.Graphics g, System.Object value);
[TODO]
protected virtual void Invalidate()
{
throw new NotImplementedException("Invalidate");
}
protected internal abstract void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum);
protected internal abstract void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight);
[TODO]
protected internal virtual void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, Brush backBrush, Brush foreBrush, bool alignToRight)
{
throw new NotImplementedException("Paint");
}
[TODO]
protected internal virtual void ReleaseHostedControl()
{
throw new NotImplementedException("ReleaseHostedControl");
}
[TODO]
public void ResetHeaderText()
{
throw new NotImplementedException("ResetHeaderText");
}
[TODO]
protected internal virtual void SetColumnValueAtRow(CurrencyManager source, int rowNum, System.Object value)
{
throw new NotImplementedException("SetColumnValueAtRow");
}
[TODO]
protected virtual void SetDataGrid(System.Windows.Forms.DataGrid value)
{
throw new NotImplementedException("SetDataGrid");
}
[TODO]
protected virtual void SetDataGridInColumn(DataGrid value)
{
throw new NotImplementedException("SetDataGridInColumn");
}
[TODO]
protected internal virtual void UpdateUI(CurrencyManager source, int rowNum, System.String instantText)
{
throw new NotImplementedException("UpdateUI");
}
public event EventHandler AlignmentChanged
{
add
{
Events.AddHandler(EventId.AlignmentChanged,value);
}
remove
{
Events.RemoveHandler(EventId.AlignmentChanged,value);
}
}
public event EventHandler FontChanged
{
add
{
Events.AddHandler(EventId.FontChanged,value);
}
remove
{
Events.RemoveHandler(EventId.FontChanged,value);
}
}
public event EventHandler HeaderTextChanged
{
add
{
Events.AddHandler(EventId.HeaderTextChanged,value);
}
remove
{
Events.RemoveHandler(EventId.HeaderTextChanged,value);
}
}
public event EventHandler MappingNameChanged
{
add
{
Events.AddHandler(EventId.MappingNameChanged,value);
}
remove
{
Events.RemoveHandler(EventId.MappingNameChanged,value);
}
}
public event EventHandler NullTextChanged
{
add
{
Events.AddHandler(EventId.NullTextChanged,value);
}
remove
{
Events.RemoveHandler(EventId.NullTextChanged,value);
}
}
public event EventHandler PropertyDescriptorChanged
{
add
{
Events.AddHandler(EventId.PropertyDescriptorChanged,value);
}
remove
{
Events.RemoveHandler(EventId.PropertyDescriptorChanged,value);
}
}
public event EventHandler ReadOnlyChanged
{
add
{
Events.AddHandler(EventId.ReadOnlyChanged,value);
}
remove
{
Events.RemoveHandler(EventId.ReadOnlyChanged,value);
}
}
public event EventHandler WidthChanged
{
add
{
Events.AddHandler(EventId.WidthChanged,value);
}
remove
{
Events.RemoveHandler(EventId.WidthChanged,value);
}
}
[TODO]
public virtual HorizontalAlignment Alignment
{
get
{
throw new NotImplementedException("Alignment");
}
set
{
throw new NotImplementedException("Alignment");
}
}
[TODO]
public virtual DataGridTableStyle DataGridTableStyle
{
get
{
throw new NotImplementedException("DataGridTableStyle");
}
}
[TODO]
protected int FontHeight
{
get
{
throw new NotImplementedException("FontHeight");
}
}
[TODO]
public AccessibleObject HeaderAccessibleObject
{
get
{
throw new NotImplementedException("HeaderAccessibleObject");
}
}
[TODO]
public virtual System.String HeaderText
{
get
{
throw new NotImplementedException("HeaderText");
}
set
{
throw new NotImplementedException("HeaderText");
}
}
[TODO]
public System.String MappingName
{
get
{
throw new NotImplementedException("MappingName");
}
set
{
throw new NotImplementedException("MappingName");
}
}
[TODO]
public virtual System.String NullText
{
get
{
throw new NotImplementedException("NullText");
}
set
{
throw new NotImplementedException("NullText");
}
}
[TODO]
public virtual System.ComponentModel.PropertyDescriptor PropertyDescriptor
{
get
{
throw new NotImplementedException("PropertyDescriptor");
}
set
{
throw new NotImplementedException("PropertyDescriptor");
}
}
[TODO]
public virtual bool ReadOnly
{
get
{
throw new NotImplementedException("ReadOnly");
}
set
{
throw new NotImplementedException("ReadOnly");
}
}
[TODO]
public virtual int Width
{
get
{
throw new NotImplementedException("Width");
}
set
{
throw new NotImplementedException("Width");
}
}
}
}//namespace
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.