context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// activationobject.cs
//
// Copyright 2010 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
namespace Baker.Text
{
internal abstract class JsActivationObject
{
#region private fields
private bool m_useStrict;//= false;
private bool m_isKnownAtCompileTime;
private JsSettings m_settings;
#endregion
#region internal properties
/// <summary>
/// Gets or sets a boolean value for whether this is an existing scope or a new one
/// generated during the current run.
/// </summary>
internal bool Existing { get; set; }
#endregion
#region public properties
public bool UseStrict
{
get
{
return m_useStrict;
}
set
{
// can set it to true, but can't set it to false
if (value)
{
// set our value
m_useStrict = value;
// and all our child scopes (recursive)
foreach (var child in ChildScopes)
{
child.UseStrict = value;
}
}
}
}
public bool IsKnownAtCompileTime
{
get { return m_isKnownAtCompileTime; }
set
{
m_isKnownAtCompileTime = value;
if (!value
&& m_settings.EvalTreatment == JsEvalTreatment.MakeAllSafe)
{
// are we a function scope?
var funcScope = this as JsFunctionScope;
if (funcScope == null)
{
// we are not a function, so the parent scope is unknown too
Parent.IfNotNull(p => p.IsKnownAtCompileTime = false);
}
else
{
// we are a function, check to see if the function object is actually
// referenced. (we don't want to mark the parent as unknown if this function
// isn't even referenced).
if (funcScope.FunctionObject.IsReferenced)
{
Parent.IsKnownAtCompileTime = false;
}
}
}
}
}
public JsActivationObject Parent { get; private set; }
public bool IsInWithScope { get; set; }
public IDictionary<string, JsVariableField> NameTable { get; private set; }
public IList<JsActivationObject> ChildScopes { get; private set; }
public ICollection<JsLookup> ScopeLookups { get; private set; }
public ICollection<IJsNameDeclaration> VarDeclaredNames { get; private set; }
public ICollection<IJsNameDeclaration> LexicallyDeclaredNames { get; private set; }
public ICollection<JsParameterDeclaration> GhostedCatchParameters { get; private set; }
public ICollection<JsFunctionObject> GhostedFunctions { get; private set; }
#endregion
protected JsActivationObject(JsActivationObject parent, JsSettings codeSettings)
{
m_isKnownAtCompileTime = true;
m_useStrict = false;
m_settings = codeSettings;
Parent = parent;
NameTable = new Dictionary<string, JsVariableField>();
ChildScopes = new List<JsActivationObject>();
// if our parent is a scope....
if (parent != null)
{
// add us to the parent's list of child scopes
parent.ChildScopes.Add(this);
// if the parent is strict, so are we
UseStrict = parent.UseStrict;
}
// create the two lists of declared items for this scope
ScopeLookups = new HashSet<JsLookup>();
VarDeclaredNames = new HashSet<IJsNameDeclaration>();
LexicallyDeclaredNames = new HashSet<IJsNameDeclaration>();
GhostedCatchParameters = new HashSet<JsParameterDeclaration>();
GhostedFunctions = new HashSet<JsFunctionObject>();
}
#region scope setup methods
/// <summary>
/// Set up this scope's fields from the declarations it contains
/// </summary>
public abstract void DeclareScope();
protected void DefineLexicalDeclarations()
{
foreach (var lexDecl in LexicallyDeclaredNames)
{
// use the function as the field value if it's a function
DefineField(lexDecl, lexDecl as JsFunctionObject);
}
}
protected void DefineVarDeclarations()
{
foreach (var varDecl in VarDeclaredNames)
{
// var-decls are always initialized to null
DefineField(varDecl, null);
}
}
private void DefineField(IJsNameDeclaration nameDecl, JsFunctionObject fieldValue)
{
var field = this[nameDecl.Name];
if (nameDecl is JsParameterDeclaration)
{
// function parameters are handled separately, so if this is a parameter declaration,
// then it must be a catch variable.
if (field == null)
{
// no collision - create the catch-error field
field = new JsVariableField(JsFieldType.CatchError, nameDecl.Name, 0, null)
{
OriginalContext = nameDecl.NameContext,
IsDeclared = true
};
this.AddField(field);
}
else
{
// it's an error to declare anything in the catch scope with the same name as the
// error variable
field.OriginalContext.HandleError(JsError.DuplicateCatch, true);
}
}
else
{
if (field == null)
{
// could be global or local depending on the scope, so let the scope create it.
field = this.CreateField(nameDecl.Name, null, 0);
field.OriginalContext = nameDecl.NameContext;
field.IsDeclared = true;
field.IsFunction = (nameDecl is JsFunctionObject);
field.FieldValue = fieldValue;
// if this field is a constant, mark it now
var lexDeclaration = nameDecl.Parent as JsLexicalDeclaration;
field.InitializationOnly = nameDecl.Parent is JsConstStatement
|| (lexDeclaration != null && lexDeclaration.StatementToken == JsToken.Const);
this.AddField(field);
}
else
{
// already defined!
// if this is a lexical declaration, then it's an error because we have two
// lexical declarations with the same name in the same scope.
if (nameDecl.Parent is JsLexicalDeclaration)
{
nameDecl.NameContext.HandleError(JsError.DuplicateLexicalDeclaration, true);
}
if (nameDecl.Initializer != null)
{
// if this is an initialized declaration, then the var part is
// superfluous and the "initializer" is really a lookup assignment.
// So bump up the ref-count for those cases.
var nameReference = nameDecl as IJsNameReference;
if (nameReference != null)
{
field.AddReference(nameReference);
}
}
// don't clobber an existing field value with null. For instance, the last
// function declaration is the winner, so always set the value if we have something,
// but a var following a function shouldn't reset it to null.
if (fieldValue != null)
{
field.FieldValue = fieldValue;
}
}
}
nameDecl.VariableField = field;
field.Declarations.Add(nameDecl);
// if this scope is within a with-statement, or if the declaration was flagged
// as not being renamable, then mark the field as not crunchable
if (IsInWithScope || nameDecl.RenameNotAllowed)
{
field.CanCrunch = false;
}
}
#endregion
#region AnalyzeScope functionality
internal virtual void AnalyzeScope()
{
// global scopes override this and don't call the next
AnalyzeNonGlobalScope();
// rename fields if we need to
ManualRenameFields();
// recurse
foreach (var activationObject in ChildScopes)
{
activationObject.AnalyzeScope();
}
}
private void AnalyzeNonGlobalScope()
{
foreach (var variableField in NameTable.Values)
{
// not referenced, not generated, and has an original context so not added after the fact.
// and we don't care if catch-error fields are unreferenced.
if (!variableField.IsReferenced
&& !variableField.IsGenerated
&& variableField.OuterField == null
&& variableField.FieldType != JsFieldType.CatchError
&& variableField.FieldType != JsFieldType.GhostCatch
&& variableField.OriginalContext != null)
{
UnreferencedVariableField(variableField);
}
else if (variableField.RefCount == 1
&& this.IsKnownAtCompileTime
&& m_settings.RemoveUnneededCode
&& m_settings.IsModificationAllowed(JsTreeModifications.RemoveUnusedVariables))
{
SingleReferenceVariableField(variableField);
}
}
}
private void UnreferencedVariableField(JsVariableField variableField)
{
// see if the value is a function
var functionObject = variableField.FieldValue as JsFunctionObject;
if (functionObject != null)
{
UnreferencedFunction(variableField, functionObject);
}
else if (variableField.FieldType == JsFieldType.Argument)
{
UnreferencedArgument(variableField);
}
else if (!variableField.WasRemoved)
{
UnreferencedVariable(variableField);
}
}
private void UnreferencedFunction(JsVariableField variableField, JsFunctionObject functionObject)
{
// if there is no name, then ignore this declaration because it's malformed.
// (won't be a function expression because those are automatically referenced).
// also ignore ghosted function fields.
if (functionObject.Name != null && variableField.FieldType != JsFieldType.GhostFunction)
{
// if the function name isn't a simple identifier, then leave it there and mark it as
// not renamable because it's probably one of those darn IE-extension event handlers or something.
if (JsScanner.IsValidIdentifier(functionObject.Name))
{
// unreferenced function declaration. fire a warning.
var ctx = functionObject.IdContext ?? variableField.OriginalContext;
ctx.HandleError(JsError.FunctionNotReferenced, false);
// hide it from the output if our settings say we can.
// we don't want to delete it, per se, because we still want it to
// show up in the scope report so the user can see that it was unreachable
// in case they are wondering where it went.
// ES6 has the notion of block-scoped function declarations. ES5 says functions can't
// be defined inside blocks -- only at the root level of the global scope or function scopes.
// so if this is a block scope, don't hide the function, even if it is unreferenced because
// of the cross-browser difference.
if (this.IsKnownAtCompileTime
&& m_settings.MinifyCode
&& m_settings.RemoveUnneededCode
&& !(this is JsBlockScope))
{
functionObject.HideFromOutput = true;
}
}
else
{
// not a valid identifier name for this function. Don't rename it because it's
// malformed and we don't want to mess up the developer's intent.
variableField.CanCrunch = false;
}
}
}
private void UnreferencedArgument(JsVariableField variableField)
{
// unreferenced argument. We only want to throw a warning if there are no referenced arguments
// AFTER this unreferenced argument. Also, we're assuming that if this is an argument field,
// this scope MUST be a function scope.
var functionScope = this as JsFunctionScope;
if (functionScope != null)
{
if (functionScope.FunctionObject.IfNotNull(func => func.IsArgumentTrimmable(variableField)))
{
// if we are planning on removing unreferenced function parameters, mark it as removed
// so we don't waste a perfectly good auto-rename name on it later.
if (m_settings.RemoveUnneededCode
&& m_settings.IsModificationAllowed(JsTreeModifications.RemoveUnusedParameters))
{
variableField.WasRemoved = true;
}
variableField.OriginalContext.HandleError(
JsError.ArgumentNotReferenced,
false);
}
}
}
private void UnreferencedVariable(JsVariableField variableField)
{
var throwWarning = true;
// not a function, not an argument, not a catch-arg, not a global.
// not referenced. If there's a single definition, and it either has no
// initializer or the initializer is constant, get rid of it.
// (unless we aren't removing unneeded code, or the scope is unknown)
if (variableField.Declarations.Count == 1
&& this.IsKnownAtCompileTime)
{
var varDecl = variableField.OnlyDeclaration as JsVariableDeclaration;
if (varDecl != null)
{
var declaration = varDecl.Parent as JsDeclaration;
if (declaration != null
&& (varDecl.Initializer == null || varDecl.Initializer.IsConstant))
{
// if the decl parent is a for-in and the decl is the variable part
// of the statement, then just leave it alone. Don't even throw a warning
var forInStatement = declaration.Parent as JsForIn;
if (forInStatement != null
&& declaration == forInStatement.Variable)
{
// just leave it alone, and don't even throw a warning for it.
// TODO: try to reuse some pre-existing variable, or maybe replace
// this vardecl with a ref to an unused parameter if this is inside
// a function.
throwWarning = false;
}
else if (m_settings.RemoveUnneededCode
&& m_settings.IsModificationAllowed(JsTreeModifications.RemoveUnusedVariables))
{
variableField.Declarations.Remove(varDecl);
// don't "remove" the field if it's a ghost to another field
if (variableField.GhostedField == null)
{
variableField.WasRemoved = true;
}
// remove the vardecl from the declaration list, and if the
// declaration list is now empty, remove it, too
declaration.Remove(varDecl);
if (declaration.Count == 0)
{
declaration.Parent.ReplaceChild(declaration, null);
}
}
}
else if (varDecl.Parent is JsForIn)
{
// then this is okay
throwWarning = false;
}
}
}
if (throwWarning && variableField.HasNoReferences)
{
// not referenced -- throw a warning, assuming it hasn't been "removed"
// via an optimization or something.
variableField.OriginalContext.HandleError(
JsError.VariableDefinedNotReferenced,
false);
}
}
private static void SingleReferenceVariableField(JsVariableField variableField)
{
// local fields that don't reference an outer field, have only one refcount
// and one declaration
if (variableField.FieldType == JsFieldType.Local
&& variableField.OuterField == null
&& variableField.Declarations.Count == 1)
{
// there should only be one, it should be a vardecl, and
// either no initializer or a constant initializer
var varDecl = variableField.OnlyDeclaration as JsVariableDeclaration;
if (varDecl != null
&& varDecl.Initializer != null
&& varDecl.Initializer.IsConstant)
{
// there should only be one
var reference = variableField.OnlyReference;
if (reference != null)
{
// if the reference is not being assigned to, it is not an outer reference
// (meaning the lookup is in the same scope as the declaration), and the
// lookup is after the declaration
if (!reference.IsAssignment
&& reference.VariableField != null
&& reference.VariableField.OuterField == null
&& reference.VariableField.CanCrunch
&& varDecl.Index < reference.Index
&& !IsIterativeReference(varDecl.Initializer, reference))
{
// so we have a declaration assigning a constant value, and only one
// reference reading that value. replace the reference with the constant
// and get rid of the declaration.
// transform: var lookup=constant;lookup ==> constant
// remove the vardecl
var declaration = varDecl.Parent as JsDeclaration;
if (declaration != null)
{
// replace the reference with the constant
variableField.References.Remove(reference);
var refNode = reference as JsAstNode;
refNode.Parent.IfNotNull(p => p.ReplaceChild(refNode, varDecl.Initializer));
// we're also going to remove the declaration itself
variableField.Declarations.Remove(varDecl);
variableField.WasRemoved = true;
// remove the vardecl from the declaration list
// and if the declaration is now empty, remove it, too
declaration.Remove(varDecl);
if (declaration.Count == 0)
{
declaration.Parent.IfNotNull(p => p.ReplaceChild(declaration, null));
}
}
}
}
}
}
}
private static bool IsIterativeReference(JsAstNode initializer, IJsNameReference reference)
{
// we only care about array and regular expressions with the global switch at this point.
// if it's not one of those types, then go ahead and assume iterative reference doesn't matter.
var regExp = initializer as JsRegExpLiteral;
if (initializer is JsArrayLiteral
|| initializer is JsObjectLiteral
|| (regExp != null && regExp.PatternSwitches != null && regExp.PatternSwitches.IndexOf("g", StringComparison.OrdinalIgnoreCase) >= 0))
{
// get the parent block for the initializer. We'll use this as a stopping point in our loop.
var parentBlock = GetParentBlock(initializer);
// walk up the parent chain from the reference. If we find a while, a for, or a do-while,
// then we know this reference is iteratively called.
// stop when the parent is null, the same block containing the initializer, or a function object.
// (because a function object will step out of scope, and we know we should be in the same scope)
var child = reference as JsAstNode;
var parent = child.Parent;
while (parent != null && parent != parentBlock && !(parent is JsFunctionObject))
{
// while or do-while is iterative -- the condition and the body are both called repeatedly.
if (parent is JsWhileNode || parent is JsDoWhile)
{
return true;
}
// for-statements call the condition, the incrementer, and the body repeatedly, but not the
// initializer.
var forNode = parent as JsForNode;
if (forNode != null && child != forNode.Initializer)
{
return true;
}
// in forin-statements, only the body is repeated, the collection is evaluated only once.
var forInStatement = parent as JsForIn;
if (forInStatement != null && child == forInStatement.Body)
{
return true;
}
// go up
child = parent;
parent = parent.Parent;
}
}
return false;
}
/// <summary>
/// Return the first Block node in the tree starting from the given node and working up through the parent nodes.
/// </summary>
/// <param name="node">initial node</param>
/// <returns>first block node in the node tree</returns>
private static JsBlock GetParentBlock(JsAstNode node)
{
while(node != null)
{
// see if the current node is a block, and if so, return it.
var block = node as JsBlock;
if (block != null)
{
return block;
}
// try the parent
node = node.Parent;
}
// if we get here, we never found a parent block.
return null;
}
protected void ManualRenameFields()
{
// if the local-renaming kill switch is on, we won't be renaming ANYTHING, so we'll have nothing to do.
if (m_settings.IsModificationAllowed(JsTreeModifications.LocalRenaming))
{
// if the parser settings has a list of rename pairs, we will want to go through and rename
// any matches
if (m_settings.HasRenamePairs)
{
// go through the list of fields in this scope. Anything defined in the script that
// is in the parser rename map should be renamed and the auto-rename flag reset so
// we don't change it later.
foreach (var varField in NameTable.Values)
{
// don't rename outer fields (only actual fields),
// and we're only concerned with global or local variables --
// those which are defined by the script (not predefined, not the arguments object)
if (varField.OuterField == null
&& (varField.FieldType != JsFieldType.Arguments && varField.FieldType != JsFieldType.Predefined))
{
// see if the name is in the parser's rename map
string newName = m_settings.GetNewName(varField.Name);
if (!string.IsNullOrEmpty(newName))
{
// it is! Change the name of the field, but make sure we reset the CanCrunch flag
// or setting the "crunched" name won't work.
// and don't bother making sure the name doesn't collide with anything else that
// already exists -- if it does, that's the developer's fault.
// TODO: should we at least throw a warning?
varField.CanCrunch = true;
varField.CrunchedName = newName;
// and make sure we don't crunch it later
varField.CanCrunch = false;
}
}
}
}
// if the parser settings has a list of no-rename names, then we will want to also mark any
// fields that match and are still slated to rename as uncrunchable so they won't get renamed.
// if the settings say we're not going to renaming anything automatically (KeepAll), then we
// have nothing to do.
if (m_settings.LocalRenaming != JsLocalRenaming.KeepAll)
{
foreach (var noRename in m_settings.NoAutoRenameCollection)
{
// don't rename outer fields (only actual fields),
// and we're only concerned with fields that can still
// be automatically renamed. If the field is all that AND is listed in
// the collection, set the CanCrunch to false
JsVariableField varField;
if (NameTable.TryGetValue(noRename, out varField)
&& varField.OuterField == null
&& varField.CanCrunch)
{
// no, we don't want to crunch this field
varField.CanCrunch = false;
}
}
}
}
}
#endregion
#region crunching methods
internal void ValidateGeneratedNames()
{
// check all the variables defined within this scope.
// we're looking for uncrunched generated fields.
foreach (JsVariableField variableField in NameTable.Values)
{
if (variableField.IsGenerated
&& variableField.CrunchedName == null)
{
// we need to rename this field.
// first we need to walk all the child scopes depth-first
// looking for references to this field. Once we find a reference,
// we then need to add all the other variables referenced in those
// scopes and all above them (from here) so we know what names we
// can't use.
var avoidTable = new HashSet<string>();
GenerateAvoidList(avoidTable, variableField.Name);
// now that we have our avoid list, create a crunch enumerator from it
JsCrunchEnumerator crunchEnum = new JsCrunchEnumerator(avoidTable);
// and use it to generate a new name
variableField.CrunchedName = crunchEnum.NextName();
}
}
// recursively traverse through our children
foreach (JsActivationObject scope in ChildScopes)
{
if (!scope.Existing)
{
scope.ValidateGeneratedNames();
}
}
}
private bool GenerateAvoidList(HashSet<string> table, string name)
{
// our reference flag is based on what was passed to us
bool isReferenced = false;
// depth first, so walk all the children
foreach (JsActivationObject childScope in ChildScopes)
{
// if any child returns true, then it or one of its descendents
// reference this variable. So we reference it, too
if (childScope.GenerateAvoidList(table, name))
{
// we'll return true because we reference it
isReferenced = true;
}
}
if (!isReferenced)
{
// none of our children reference the scope, so see if we do
isReferenced = NameTable.ContainsKey(name);
}
if (isReferenced)
{
// if we reference the name or are in line to reference the name,
// we need to add all the variables we reference to the list
foreach (var variableField in NameTable.Values)
{
table.Add(variableField.ToString());
}
}
// return whether or not we are in the reference chain
return isReferenced;
}
internal virtual void AutoRenameFields()
{
// if we're not known at compile time, then we can't crunch
// the local variables in this scope, because we can't know if
// something will reference any of it at runtime.
// eval is something that will make the scope unknown because we
// don't know what eval will evaluate to until runtime
if (m_isKnownAtCompileTime)
{
// get an array of all the uncrunched local variables defined in this scope
var localFields = GetUncrunchedLocals();
if (localFields != null)
{
// create a crunch-name enumerator, taking into account any fields within our
// scope that have already been crunched.
var avoidSet = new HashSet<string>();
foreach (var field in NameTable.Values)
{
// if the field can't be crunched, or if it can but we've already crunched it,
// or if it's an outer variable (that hasn't been generated) and its OWNING scope isn't known
// (and therefore we CANNOT crunch it),
// then add it to the avoid list so we don't reuse that name
if (!field.CanCrunch || field.CrunchedName != null
|| (field.OuterField != null && !field.IsGenerated && field.OwningScope != null && !field.OwningScope.IsKnownAtCompileTime))
{
avoidSet.Add(field.ToString());
}
}
var crunchEnum = new JsCrunchEnumerator(avoidSet);
foreach (var localField in localFields)
{
// if we are an unambiguous reference to a named function expression and we are not
// referenced by anyone else, then we can just skip this variable because the
// name will be stripped from the output anyway.
// we also always want to crunch "placeholder" fields.
if (localField.CanCrunch
&& (localField.RefCount > 0 || localField.IsDeclared || localField.IsPlaceholder
|| !(m_settings.RemoveFunctionExpressionNames && m_settings.IsModificationAllowed(JsTreeModifications.RemoveFunctionExpressionNames))))
{
localField.CrunchedName = crunchEnum.NextName();
}
}
}
}
// then traverse through our children
foreach (JsActivationObject scope in ChildScopes)
{
scope.AutoRenameFields();
}
}
internal IEnumerable<JsVariableField> GetUncrunchedLocals()
{
// there can't be more uncrunched fields than total fields
var list = new List<JsVariableField>(NameTable.Count);
foreach (var variableField in NameTable.Values)
{
// if the field is defined in this scope and hasn't been crunched
// AND can still be crunched AND wasn't removed during the optimization process
if (variableField != null && variableField.OuterField == null && variableField.CrunchedName == null
&& variableField.CanCrunch && !variableField.WasRemoved)
{
// if local renaming is not crunch all, then it must be crunch all but localization
// (we don't get called if we aren't crunching anything).
// SO for the first clause:
// IF we are crunch all, we're good; but if we aren't crunch all, then we're only good if
// the name doesn't start with "L_".
// The second clause is only computed IF we already think we're good to go.
// IF we aren't preserving function names, then we're good. BUT if we are, we're
// only good to go if this field doesn't represent a function object.
if ((m_settings.LocalRenaming == JsLocalRenaming.CrunchAll
|| !variableField.Name.StartsWith("L_", StringComparison.Ordinal))
&& !(m_settings.PreserveFunctionNames && variableField.IsFunction))
{
// don't add to our list if it's a function that's going to be hidden anyway
JsFunctionObject funcObject;
if (!variableField.IsFunction
|| (funcObject = variableField.FieldValue as JsFunctionObject) == null
|| !funcObject.HideFromOutput)
{
list.Add(variableField);
}
}
}
}
if (list.Count == 0)
{
return null;
}
// sort the array and return it
list.Sort(ReferenceComparer.Instance);
return list;
}
#endregion
#region field-management methods
public virtual JsVariableField this[string name]
{
get
{
JsVariableField variableField;
// check to see if this name is already defined in this scope
if (!NameTable.TryGetValue(name, out variableField))
{
// not in this scope
variableField = null;
}
return variableField;
}
}
public JsVariableField FindReference(string name)
{
// see if we have it
var variableField = this[name];
// if we didn't find anything and this scope has a parent
if (variableField == null)
{
if (this.Parent != null)
{
// recursively go up the scope chain to find a reference,
// then create an inner field to point to it and we'll return
// that one.
variableField = CreateInnerField(this.Parent.FindReference(name));
// mark it as a placeholder. we might be going down a chain of scopes,
// where we will want to reserve the variable name, but not actually reference it.
// at the end where it is actually referenced we will reset the flag.
variableField.IsPlaceholder = true;
}
else
{
// must be global scope. the field is undefined!
variableField = AddField(new JsVariableField(JsFieldType.UndefinedGlobal, name, 0, null));
}
}
return variableField;
}
public virtual JsVariableField DeclareField(string name, object value, FieldAttributes attributes)
{
JsVariableField variableField;
if (!NameTable.TryGetValue(name, out variableField))
{
variableField = CreateField(name, value, attributes);
AddField(variableField);
}
return variableField;
}
public virtual JsVariableField CreateField(JsVariableField outerField)
{
// use the same type as the outer field by default
return outerField.IfNotNull(o => new JsVariableField(o.FieldType, o));
}
public abstract JsVariableField CreateField(string name, object value, FieldAttributes attributes);
public virtual JsVariableField CreateInnerField(JsVariableField outerField)
{
JsVariableField innerField = null;
if (outerField != null)
{
// create a new inner field to be added to our scope
innerField = CreateField(outerField);
AddField(innerField);
}
return innerField;
}
internal JsVariableField AddField(JsVariableField variableField)
{
// add it to our name table
NameTable[variableField.Name] = variableField;
// set the owning scope to this is we are the outer field, or the outer field's
// owning scope if this is an inner field
variableField.OwningScope = variableField.OuterField == null ? this : variableField.OuterField.OwningScope;
return variableField;
}
public IJsNameDeclaration VarDeclaredName(string name)
{
// check each var-decl name from inside this scope
foreach (var varDecl in this.VarDeclaredNames)
{
// if the name matches, return the field
if (string.CompareOrdinal(varDecl.Name, name) == 0)
{
return varDecl;
}
}
// if we get here, we didn't find a match
return null;
}
public IJsNameDeclaration LexicallyDeclaredName(string name)
{
// check each var-decl name from inside this scope
foreach (var lexDecl in this.LexicallyDeclaredNames)
{
// if the name matches, return the field
if (string.CompareOrdinal(lexDecl.Name, name) == 0)
{
return lexDecl;
}
}
// if we get here, we didn't find a match
return null;
}
public void AddGlobal(string name)
{
// first, go up to the global scope
var scope = this;
while (scope.Parent != null)
{
scope = scope.Parent;
}
// now see if there is a field with that name already;
// will return a non-null field object if there is.
var field = scope[name];
if (field == null)
{
// nothing with this name. Add it as a global field
scope.AddField(scope.CreateField(name, null, 0));
}
}
#endregion
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Globalization;
using System.Threading;
namespace System
{
static partial class CoreExtensions
{
/// <summary>
/// Timeouts the invoke.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
public static void TimeoutInvoke(this Action source, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action action = () => { threadToKill = Thread.CurrentThread; source(); };
var result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
action.EndInvoke(result);
return;
}
threadToKill.Abort();
throw new TimeoutException();
}
/// <summary>
/// Timeouts the invoke.
/// </summary>
/// <typeparam name="T1">The type of the 1.</typeparam>
/// <param name="source">The source.</param>
/// <param name="arg1">The arg1.</param>
/// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
public static void TimeoutInvoke<T1>(this Action<T1> source, T1 arg1, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action action = () => { threadToKill = Thread.CurrentThread; source(arg1); };
var result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
action.EndInvoke(result);
return;
}
threadToKill.Abort();
throw new TimeoutException();
}
/// <summary>
/// Timeouts the invoke.
/// </summary>
/// <typeparam name="T1">The type of the 1.</typeparam>
/// <typeparam name="T2">The type of the 2.</typeparam>
/// <param name="source">The source.</param>
/// <param name="arg1">The arg1.</param>
/// <param name="arg2">The arg2.</param>
/// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
public static void TimeoutInvoke<T1, T2>(this Action<T1, T2> source, T1 arg1, T2 arg2, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2); };
var result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
action.EndInvoke(result);
return;
}
threadToKill.Abort();
throw new TimeoutException();
}
/// <summary>
/// Timeouts the invoke.
/// </summary>
/// <typeparam name="T1">The type of the 1.</typeparam>
/// <typeparam name="T2">The type of the 2.</typeparam>
/// <typeparam name="T3">The type of the 3.</typeparam>
/// <param name="source">The source.</param>
/// <param name="arg1">The arg1.</param>
/// <param name="arg2">The arg2.</param>
/// <param name="arg3">The arg3.</param>
/// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
public static void TimeoutInvoke<T1, T2, T3>(this Action<T1, T2, T3> source, T1 arg1, T2 arg2, T3 arg3, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3); };
var result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
action.EndInvoke(result);
return;
}
threadToKill.Abort();
throw new TimeoutException();
}
/// <summary>
/// Timeouts the invoke.
/// </summary>
/// <typeparam name="T1">The type of the 1.</typeparam>
/// <typeparam name="T2">The type of the 2.</typeparam>
/// <typeparam name="T3">The type of the 3.</typeparam>
/// <typeparam name="T4">The type of the 4.</typeparam>
/// <param name="source">The source.</param>
/// <param name="arg1">The arg1.</param>
/// <param name="arg2">The arg2.</param>
/// <param name="arg3">The arg3.</param>
/// <param name="arg4">The arg4.</param>
/// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
public static void TimeoutInvoke<T1, T2, T3, T4>(this Action<T1, T2, T3, T4> source, T1 arg1, T2 arg2, T3 arg3, T4 arg4, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3, arg4); };
var result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
action.EndInvoke(result);
return;
}
threadToKill.Abort();
throw new TimeoutException();
}
#if CLR4
/// <summary>
/// Tries the timeout.
/// </summary>
/// <typeparam name="T1">The type of the 1.</typeparam>
/// <typeparam name="T2">The type of the 2.</typeparam>
/// <typeparam name="T3">The type of the 3.</typeparam>
/// <typeparam name="T4">The type of the 4.</typeparam>
/// <typeparam name="T5">The type of the 5.</typeparam>
/// <param name="source">The source.</param>
/// <param name="arg1">The arg1.</param>
/// <param name="arg2">The arg2.</param>
/// <param name="arg3">The arg3.</param>
/// <param name="arg4">The arg4.</param>
/// <param name="arg5">The arg5.</param>
/// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
public static void TryTimeout<T1, T2, T3, T4, T5>(this Action<T1, T2, T3, T4, T5> source, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3, arg4, arg5); };
var result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
action.EndInvoke(result);
return;
}
threadToKill.Abort();
throw new TimeoutException();
}
/// <summary>
/// Tries the timeout.
/// </summary>
/// <typeparam name="T1">The type of the 1.</typeparam>
/// <typeparam name="T2">The type of the 2.</typeparam>
/// <typeparam name="T3">The type of the 3.</typeparam>
/// <typeparam name="T4">The type of the 4.</typeparam>
/// <typeparam name="T5">The type of the 5.</typeparam>
/// <typeparam name="T6">The type of the 6.</typeparam>
/// <param name="source">The source.</param>
/// <param name="arg1">The arg1.</param>
/// <param name="arg2">The arg2.</param>
/// <param name="arg3">The arg3.</param>
/// <param name="arg4">The arg4.</param>
/// <param name="arg5">The arg5.</param>
/// <param name="arg6">The arg6.</param>
/// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
public static void TryTimeout<T1, T2, T3, T4, T5, T6>(this Action<T1, T2, T3, T4, T5, T6> source, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3, arg4, arg5, arg6); };
var result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
action.EndInvoke(result);
return;
}
threadToKill.Abort();
throw new TimeoutException();
}
/// <summary>
/// Tries the timeout.
/// </summary>
/// <typeparam name="T1">The type of the 1.</typeparam>
/// <typeparam name="T2">The type of the 2.</typeparam>
/// <typeparam name="T3">The type of the 3.</typeparam>
/// <typeparam name="T4">The type of the 4.</typeparam>
/// <typeparam name="T5">The type of the 5.</typeparam>
/// <typeparam name="T6">The type of the 6.</typeparam>
/// <typeparam name="T7">The type of the 7.</typeparam>
/// <param name="source">The source.</param>
/// <param name="arg1">The arg1.</param>
/// <param name="arg2">The arg2.</param>
/// <param name="arg3">The arg3.</param>
/// <param name="arg4">The arg4.</param>
/// <param name="arg5">The arg5.</param>
/// <param name="arg6">The arg6.</param>
/// <param name="arg7">The arg7.</param>
/// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
public static void TryTimeout<T1, T2, T3, T4, T5, T6, T7>(this Action<T1, T2, T3, T4, T5, T6, T7> source, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3, arg4, arg5, arg6, arg7); };
var result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
action.EndInvoke(result);
return;
}
threadToKill.Abort();
throw new TimeoutException();
}
/// <summary>
/// Tries the timeout.
/// </summary>
/// <typeparam name="T1">The type of the 1.</typeparam>
/// <typeparam name="T2">The type of the 2.</typeparam>
/// <typeparam name="T3">The type of the 3.</typeparam>
/// <typeparam name="T4">The type of the 4.</typeparam>
/// <typeparam name="T5">The type of the 5.</typeparam>
/// <typeparam name="T6">The type of the 6.</typeparam>
/// <typeparam name="T7">The type of the 7.</typeparam>
/// <typeparam name="T8">The type of the 8.</typeparam>
/// <param name="source">The source.</param>
/// <param name="arg1">The arg1.</param>
/// <param name="arg2">The arg2.</param>
/// <param name="arg3">The arg3.</param>
/// <param name="arg4">The arg4.</param>
/// <param name="arg5">The arg5.</param>
/// <param name="arg6">The arg6.</param>
/// <param name="arg7">The arg7.</param>
/// <param name="arg8">The arg8.</param>
/// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
public static void TryTimeout<T1, T2, T3, T4, T5, T6, T7, T8>(this Action<T1, T2, T3, T4, T5, T6, T7, T8> source, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); };
var result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
action.EndInvoke(result);
return;
}
threadToKill.Abort();
throw new TimeoutException();
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
namespace Stratus.AI
{
public class StratusBehaviorTreeEditorWindow : StratusEditorWindow<StratusBehaviorTreeEditorWindow>
{
//----------------------------------------------------------------------/
// Declarations
//----------------------------------------------------------------------/
public enum Mode
{
Editor = 0,
Debugger = 1,
}
public class BehaviourTreeView : StratusHierarchicalTreeView<BehaviorTree.BehaviorNode>
{
private StratusBehaviorTreeEditorWindow window => StratusBehaviorTreeEditorWindow.instance;
private BehaviorTree tree => StratusBehaviorTreeEditorWindow.instance.behaviorTree;
public BehaviourTreeView(TreeViewState state, IList<BehaviorTree.BehaviorNode> data) : base(state, data)
{
}
protected override bool IsParentValid(BehaviorTree.BehaviorNode parent)
{
//Trace.Script($"Parent type = {parent.dataType}");
if (parent.data == null)
{
return false;
}
if (parent.data is StratusAIComposite)
{
return true;
}
else if (parent.data is StratusAIDecorator && !parent.hasChildren)
{
return true;
}
return false;
}
protected override void OnItemContextMenu(GenericMenu menu, BehaviorTree.BehaviorNode treeElement)
{
// Tasks
if (treeElement.data is StratusAITask)
{
BehaviorTree.BehaviorNode parent = treeElement.GetParent<BehaviorTree.BehaviorNode>();
menu.AddItem("Duplicate", false, () => this.window.AddNode((StratusAIBehavior)treeElement.data.Clone(), parent));
menu.AddPopup("Add/Decorator", StratusBehaviorTreeEditorWindow.decoratorTypes.displayedOptions, (int index) =>
{
this.window.AddParentNode(StratusBehaviorTreeEditorWindow.decoratorTypes.AtIndex(index), treeElement);
});
}
// Composites
else if (treeElement.data is StratusAIComposite)
{
menu.AddPopup("Add/Tasks", StratusBehaviorTreeEditorWindow.taskTypes.displayedOptions, (int index) =>
{
this.window.AddChildNode(StratusBehaviorTreeEditorWindow.taskTypes.AtIndex(index), treeElement);
});
menu.AddPopup("Add/Composites", StratusBehaviorTreeEditorWindow.compositeTypes.displayedOptions, (int index) =>
{
this.window.AddChildNode(StratusBehaviorTreeEditorWindow.compositeTypes.AtIndex(index), treeElement);
});
menu.AddPopup("Add/Decorator", StratusBehaviorTreeEditorWindow.decoratorTypes.displayedOptions, (int index) =>
{
this.window.AddParentNode(StratusBehaviorTreeEditorWindow.decoratorTypes.AtIndex(index), treeElement);
});
menu.AddPopup("Replace", StratusBehaviorTreeEditorWindow.compositeTypes.displayedOptions, (int index) =>
{
this.window.ReplaceNode(treeElement, StratusBehaviorTreeEditorWindow.compositeTypes.AtIndex(index));
});
}
// Decorators
else if (treeElement.data is StratusAIDecorator)
{
if (!treeElement.hasChildren)
{
menu.AddPopup("Add/Tasks", StratusBehaviorTreeEditorWindow.taskTypes.displayedOptions, (int index) =>
{
this.window.AddChildNode(StratusBehaviorTreeEditorWindow.taskTypes.AtIndex(index), treeElement);
});
menu.AddPopup("Add/Composites", StratusBehaviorTreeEditorWindow.compositeTypes.displayedOptions, (int index) =>
{
this.window.AddChildNode(StratusBehaviorTreeEditorWindow.compositeTypes.AtIndex(index), treeElement);
});
}
}
// Common
if (treeElement.hasChildren)
{
menu.AddItem("Remove/Include Children", false, () => this.window.RemoveNode(treeElement));
menu.AddItem("Remove/Exclude Children", false, () => this.window.RemoveNodeOnly(treeElement));
}
else
{
menu.AddItem("Remove", false, () => this.window.RemoveNode(treeElement));
}
}
protected override void OnContextMenu(GenericMenu menu)
{
// Composite
menu.AddPopup("Add/Composites", StratusBehaviorTreeEditorWindow.compositeTypes.displayedOptions, (int index) =>
{
this.window.AddChildNode(StratusBehaviorTreeEditorWindow.compositeTypes.AtIndex(index));
});
// Actions
menu.AddPopup("Add/Tasks", StratusBehaviorTreeEditorWindow.taskTypes.displayedOptions, (int index) =>
{
this.window.AddChildNode(StratusBehaviorTreeEditorWindow.taskTypes.AtIndex(index));
});
menu.AddItem("Clear", false, () => this.window.RemoveAllNodes());
}
protected override void OnBeforeRow(Rect rect, TreeViewItem<BehaviorTree.BehaviorNode> treeViewItem)
{
if (treeViewItem.item.data is StratusAIComposite)
{
StratusGUI.GUIBox(rect, StratusAIComposite.color);
}
else if (treeViewItem.item.data is StratusAITask)
{
StratusGUI.GUIBox(rect, StratusAITask.color);
}
else if (treeViewItem.item.data is StratusAIDecorator)
{
StratusGUI.GUIBox(rect, StratusAIDecorator.color);
}
}
}
//----------------------------------------------------------------------/
// Fields
//----------------------------------------------------------------------/
[SerializeField]
private BehaviourTreeView treeInspector;
[SerializeField]
private TreeViewState treeViewState;
[SerializeField]
private Mode mode = Mode.Editor;
[SerializeField]
private StratusAgent selectedAgent;
[SerializeField]
public BehaviorTree behaviorTree;
private StratusSerializedEditorObject currentNodeSerializedObject;
private const string folder = "Stratus/Experimental/AI/";
private Vector2 inspectorScrollPosition, blackboardScrollPosition;
private StratusSerializedPropertyMap behaviorTreeProperties;
private StratusEditor blackboardEditor;
private string[] toolbarOptions = new string[]
{
nameof(Mode.Editor),
nameof(Mode.Debugger),
};
//----------------------------------------------------------------------/
// Properties
//----------------------------------------------------------------------/
private static Type compositeType { get; } = typeof(StratusAIComposite);
private static Type decoratorType { get; } = typeof(StratusAIDecorator);
/// <summary>
/// All supported behavior types
/// </summary>
public static StratusTypeSelector behaviorTypes { get; } = StratusTypeSelector.FilteredSelector(typeof(StratusAIBehavior), typeof(StratusAIService), false, true);
/// <summary>
/// All supported decorator types
/// </summary>
public static StratusTypeSelector compositeTypes { get; } = new StratusTypeSelector(typeof(StratusAIComposite), false, true);
/// <summary>
/// All supported decorator types
/// </summary>
public static StratusTypeSelector taskTypes { get; } = new StratusTypeSelector(typeof(StratusAITask), false, true);
/// <summary>
/// All supported decorator types
/// </summary>
public static StratusTypeSelector serviceTypes { get; } = new StratusTypeSelector(typeof(StratusAIService), false, true);
/// <summary>
/// All supported decorator types
/// </summary>
public static StratusTypeSelector decoratorTypes { get; } = new StratusTypeSelector(typeof(StratusAIDecorator), false, true);
/// <summary>
/// The blackboard being used by the tree
/// </summary>
private StratusBlackboard blackboard => this.behaviorTree.blackboard;
/// <summary>
/// The scope of the blackboard being inspected
/// </summary>
private StratusBlackboard.Scope scope;
/// <summary>
/// The nodes currently being inspected
/// </summary>
public IList<BehaviorTree.BehaviorNode> currentNodes { get; private set; }
/// <summary>
/// The nodes currently being inspected
/// </summary>
public BehaviorTree.BehaviorNode currentNode { get; private set; }
public bool hasSelection => this.currentNodes != null;
/// <summary>
/// Whether the editor for the BT has been initialized
/// </summary>
private bool isTreeSet => this.behaviorTree != null && this.behaviorTreeProperties != null;
/// <summary>
/// Whether the blackboard has been set
/// </summary>
private bool isBlackboardSet => this.blackboardEditor;
//----------------------------------------------------------------------/
// Messages
//----------------------------------------------------------------------/
protected override void OnWindowEnable()
{
if (this.treeViewState == null)
{
this.treeViewState = new TreeViewState();
}
if (this.behaviorTree)
{
this.treeInspector = new BehaviourTreeView(this.treeViewState, this.behaviorTree.tree.elements);
this.OnTreeSet();
}
else
{
//TreeBuilder<BehaviorTree.BehaviorNode, Behavior> treeBuilder = new TreeBuilder<BehaviorTree.BehaviorNode, Behavior>();
var tree = new StratusSerializedTree<BehaviorTree.BehaviorNode, StratusAIBehavior>();
this.treeInspector = new BehaviourTreeView(this.treeViewState, tree.elements);
}
this.treeInspector.onSelectionIdsChanged += this.OnSelectionChanged;
this.treeInspector.Reload();
}
protected override void OnWindowGUI()
{
StratusEditorGUI.BeginAligned(TextAlignment.Center);
this.mode = (Mode)GUILayout.Toolbar((int)this.mode, this.toolbarOptions, GUILayout.ExpandWidth(false));
StratusEditorGUI.EndAligned();
GUILayout.Space(padding);
switch (this.mode)
{
case Mode.Editor:
this.DrawEditor();
break;
case Mode.Debugger:
this.DrawDebugger();
break;
}
}
private void OnSelectionChange()
{
Debug.Log("Selection changed!");
if (Selection.activeGameObject != null)
{
var agent = Selection.activeGameObject.GetComponent<StratusAgent>();
if (agent != null)
{
OnAgentSelected(agent);
}
}
}
//----------------------------------------------------------------------/
// Procedures
//----------------------------------------------------------------------/
private void DrawEditor()
{
//EditProperty(nameof(this.behaviorTree));
if (this.InspectObjectFieldWithHeader(ref this.behaviorTree, "Behavior Tree"))
{
this.OnTreeSet();
}
if (!this.isTreeSet)
{
return;
}
//if (StratusEditorUtility.currentEvent.type != EventType.Repaint)
// return;
Rect rect = this.currentPosition; // this.currentPosition;
rect = StratusEditorUtility.Pad(rect);
rect = StratusEditorUtility.PadVertical(rect, lineHeight * 5f);
// Hierarchy: LEFT
rect.width *= 0.5f;
this.DrawHierarchy(rect);
// Inspector: TOP-RIGHT
rect.x += rect.width;
rect.width -= StratusEditorGUI.standardPadding;
rect.height *= 0.5f;
rect.height -= padding * 2f;
this.DrawInspector(rect);
// Blackboard: BOTTOM-RIGHT
rect.y += rect.height;
rect.y += padding;
this.DrawBlackboard(rect);
}
private void DrawDebugger()
{
//EditProperty(nameof(this.agent));
//EditProperty(nameof(debugTarget));
this.InspectObjectFieldWithHeader(ref this.selectedAgent, "Agent");
if (selectedAgent != null)
{
}
}
private void DrawHierarchy(Rect rect)
{
//if (behaviorTree != null)
//GUI.BeginGroup(rect);
GUILayout.BeginArea(rect);
GUILayout.Label("Hierarchy", StratusGUIStyles.header);
//rect.y += lineHeight * 2f;
GUILayout.EndArea();
//GUI.EndGroup();
float offset = lineHeight * 3f;
rect = StratusEditorUtility.RaiseVertical(rect, offset);
this.treeInspector?.TreeViewGUI(rect);
//rect = StratusEditorUtility.PadVertical(rect, lineHeight);
}
private void DrawInspector(Rect rect)
{
GUILayout.BeginArea(rect);
GUILayout.Label("Inspector", StratusGUIStyles.header);
if (this.hasSelection)
{
if (this.currentNodes.Count == 1)
{
GUILayout.Label(this.currentNode.dataTypeName, EditorStyles.largeLabel);
this.inspectorScrollPosition = GUILayout.BeginScrollView(this.inspectorScrollPosition, GUI.skin.box);
//this.currentNodeSerializedObject.DrawEditorGUI(rect);
this.currentNodeSerializedObject.DrawEditorGUILayout();
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("Editing multiple nodes is not supported!", EditorStyles.largeLabel);
}
}
GUILayout.EndArea();
}
private void DrawBlackboard(Rect rect)
{
GUILayout.BeginArea(rect);
GUILayout.Label("Blackboard", StratusGUIStyles.header);
{
// Set the blackboard
SerializedProperty blackboardProperty = this.behaviorTreeProperties.GetProperty(nameof(BehaviorTree.blackboard));
bool changed = this.InspectProperty(blackboardProperty, "Asset");
if (changed && this.blackboard != null)
{
this.OnBlackboardSet();
}
EditorGUILayout.Space();
// Draw the blackboard
if (this.blackboardEditor != null)
{
// Controls
StratusEditorGUI.BeginAligned(TextAlignment.Center);
StratusEditorGUI.EnumToolbar(ref this.scope);
StratusEditorGUI.EndAligned();
this.blackboardScrollPosition = EditorGUILayout.BeginScrollView(this.blackboardScrollPosition, GUI.skin.box);
switch (this.scope)
{
case StratusBlackboard.Scope.Local:
this.blackboardEditor.DrawSerializedProperty(nameof(StratusBlackboard.locals));
break;
case StratusBlackboard.Scope.Global:
this.blackboardEditor.DrawSerializedProperty(nameof(StratusBlackboard.globals));
break;
}
EditorGUILayout.EndScrollView();
}
}
GUILayout.EndArea();
}
//----------------------------------------------------------------------/
// Methods: Private
//----------------------------------------------------------------------/
private void AddChildNode(Type type, BehaviorTree.BehaviorNode parent = null)
{
if (parent != null)
{
this.behaviorTree.AddBehavior(type, parent);
}
else
{
this.behaviorTree.AddBehavior(type);
}
this.Save();
}
private void AddParentNode(Type type, BehaviorTree.BehaviorNode child)
{
this.behaviorTree.AddParentBehavior(type, child);
this.Save();
}
private void AddNode(StratusAIBehavior behavior, BehaviorTree.BehaviorNode parent = null)
{
if (parent != null)
{
this.behaviorTree.AddBehavior(behavior, parent);
}
else
{
this.behaviorTree.AddBehavior(behavior);
}
this.Save();
}
private void RemoveNode(BehaviorTree.BehaviorNode node)
{
this.currentNodeSerializedObject = null;
this.currentNodes = null;
this.behaviorTree.RemoveBehavior(node);
this.Save();
}
private void RemoveNodeOnly(BehaviorTree.BehaviorNode node)
{
this.currentNodeSerializedObject = null;
this.currentNodes = null;
this.behaviorTree.RemoveBehaviorExcludeChildren(node);
this.Save();
}
private void ReplaceNode(BehaviorTree.BehaviorNode node, Type behaviorType)
{
this.currentNodeSerializedObject = null;
this.currentNodes = null;
this.behaviorTree.ReplaceBehavior(node, behaviorType);
this.Save();
}
private void RemoveAllNodes()
{
this.behaviorTree.ClearBehaviors();
this.currentNodeSerializedObject = null;
this.currentNodes = null;
this.Save();
}
private void Refresh()
{
this.treeInspector.SetTree(this.behaviorTree.tree.elements);
this.Repaint();
}
private void OnTreeSet()
{
this.behaviorTree.Assert();
this.behaviorTreeProperties = new StratusSerializedPropertyMap(this.behaviorTree, typeof(StratusScriptable));
// Blackboard
this.blackboardEditor = null;
if (this.blackboard)
{
this.OnBlackboardSet();
}
this.Refresh();
}
private void OnBlackboardSet()
{
this.blackboardEditor = StratusEditor.CreateEditor(this.behaviorTree.blackboard) as StratusEditor;
}
private void Save()
{
EditorUtility.SetDirty(this.behaviorTree);
Undo.RecordObject(this.behaviorTree, "Behavior Tree Edit");
this.Refresh();
}
private void OnSelectionChanged(IList<int> ids)
{
this.currentNodeSerializedObject = null;
//this.currentNodeProperty = null;
this.currentNodes = this.treeInspector.GetElements(ids);
if (this.currentNodes.Count > 0)
{
this.currentNode = this.currentNodes[0];
this.currentNodeSerializedObject = new StratusSerializedEditorObject(this.currentNode.data);
//SerializedObject boo = new SerializedObject(currentNode.data);
//this.currentNodeProperty = this.treeElementsProperty.GetArrayElementAtIndex(ids[0]);
}
}
private void OnAgentSelected(StratusAgent agent)
{
this.selectedAgent = agent;
}
//----------------------------------------------------------------------/
// Methods: Static
//----------------------------------------------------------------------/
[OnOpenAsset]
public static bool OnOpenAsset(int instanceID, int line)
{
BehaviorTree myTreeAsset = EditorUtility.InstanceIDToObject(instanceID) as BehaviorTree;
if (myTreeAsset != null)
{
Open(myTreeAsset);
return true;
}
return false;
}
public static void Open(BehaviorTree tree)
{
OnOpen("Behavior Tree");
instance.SetTree(tree);
}
public void SetTree(BehaviorTree tree)
{
this.behaviorTree = tree;
this.OnTreeSet();
}
}
}
| |
using System;
using System.IO;
using CatLib._3rd.ICSharpCode.SharpZipLib.Checksum;
using CatLib._3rd.ICSharpCode.SharpZipLib.Zip.Compression;
using CatLib._3rd.ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace CatLib._3rd.ICSharpCode.SharpZipLib.GZip
{
/// <summary>
/// This filter stream is used to compress a stream into a "GZIP" stream.
/// The "GZIP" format is described in RFC 1952.
///
/// author of the original java version : John Leuner
/// </summary>
/// <example> This sample shows how to gzip a file
/// <code>
/// using System;
/// using System.IO;
///
/// using ICSharpCode.SharpZipLib.GZip;
/// using ICSharpCode.SharpZipLib.Core;
///
/// class MainClass
/// {
/// public static void Main(string[] args)
/// {
/// using (Stream s = new GZipOutputStream(File.Create(args[0] + ".gz")))
/// using (FileStream fs = File.OpenRead(args[0])) {
/// byte[] writeData = new byte[4096];
/// Streamutils.Copy(s, fs, writeData);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public class GZipOutputStream : DeflaterOutputStream
{
enum OutputState
{
Header,
Footer,
Finished,
Closed,
};
#region Instance Fields
/// <summary>
/// CRC-32 value for uncompressed data
/// </summary>
protected Crc32 crc = new Crc32();
OutputState state_ = OutputState.Header;
#endregion
#region Constructors
/// <summary>
/// Creates a GzipOutputStream with the default buffer size
/// </summary>
/// <param name="baseOutputStream">
/// The stream to read data (to be compressed) from
/// </param>
public GZipOutputStream(Stream baseOutputStream)
: this(baseOutputStream, 4096)
{
}
/// <summary>
/// Creates a GZipOutputStream with the specified buffer size
/// </summary>
/// <param name="baseOutputStream">
/// The stream to read data (to be compressed) from
/// </param>
/// <param name="size">
/// Size of the buffer to use
/// </param>
public GZipOutputStream(Stream baseOutputStream, int size) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true), size)
{
}
#endregion
#region Public API
/// <summary>
/// Sets the active compression level (1-9). The new level will be activated
/// immediately.
/// </summary>
/// <param name="level">The compression level to set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Level specified is not supported.
/// </exception>
/// <see cref="Deflater"/>
public void SetLevel(int level)
{
if (level < Deflater.BEST_SPEED) {
throw new ArgumentOutOfRangeException("level");
}
deflater_.SetLevel(level);
}
/// <summary>
/// Get the current compression level.
/// </summary>
/// <returns>The current compression level.</returns>
public int GetLevel()
{
return deflater_.GetLevel();
}
#endregion
#region Stream overrides
/// <summary>
/// Write given buffer to output updating crc
/// </summary>
/// <param name="buffer">Buffer to write</param>
/// <param name="offset">Offset of first byte in buf to write</param>
/// <param name="count">Number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (state_ == OutputState.Header) {
WriteHeader();
}
if (state_ != OutputState.Footer) {
throw new InvalidOperationException("Write not permitted in current state");
}
crc.Update(buffer, offset, count);
base.Write(buffer, offset, count);
}
/// <summary>
/// Writes remaining compressed output data to the output stream
/// and closes it.
/// </summary>
protected override void Dispose(bool disposing)
{
try {
Finish();
} finally {
if (state_ != OutputState.Closed) {
state_ = OutputState.Closed;
if (IsStreamOwner) {
baseOutputStream_.Dispose();
}
}
}
}
#endregion
#region DeflaterOutputStream overrides
/// <summary>
/// Finish compression and write any footer information required to stream
/// </summary>
public override void Finish()
{
// If no data has been written a header should be added.
if (state_ == OutputState.Header) {
WriteHeader();
}
if (state_ == OutputState.Footer) {
state_ = OutputState.Finished;
base.Finish();
var totalin = (uint)(deflater_.TotalIn & 0xffffffff);
var crcval = (uint)(crc.Value & 0xffffffff);
byte[] gzipFooter;
unchecked {
gzipFooter = new byte[] {
(byte) crcval, (byte) (crcval >> 8),
(byte) (crcval >> 16), (byte) (crcval >> 24),
(byte) totalin, (byte) (totalin >> 8),
(byte) (totalin >> 16), (byte) (totalin >> 24)
};
}
baseOutputStream_.Write(gzipFooter, 0, gzipFooter.Length);
}
}
#endregion
#region Support Routines
void WriteHeader()
{
if (state_ == OutputState.Header) {
state_ = OutputState.Footer;
var mod_time = (int)((DateTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000L); // Ticks give back 100ns intervals
byte[] gzipHeader = {
// The two magic bytes
(byte) (GZipConstants.GZIP_MAGIC >> 8), (byte) (GZipConstants.GZIP_MAGIC & 0xff),
// The compression type
(byte) Deflater.DEFLATED,
// The flags (not set)
0,
// The modification time
(byte) mod_time, (byte) (mod_time >> 8),
(byte) (mod_time >> 16), (byte) (mod_time >> 24),
// The extra flags
0,
// The OS type (unknown)
(byte) 255
};
baseOutputStream_.Write(gzipHeader, 0, gzipHeader.Length);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ServiceModel.Syndication
{
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Xml;
[DataContract]
public abstract class SyndicationItemFormatter
{
private SyndicationItem _item;
protected SyndicationItemFormatter()
{
_item = null;
}
protected SyndicationItemFormatter(SyndicationItem itemToWrite)
{
if (itemToWrite == null)
{
throw new ArgumentNullException(nameof(itemToWrite));
}
_item = itemToWrite;
}
public SyndicationItem Item
{
get
{
return _item;
}
}
public abstract String Version
{ get; }
public abstract bool CanRead(XmlReader reader);
public abstract Task ReadFromAsync(XmlReader reader);
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "{0}, SyndicationVersion={1}", this.GetType(), this.Version);
}
public abstract Task WriteToAsync(XmlWriter writer);
internal protected virtual void SetItem(SyndicationItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
_item = item;
}
internal static SyndicationItem CreateItemInstance(Type itemType)
{
if (itemType.Equals(typeof(SyndicationItem)))
{
return new SyndicationItem();
}
else
{
return (SyndicationItem)Activator.CreateInstance(itemType);
}
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationItem item)
{
SyndicationFeedFormatter.LoadElementExtensions(buffer, writer, item);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationCategory category)
{
SyndicationFeedFormatter.LoadElementExtensions(buffer, writer, category);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationLink link)
{
SyndicationFeedFormatter.LoadElementExtensions(buffer, writer, link);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationPerson person)
{
SyndicationFeedFormatter.LoadElementExtensions(buffer, writer, person);
}
protected static SyndicationCategory CreateCategory(SyndicationItem item)
{
return SyndicationFeedFormatter.CreateCategory(item);
}
protected static SyndicationLink CreateLink(SyndicationItem item)
{
return SyndicationFeedFormatter.CreateLink(item);
}
protected static SyndicationPerson CreatePerson(SyndicationItem item)
{
return SyndicationFeedFormatter.CreatePerson(item);
}
protected static void LoadElementExtensions(XmlReader reader, SyndicationItem item, int maxExtensionSize)
{
SyndicationFeedFormatter.LoadElementExtensions(reader, item, maxExtensionSize);
}
protected static void LoadElementExtensions(XmlReader reader, SyndicationCategory category, int maxExtensionSize)
{
SyndicationFeedFormatter.LoadElementExtensions(reader, category, maxExtensionSize);
}
protected static void LoadElementExtensions(XmlReader reader, SyndicationLink link, int maxExtensionSize)
{
SyndicationFeedFormatter.LoadElementExtensions(reader, link, maxExtensionSize);
}
protected static void LoadElementExtensions(XmlReader reader, SyndicationPerson person, int maxExtensionSize)
{
SyndicationFeedFormatter.LoadElementExtensions(reader, person, maxExtensionSize);
}
protected static bool TryParseAttribute(string name, string ns, string value, SyndicationItem item, string version)
{
return SyndicationFeedFormatter.TryParseAttribute(name, ns, value, item, version);
}
protected static bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category, string version)
{
return SyndicationFeedFormatter.TryParseAttribute(name, ns, value, category, version);
}
protected static bool TryParseAttribute(string name, string ns, string value, SyndicationLink link, string version)
{
return SyndicationFeedFormatter.TryParseAttribute(name, ns, value, link, version);
}
protected static bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person, string version)
{
return SyndicationFeedFormatter.TryParseAttribute(name, ns, value, person, version);
}
protected static bool TryParseContent(XmlReader reader, SyndicationItem item, string contentType, string version, out SyndicationContent content)
{
return SyndicationFeedFormatter.TryParseContent(reader, item, contentType, version, out content);
}
protected static bool TryParseElement(XmlReader reader, SyndicationItem item, string version)
{
return SyndicationFeedFormatter.TryParseElement(reader, item, version);
}
protected static bool TryParseElement(XmlReader reader, SyndicationCategory category, string version)
{
return SyndicationFeedFormatter.TryParseElement(reader, category, version);
}
protected static bool TryParseElement(XmlReader reader, SyndicationLink link, string version)
{
return SyndicationFeedFormatter.TryParseElement(reader, link, version);
}
protected static bool TryParseElement(XmlReader reader, SyndicationPerson person, string version)
{
return SyndicationFeedFormatter.TryParseElement(reader, person, version);
}
protected static async Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationItem item, string version)
{
await SyndicationFeedFormatter.WriteAttributeExtensionsAsync(writer, item, version);
}
protected static async Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationCategory category, string version)
{
await SyndicationFeedFormatter.WriteAttributeExtensionsAsync(writer, category, version);
}
protected static async Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationLink link, string version)
{
await SyndicationFeedFormatter.WriteAttributeExtensions(writer, link, version);
}
protected static async Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationPerson person, string version)
{
await SyndicationFeedFormatter.WriteAttributeExtensionsAsync(writer, person, version);
}
protected static async Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationItem item, string version)
{
await SyndicationFeedFormatter.WriteElementExtensionsAsync(writer, item, version);
}
protected abstract SyndicationItem CreateItemInstance();
protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationCategory category, string version)
{
return SyndicationFeedFormatter.WriteElementExtensionsAsync(writer, category, version);
}
protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationLink link, string version)
{
return SyndicationFeedFormatter.WriteElementExtensionsAsync(writer, link, version);
}
protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationPerson person, string version)
{
return SyndicationFeedFormatter.WriteElementExtensionsAsync(writer, person, version);
}
}
}
| |
// The MIT License
//
// Copyright (c) 2012-2015 Jordan E. Terrell
//
// 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.Text;
using System.Linq;
using NUnit.Framework;
using System.Collections;
namespace iSynaptic.Commons.Collections.Generic
{
[TestFixture]
public class ReadOnlyDictionaryTests
{
[Test]
public void NullInnerDictionary()
{
Assert.Throws<ArgumentNullException>(() => new ReadOnlyDictionary<string, string>(null));
}
[Test]
public void Add()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict = dict.ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => dict.Add("", ""));
}
[Test]
public void ContainsKey()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict = dict.ToReadOnlyDictionary();
Assert.IsTrue(dict.ContainsKey("Key"));
Assert.IsFalse(dict.ContainsKey("OtherKey"));
}
[Test]
public void Keys()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict.Add("OtherKey", "OtherValue");
dict = dict.ToReadOnlyDictionary();
Assert.IsTrue(dict.Keys.SequenceEqual(new string[] { "Key", "OtherKey" }));
}
[Test]
public void Remove()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict = dict.ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => dict.Remove("Key"));
}
[Test]
public void TryGetValue()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict = dict.ToReadOnlyDictionary();
string value = null;
Assert.IsTrue(dict.TryGetValue("Key", out value));
Assert.AreEqual("Value", value);
Assert.IsFalse(dict.TryGetValue("OtherKey", out value));
Assert.IsNull(value);
}
[Test]
public void Values()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict.Add("OtherKey", "OtherValue");
dict = dict.ToReadOnlyDictionary();
Assert.IsTrue(dict.Values.SequenceEqual(new string[] { "Value", "OtherValue" }));
}
[Test]
public void GetViaKeyIndexer()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict.Add("OtherKey", "OtherValue");
dict = dict.ToReadOnlyDictionary();
Assert.AreEqual("Value", dict["Key"]);
Assert.AreEqual("OtherValue", dict["OtherKey"]);
Assert.Throws<KeyNotFoundException>(() => { string val = dict["NonExistentValue"]; });
}
[Test]
public void SetViaKeyIndexer()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict = dict.ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => dict["Key"] = "Value");
}
[Test]
public void AddViaCollectionInterface()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict = dict.ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => dict.Add(KeyValuePair.Create("Key", "Value")));
}
[Test]
public void Clear()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict = dict.ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => dict.Clear());
}
[Test]
public void Contains()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict.Add("OtherKey", "OtherValue");
dict = dict.ToReadOnlyDictionary();
Assert.IsTrue(dict.Contains(KeyValuePair.Create("Key", "Value")));
Assert.IsTrue(dict.Contains(KeyValuePair.Create("OtherKey", "OtherValue")));
Assert.IsFalse(dict.Contains(KeyValuePair.Create("NonExistent", "NonExistentValue")));
}
[Test]
public void CopyTo()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict.Add("OtherKey", "OtherValue");
dict = dict.ToReadOnlyDictionary();
var values = new KeyValuePair<string, string>[3];
var expectedValues = new[]
{
KeyValuePair.Create("Key", "Value"),
KeyValuePair.Create("OtherKey", "OtherValue"),
default(KeyValuePair<string, string>)
};
dict.CopyTo(values, 0);
Assert.IsTrue(values.SequenceEqual(expectedValues));
dict.CopyTo(values, 1);
expectedValues[2] = expectedValues[1];
expectedValues[1] = expectedValues[0];
Assert.IsTrue(values.SequenceEqual(expectedValues));
}
[Test]
public void Count()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict.Add("OtherKey", "OtherValue");
dict = dict.ToReadOnlyDictionary();
Assert.AreEqual(2, dict.Count);
}
[Test]
public void IsReadOnly()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict = dict.ToReadOnlyDictionary();
Assert.IsTrue(dict.IsReadOnly);
}
[Test]
public void RemoveViaCollectionInterface()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict = dict.ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => dict.Remove(KeyValuePair.Create("Key", "Value")));
}
[Test]
public void GenericGetEnumerator()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict.Add("OtherKey", "OtherValue");
dict = dict.ToReadOnlyDictionary();
var values = new[]
{
KeyValuePair.Create("Key", "Value"),
KeyValuePair.Create("OtherKey", "OtherValue")
};
Assert.IsTrue(dict.SequenceEqual(values));
}
[Test]
public void GetEnumerator()
{
IDictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key", "Value");
dict.Add("OtherKey", "OtherValue");
dict = dict.ToReadOnlyDictionary();
var values = new[]
{
KeyValuePair.Create("Key", "Value"),
KeyValuePair.Create("OtherKey", "OtherValue")
};
IEnumerable enumerable = dict;
Assert.IsTrue(enumerable.OfType<KeyValuePair<string, string>>().SequenceEqual(values));
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class BindTests
{
private class PropertyAndFields
{
#pragma warning disable 649 // Assigned through expressions.
public string StringProperty { get; set; }
public string StringField;
public readonly string ReadonlyStringField;
public string ReadonlyStringProperty => "";
public static string StaticStringProperty { get; set; }
public static string StaticStringField;
public static string StaticReadonlyStringProperty => "";
public static readonly string StaticReadonlyStringField = "";
public const string ConstantString = "Constant";
#pragma warning restore 649
}
private class Unreadable<T>
{
public T WriteOnly
{
set { }
}
}
private class GenericType<T>
{
public int AlwaysInt32 { get; set; }
}
[Fact]
public void NullPropertyAccessor()
{
AssertExtensions.Throws<ArgumentNullException>("propertyAccessor", () => Expression.Bind(default(MethodInfo), Expression.Constant(0)));
}
[Fact]
public void NullMember()
{
AssertExtensions.Throws<ArgumentNullException>("member", () => Expression.Bind(default(MemberInfo), Expression.Constant(0)));
}
[Fact]
public void NullExpression()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StringProperty))[0];
PropertyInfo property = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty));
AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.Bind(member, null));
AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.Bind(property, null));
}
[Fact]
public void ReadOnlyMember()
{
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(typeof(string).GetProperty(nameof(string.Length)), Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(typeof(string).GetMember(nameof(string.Length))[0], Expression.Constant(0)));
}
[Fact]
public void WriteOnlyExpression()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StringProperty))[0];
PropertyInfo property = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty));
Expression expression = Expression.Property(Expression.Constant(new Unreadable<string>()), typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Bind(member, expression));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Bind(property, expression));
}
[Fact]
public void MethodForMember()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(object.ToString))[0];
MethodInfo method = typeof(PropertyAndFields).GetMethod(nameof(object.ToString));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(member, Expression.Constant("")));
AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.Bind(method, Expression.Constant("")));
}
[Fact]
public void ExpressionTypeNotAssignable()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StringProperty))[0];
PropertyInfo property = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Bind(member, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Bind(property, Expression.Constant(0)));
}
[Fact]
public void OpenGenericTypesMember()
{
MemberInfo member = typeof(Unreadable<>).GetMember("WriteOnly")[0];
PropertyInfo property = typeof(Unreadable<>).GetProperty("WriteOnly");
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Bind(member, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Bind(property, Expression.Constant(0)));
}
[Fact]
public void OpenGenericTypesNonGenericMember()
{
MemberInfo member = typeof(GenericType<>).GetMember(nameof(GenericType<int>.AlwaysInt32))[0];
PropertyInfo property = typeof(GenericType<>).GetProperty(nameof(GenericType<int>.AlwaysInt32));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Bind(member, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Bind(property, Expression.Constant(0)));
}
[Fact]
public void MustBeMemberOfType()
{
NewExpression newExp = Expression.New(typeof(UriBuilder));
MemberAssignment bind = Expression.Bind(
typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty)),
Expression.Constant("value")
);
AssertExtensions.Throws<ArgumentException>("bindings[0]", () => Expression.MemberInit(newExp, bind));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void MemberAssignmentFromMember(bool useInterpreter)
{
PropertyAndFields result = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(
typeof(PropertyAndFields).GetMember("StringProperty")[0],
Expression.Constant("Hello Property")
),
Expression.Bind(
typeof(PropertyAndFields).GetMember("StringField")[0],
Expression.Constant("Hello Field")
)
)
).Compile(useInterpreter)();
Assert.Equal("Hello Property", result.StringProperty);
Assert.Equal("Hello Field", result.StringField);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void MemberAssignmentFromMethodInfo(bool useInterpreter)
{
PropertyAndFields result = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(
typeof(PropertyAndFields).GetProperty("StringProperty"),
Expression.Constant("Hello Property")
)
)
).Compile(useInterpreter)();
Assert.Equal("Hello Property", result.StringProperty);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ConstantField(bool useInterpreter)
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.ConstantString))[0];
Expression<Func<PropertyAndFields>> attemptAssignToConstant = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(member, Expression.Constant(""))
)
);
Assert.Throws<NotSupportedException>(() => attemptAssignToConstant.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ReadonlyField(bool useInterpreter)
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.ReadonlyStringField))[0];
Expression<Func<PropertyAndFields>> assignToReadonly = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(member, Expression.Constant("ABC"))
)
);
Func<PropertyAndFields> func = assignToReadonly.Compile(useInterpreter);
Assert.Equal("ABC", func().ReadonlyStringField);
}
[Fact]
public void ReadonlyProperty()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.ReadonlyStringProperty))[0];
PropertyInfo property = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.ReadonlyStringProperty));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(member, Expression.Constant("")));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(property, Expression.Constant("")));
}
[Fact]
public void StaticReadonlyProperty()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StaticReadonlyStringProperty))[0];
PropertyInfo property = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StaticReadonlyStringProperty));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(member, Expression.Constant("")));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(property, Expression.Constant("")));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void StaticField(bool useInterpreter)
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StaticStringField))[0];
Expression<Func<PropertyAndFields>> assignToReadonly = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(member, Expression.Constant("ABC"))
)
);
Func<PropertyAndFields> func = assignToReadonly.Compile(useInterpreter);
PropertyAndFields.StaticStringField = "123";
func();
Assert.Equal("ABC", PropertyAndFields.StaticStringField);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void StaticReadonlyField(bool useInterpreter)
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StaticReadonlyStringField))[0];
Expression<Func<PropertyAndFields>> assignToReadonly = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(member, Expression.Constant("ABC" + useInterpreter))
)
);
Func<PropertyAndFields> func = assignToReadonly.Compile(useInterpreter);
func();
Assert.Equal("ABC" + useInterpreter, PropertyAndFields.StaticReadonlyStringField);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void StaticProperty(bool useInterpreter)
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StaticStringProperty))[0];
Expression<Func<PropertyAndFields>> assignToStaticProperty = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(member, Expression.Constant("ABC"))
)
);
Assert.Throws<InvalidProgramException>(() => assignToStaticProperty.Compile(useInterpreter));
}
[Fact]
public void UpdateDifferentReturnsDifferent()
{
MemberAssignment bind = Expression.Bind(typeof(PropertyAndFields).GetProperty("StringProperty"), Expression.Constant("Hello Property"));
Assert.NotSame(bind, Expression.Default(typeof(string)));
}
[Fact]
public void UpdateSameReturnsSame()
{
MemberAssignment bind = Expression.Bind(typeof(PropertyAndFields).GetProperty("StringProperty"), Expression.Constant("Hello Property"));
Assert.Same(bind, bind.Update(bind.Expression));
}
[Fact]
public void MemberBindingTypeAssignment()
{
MemberAssignment bind = Expression.Bind(typeof(PropertyAndFields).GetProperty("StringProperty"), Expression.Constant("Hello Property"));
Assert.Equal(MemberBindingType.Assignment, bind.BindingType);
}
private class BogusBinding : MemberBinding
{
public BogusBinding(MemberBindingType type, MemberInfo member)
#pragma warning disable 618
: base(type, member)
#pragma warning restore 618
{
}
public override string ToString() => ""; // Called internal to test framework and default would throw.
}
private static IEnumerable<object[]> BogusBindings()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StaticReadonlyStringField))[0];
foreach (MemberBindingType type in new[] {MemberBindingType.Assignment, MemberBindingType.ListBinding, MemberBindingType.MemberBinding, (MemberBindingType)(-1)})
{
yield return new object[] {new BogusBinding(type, member)};
}
}
[Theory, MemberData(nameof(BogusBindings))]
public void BogusBindingType(MemberBinding binding)
{
AssertExtensions.Throws<ArgumentException>("bindings[0]", () => Expression.MemberInit(Expression.New(typeof(PropertyAndFields)), binding));
}
#if FEATURE_COMPILE
[Fact]
public void GlobalMethod()
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module");
MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new [] {typeof(int)});
globalMethod.GetILGenerator().Emit(OpCodes.Ret);
module.CreateGlobalFunctions();
MethodInfo globalMethodInfo = module.GetMethod(globalMethod.Name);
AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.Bind(globalMethodInfo, Expression.Constant(2)));
}
[Fact]
public void GlobalField()
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module");
FieldBuilder fieldBuilder = module.DefineInitializedData("GlobalField", new byte[4], FieldAttributes.Public);
module.CreateGlobalFunctions();
FieldInfo globalField = module.GetField(fieldBuilder.Name);
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(globalField, Expression.Default(globalField.FieldType)));
}
#endif
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Encog.Util.HTTP;
using Encog.Util.File;
namespace Encog.Bot
{
/// <summary>
/// Utility class for bots.
/// </summary>
public class BotUtil
{
/// <summary>
/// How much data to read at once.
/// </summary>
public static int BufferSize = 8192;
/// <summary>
/// This method is very useful for grabbing information from a HTML page.
/// </summary>
/// <param name="str">The string to search.</param>
/// <param name="token1">The text, or tag, that comes before the desired text</param>
/// <param name="token2">The text, or tag, that comes after the desired text</param>
/// <param name="index">Index in the string to start searching from.</param>
/// <param name="occurence">What occurence.</param>
/// <returns>The contents of the URL that was downloaded.</returns>
public static String ExtractFromIndex(String str, String token1,
String token2, int index, int occurence)
{
// convert everything to lower case
String searchStr = str.ToLower();
String token1Lower = token1.ToLower();
String token2Lower = token2.ToLower();
int count = occurence;
// now search
int location1 = index - 1;
do
{
location1 = searchStr.IndexOf(token1Lower, location1 + 1);
if (location1 == -1)
{
return null;
}
count--;
} while (count > 0);
// return the result from the original string that has mixed
// case
int location2 = searchStr.IndexOf(token2Lower, location1 + 1);
if (location2 == -1)
{
return null;
}
return str.Substring(location1 + token1Lower.Length, location2 - (location1 + token1.Length));
}
/// <summary>
/// This method is very useful for grabbing information from a HTML page.
/// </summary>
/// <param name="str">The string to search.</param>
/// <param name="token1">The text, or tag, that comes before the desired text.</param>
/// <param name="token2">The text, or tag, that comes after the desired text.</param>
/// <param name="index">Which occurrence of token1 to use, 1 for the first.</param>
/// <returns>The contents of the URL that was downloaded.</returns>
public static String Extract(String str, String token1,
String token2, int index)
{
// convert everything to lower case
String searchStr = str.ToLower();
String token1Lower = token1.ToLower();
String token2Lower = token2.ToLower();
int count = index;
// now search
int location1 = -1;
do
{
location1 = searchStr.IndexOf(token1Lower, location1 + 1);
if (location1 == -1)
{
return null;
}
count--;
} while (count > 0);
// return the result from the original string that has mixed
// case
int location2 = searchStr.IndexOf(token2Lower, location1 + 1);
if (location2 == -1)
{
return null;
}
return str.Substring(location1 + token1Lower.Length, location2 - (location1 + token1.Length));
}
/// <summary>
/// Post to a page.
/// </summary>
/// <param name="uri">The URI to post to.</param>
/// <param name="param">The post params.</param>
/// <returns>The HTTP response.</returns>
public static String POSTPage(Uri uri, IDictionary<String, String> param)
{
WebRequest req = WebRequest.Create(uri);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
var postString = new StringBuilder();
foreach (String key in param.Keys)
{
String value = param[key];
if (value != null)
{
if (postString.Length != 0)
postString.Append('&');
postString.Append(key);
postString.Append('=');
postString.Append(FormUtility.Encode(value));
}
}
byte[] bytes = Encoding.ASCII.GetBytes(postString.ToString());
req.ContentLength = bytes.Length;
Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
WebResponse resp = req.GetResponse();
if (resp == null) return null;
var sr = new StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
/// <summary>
/// Post bytes to a page.
/// </summary>
/// <param name="uri">The URI to post to.</param>
/// <param name="bytes">The bytes to post.</param>
/// <param name="length">The length of the posted data.</param>
/// <returns>The HTTP response.</returns>
public static String POSTPage(Uri uri, byte[] bytes, int length)
{
WebRequest webRequest = WebRequest.Create(uri);
//webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.ContentLength = length;
Stream os = null;
try
{
// send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, length); //Send it
}
catch (WebException ex)
{
throw new BotError(ex);
}
finally
{
if (os != null)
{
os.Flush();
}
}
try
{
// get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{
return null;
}
var sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd();
}
catch (WebException ex)
{
throw new BotError(ex);
}
}
/// <summary>
/// Load the specified web page into a string.
/// </summary>
/// <param name="url">The url to load.</param>
/// <returns>The web page as a string.</returns>
public static String LoadPage(Uri url)
{
try
{
var result = new StringBuilder();
var buffer = new byte[BufferSize];
int length;
WebRequest http = WebRequest.Create(url);
var response = (HttpWebResponse) http.GetResponse();
Stream istream = response.GetResponseStream();
do
{
length = istream.Read(buffer, 0, buffer.Length);
if (length > 0)
{
String str = Encoding.UTF8.GetString(buffer, 0, length);
result.Append(str);
}
} while (length > 0);
return result.ToString();
}
catch (IOException e)
{
#if logging
if (LOGGER.IsErrorEnabled)
{
LOGGER.Error("Exception", e);
}
#endif
throw new BotError(e);
}
}
/// <summary>
/// Private constructor.
/// </summary>
private BotUtil()
{
}
/// <summary>
/// Post to a page.
/// </summary>
/// <param name="uri">The URI to post to.</param>
/// <param name="stream">The stream.</param>
/// <returns>The page returned.</returns>
public static string POSTPage(Uri uri, Stream stream)
{
WebRequest req = WebRequest.Create(uri);
//req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
Stream os = req.GetRequestStream();
FileUtil.CopyStream(stream, os);
os.Close();
WebResponse resp = req.GetResponse();
if (resp == null) return null;
var sr = new StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
}
}
| |
/*
* 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 OpenMetaverse;
namespace OpenSim.Framework
{
/// <summary>
/// Information about a particular user known to the userserver
/// </summary>
public class UserProfileData
{
/// <summary>
/// A UNIX Timestamp (seconds since epoch) for the users creation
/// </summary>
private int m_created;
/// <summary>
/// The users last registered agent (filled in on the user server)
/// </summary>
private UserAgentData m_currentAgent;
/// <summary>
/// The first component of a users account name
/// </summary>
private string m_firstname;
/// <summary>
/// The coordinates inside the region of the home location
/// </summary>
private Vector3 m_homeLocation;
/// <summary>
/// Where the user will be looking when they rez.
/// </summary>
private Vector3 m_homeLookAt;
private uint m_homeRegionX;
private uint m_homeRegionY;
/// <summary>
/// The ID value for this user
/// </summary>
private UUID m_id;
/// <summary>
/// A UNIX Timestamp for the users last login date / time
/// </summary>
private int m_lastLogin;
/// <summary>
/// A salted hash containing the users password, in the format md5(md5(password) + ":" + salt)
/// </summary>
/// <remarks>This is double MD5'd because the client sends an unsalted MD5 to the loginserver</remarks>
private string m_passwordHash;
/// <summary>
/// The salt used for the users hash, should be 32 bytes or longer
/// </summary>
private string m_passwordSalt;
/// <summary>
/// The about text listed in a users profile.
/// </summary>
private string m_profileAboutText = String.Empty;
/// <summary>
/// A uint mask containing the "I can do" fields of the users profile
/// </summary>
private uint m_profileCanDoMask;
/// <summary>
/// The profile image for the users first life tab
/// </summary>
private UUID m_profileFirstImage;
/// <summary>
/// The first life about text listed in a users profile
/// </summary>
private string m_profileFirstText = String.Empty;
/// <summary>
/// The profile image for an avatar stored on the asset server
/// </summary>
private UUID m_profileImage;
/// <summary>
/// A uint mask containing the "I want to do" part of the users profile
/// </summary>
private uint m_profileWantDoMask; // Profile window "I want to" mask
/// <summary>
/// The profile url for an avatar
/// </summary>
private string m_profileUrl;
/// <summary>
/// The second component of a users account name
/// </summary>
private string m_surname;
/// <summary>
/// A valid email address for the account. Useful for password reset requests.
/// </summary>
private string m_email = String.Empty;
/// <summary>
/// A URI to the users asset server, used for foreigners and large grids.
/// </summary>
private string m_userAssetUri = String.Empty;
/// <summary>
/// A URI to the users inventory server, used for foreigners and large grids
/// </summary>
private string m_userInventoryUri = String.Empty;
/// <summary>
/// The last used Web_login_key
/// </summary>
private UUID m_webLoginKey;
// Data for estates and other goodies
// to get away from per-machine configs a little
//
private int m_userFlags;
private int m_godLevel;
private string m_customType;
private UUID m_partner;
/// <summary>
/// The regionhandle of the users preferred home region. If
/// multiple sims occupy the same spot, the grid may decide
/// which region the user logs into
/// </summary>
public virtual ulong HomeRegion
{
get
{
return Util.RegionWorldLocToHandle(Util.RegionToWorldLoc(m_homeRegionX), Util.RegionToWorldLoc(m_homeRegionY));
// return Utils.UIntsToLong( m_homeRegionX * (uint)Constants.RegionSize, m_homeRegionY * (uint)Constants.RegionSize);
}
set
{
uint regionWorldLocX, regionWorldLocY;
Util.RegionHandleToWorldLoc(value, out regionWorldLocX, out regionWorldLocY);
m_homeRegionX = Util.WorldToRegionLoc(regionWorldLocX);
m_homeRegionY = Util.WorldToRegionLoc(regionWorldLocY);
// m_homeRegionX = (uint) (value >> 40);
// m_homeRegionY = (((uint) (value)) >> 8);
}
}
private UUID m_homeRegionId;
/// <summary>
/// The regionID of the users home region. This is unique;
/// even if the position of the region changes within the
/// grid, this will refer to the same region.
/// </summary>
public UUID HomeRegionID
{
get { return m_homeRegionId; }
set { m_homeRegionId = value; }
}
// Property wrappers
public UUID ID
{
get { return m_id; }
set { m_id = value; }
}
public UUID WebLoginKey
{
get { return m_webLoginKey; }
set { m_webLoginKey = value; }
}
public string FirstName
{
get { return m_firstname; }
set { m_firstname = value; }
}
public string SurName
{
get { return m_surname; }
set { m_surname = value; }
}
/// <value>
/// The concatentation of the various name components.
/// </value>
public string Name
{
get { return String.Format("{0} {1}", m_firstname, m_surname); }
}
public string Email
{
get { return m_email; }
set { m_email = value; }
}
public string PasswordHash
{
get { return m_passwordHash; }
set { m_passwordHash = value; }
}
public string PasswordSalt
{
get { return m_passwordSalt; }
set { m_passwordSalt = value; }
}
public uint HomeRegionX
{
get { return m_homeRegionX; }
set { m_homeRegionX = value; }
}
public uint HomeRegionY
{
get { return m_homeRegionY; }
set { m_homeRegionY = value; }
}
public Vector3 HomeLocation
{
get { return m_homeLocation; }
set { m_homeLocation = value; }
}
// for handy serialization
public float HomeLocationX
{
get { return m_homeLocation.X; }
set { m_homeLocation.X = value; }
}
public float HomeLocationY
{
get { return m_homeLocation.Y; }
set { m_homeLocation.Y = value; }
}
public float HomeLocationZ
{
get { return m_homeLocation.Z; }
set { m_homeLocation.Z = value; }
}
public Vector3 HomeLookAt
{
get { return m_homeLookAt; }
set { m_homeLookAt = value; }
}
// for handy serialization
public float HomeLookAtX
{
get { return m_homeLookAt.X; }
set { m_homeLookAt.X = value; }
}
public float HomeLookAtY
{
get { return m_homeLookAt.Y; }
set { m_homeLookAt.Y = value; }
}
public float HomeLookAtZ
{
get { return m_homeLookAt.Z; }
set { m_homeLookAt.Z = value; }
}
public int Created
{
get { return m_created; }
set { m_created = value; }
}
public int LastLogin
{
get { return m_lastLogin; }
set { m_lastLogin = value; }
}
public string UserInventoryURI
{
get { return m_userInventoryUri; }
set { m_userInventoryUri = value; }
}
public string UserAssetURI
{
get { return m_userAssetUri; }
set { m_userAssetUri = value; }
}
public uint CanDoMask
{
get { return m_profileCanDoMask; }
set { m_profileCanDoMask = value; }
}
public uint WantDoMask
{
get { return m_profileWantDoMask; }
set { m_profileWantDoMask = value; }
}
public string AboutText
{
get { return m_profileAboutText; }
set { m_profileAboutText = value; }
}
public string FirstLifeAboutText
{
get { return m_profileFirstText; }
set { m_profileFirstText = value; }
}
public string ProfileUrl
{
get { return m_profileUrl; }
set { m_profileUrl = value; }
}
public UUID Image
{
get { return m_profileImage; }
set { m_profileImage = value; }
}
public UUID FirstLifeImage
{
get { return m_profileFirstImage; }
set { m_profileFirstImage = value; }
}
public UserAgentData CurrentAgent
{
get { return m_currentAgent; }
set { m_currentAgent = value; }
}
public int UserFlags
{
get { return m_userFlags; }
set { m_userFlags = value; }
}
public int GodLevel
{
get { return m_godLevel; }
set { m_godLevel = value; }
}
public string CustomType
{
get { return m_customType; }
set { m_customType = value; }
}
public UUID Partner
{
get { return m_partner; }
set { m_partner = value; }
}
}
}
| |
// 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.
//#define POINTS_FILTER_TRACE
using System;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Media;
using System.Collections.Generic;
namespace MS.Internal.Ink
{
#region ErasingStroke
/// <summary>
/// This class represents a contour of an erasing stroke, and provides
/// internal API for static and incremental stroke_contour vs stroke_contour
/// hit-testing.
/// </summary>
internal class ErasingStroke
{
#region Constructors
/// <summary>
/// Constructor for incremental erasing
/// </summary>
/// <param name="erasingShape">The shape of the eraser's tip</param>
internal ErasingStroke(StylusShape erasingShape)
{
System.Diagnostics.Debug.Assert(erasingShape != null);
_nodeIterator = new StrokeNodeIterator(erasingShape);
}
/// <summary>
/// Constructor for static (atomic) erasing
/// </summary>
/// <param name="erasingShape">The shape of the eraser's tip</param>
/// <param name="path">the spine of the erasing stroke</param>
internal ErasingStroke(StylusShape erasingShape, IEnumerable<Point> path)
: this(erasingShape)
{
MoveTo(path);
}
#endregion
#region API
/// <summary>
/// Generates stroke nodes along a given path.
/// Drops any previously genererated nodes.
/// </summary>
/// <param name="path"></param>
internal void MoveTo(IEnumerable<Point> path)
{
System.Diagnostics.Debug.Assert((path != null) && (IEnumerablePointHelper.GetCount(path) != 0));
Point[] points = IEnumerablePointHelper.GetPointArray(path);
if (_erasingStrokeNodes == null)
{
_erasingStrokeNodes = new List<StrokeNode>(points.Length);
_erasingStrokeNodeBounds = new List<Rect>(points.Length);
}
else
{
_erasingStrokeNodes.Clear();
_erasingStrokeNodeBounds.Clear();
}
_bounds = Rect.Empty;
_nodeIterator = _nodeIterator.GetIteratorForNextSegment(points.Length > 1 ? FilterPoints(points) : points);
for (int i = 0; i < _nodeIterator.Count; i++)
{
StrokeNode strokeNode = _nodeIterator[i];
var boundsConnected = strokeNode.GetBoundsConnected();
_bounds.Union(boundsConnected);
_erasingStrokeNodes.Add(strokeNode);
_erasingStrokeNodeBounds.Add(boundsConnected);
}
#if POINTS_FILTER_TRACE
_totalPointsAdded += path.Length;
System.Diagnostics.Debug.WriteLine(String.Format("Total Points added: {0} screened: {1} collinear screened: {2}", _totalPointsAdded, _totalPointsScreened, _collinearPointsScreened));
#endif
}
/// <summary>
/// Returns the bounds of the eraser's last move.
/// </summary>
/// <value></value>
internal Rect Bounds { get { return _bounds; } }
/// <summary>
/// Hit-testing for stroke erase scenario.
/// </summary>
/// <param name="iterator">the stroke nodes to iterate</param>
/// <returns>true if the strokes intersect, false otherwise</returns>
internal bool HitTest(StrokeNodeIterator iterator)
{
System.Diagnostics.Debug.Assert(iterator != null);
if ((_erasingStrokeNodes == null) || (_erasingStrokeNodes.Count == 0))
{
return false;
}
Rect inkSegmentBounds = Rect.Empty;
for (int i = 0; i < iterator.Count; i++)
{
StrokeNode inkStrokeNode = iterator[i];
Rect inkNodeBounds = inkStrokeNode.GetBounds();
inkSegmentBounds.Union(inkNodeBounds);
if (inkSegmentBounds.IntersectsWith(_bounds))
{
for (var index = 0; index < _erasingStrokeNodes.Count; index++)
{
var erasingStrokeNodeBound = _erasingStrokeNodeBounds[index];
if (inkSegmentBounds.IntersectsWith(erasingStrokeNodeBound))
{
StrokeNode erasingStrokeNode = _erasingStrokeNodes[index];
if (erasingStrokeNode.HitTest(inkStrokeNode))
{
return true;
}
}
}
}
}
return false;
}
/// <summary>
/// Hit-testing for point erase.
/// </summary>
/// <param name="iterator"></param>
/// <param name="intersections"></param>
/// <returns></returns>
internal bool EraseTest(StrokeNodeIterator iterator, List<StrokeIntersection> intersections)
{
System.Diagnostics.Debug.Assert(iterator != null);
System.Diagnostics.Debug.Assert(intersections != null);
intersections.Clear();
List<StrokeFIndices> eraseAt = new List<StrokeFIndices>();
if ((_erasingStrokeNodes == null) || (_erasingStrokeNodes.Count == 0))
{
return false;
}
Rect inkSegmentBounds = Rect.Empty;
for (int x = 0; x < iterator.Count; x++)
{
StrokeNode inkStrokeNode = iterator[x];
Rect inkNodeBounds = inkStrokeNode.GetBounds();
inkSegmentBounds.Union(inkNodeBounds);
if (inkSegmentBounds.IntersectsWith(_bounds))
{
int index = eraseAt.Count;
for (var strokeNodeIndex = 0; strokeNodeIndex < _erasingStrokeNodes.Count; strokeNodeIndex++)
{
var erasingStrokeNodeBound = _erasingStrokeNodeBounds[strokeNodeIndex];
if (inkSegmentBounds.IntersectsWith(erasingStrokeNodeBound) == false)
{
continue;
}
StrokeNode erasingStrokeNode = _erasingStrokeNodes[strokeNodeIndex];
StrokeFIndices fragment = inkStrokeNode.CutTest(erasingStrokeNode);
if (fragment.IsEmpty)
{
continue;
}
// Merge it with the other results for this ink segment
bool inserted = false;
for (int i = index; i < eraseAt.Count; i++)
{
StrokeFIndices lastFragment = eraseAt[i];
if (fragment.BeginFIndex < lastFragment.EndFIndex)
{
// If the fragments overlap, merge them
if (fragment.EndFIndex > lastFragment.BeginFIndex)
{
fragment = new StrokeFIndices(
Math.Min(lastFragment.BeginFIndex, fragment.BeginFIndex),
Math.Max(lastFragment.EndFIndex, fragment.EndFIndex));
// If the fragment doesn't go beyond lastFragment, break
if ((fragment.EndFIndex <= lastFragment.EndFIndex) || ((i + 1) == eraseAt.Count))
{
inserted = true;
eraseAt[i] = fragment;
break;
}
else
{
eraseAt.RemoveAt(i);
i--;
}
}
// insert otherwise
else
{
eraseAt.Insert(i, fragment);
inserted = true;
break;
}
}
}
// If not merged nor inserted, add it to the end of the list
if (false == inserted)
{
eraseAt.Add(fragment);
}
// Break out if the entire ink segment is hit - {BeforeFirst, AfterLast}
if (eraseAt[eraseAt.Count - 1].IsFull)
{
break;
}
}
// Merge inter-segment overlapping fragments
if ((index > 0) && (index < eraseAt.Count))
{
StrokeFIndices lastFragment = eraseAt[index - 1];
if (DoubleUtil.AreClose(lastFragment.EndFIndex, StrokeFIndices.AfterLast) )
{
if (DoubleUtil.AreClose(eraseAt[index].BeginFIndex, StrokeFIndices.BeforeFirst))
{
lastFragment.EndFIndex = eraseAt[index].EndFIndex;
eraseAt[index - 1] = lastFragment;
eraseAt.RemoveAt(index);
}
else
{
lastFragment.EndFIndex = inkStrokeNode.Index;
eraseAt[index - 1] = lastFragment;
}
}
}
}
// Start next ink segment
inkSegmentBounds = inkNodeBounds;
}
if (eraseAt.Count != 0)
{
foreach (StrokeFIndices segment in eraseAt)
{
intersections.Add(new StrokeIntersection(segment.BeginFIndex, StrokeFIndices.AfterLast,
StrokeFIndices.BeforeFirst, segment.EndFIndex));
}
}
return (eraseAt.Count != 0);
}
#endregion
#region private API
private Point[] FilterPoints(Point[] path)
{
System.Diagnostics.Debug.Assert(path.Length > 1);
Point back2, back1;
int i;
List<Point> newPath = new List<Point>();
if (_nodeIterator.Count == 0)
{
newPath.Add(path[0]);
newPath.Add(path[1]);
back2 = path[0];
back1 = path[1];
i = 2;
}
else
{
newPath.Add(path[0]);
back2 = _nodeIterator[_nodeIterator.Count - 1].Position;
back1 = path[0];
i = 1;
}
while (i < path.Length)
{
if (DoubleUtil.AreClose(back1, path[i]))
{
// Filter out duplicate points
i++;
continue;
}
Vector begin = back2 - back1;
Vector end = path[i] - back1;
//On a line defined by begin & end, finds the findex of the point nearest to the origin (0,0).
double findex = StrokeNodeOperations.GetProjectionFIndex(begin, end);
if (DoubleUtil.IsBetweenZeroAndOne(findex))
{
Vector v = (begin + (end - begin) * findex);
if (v.LengthSquared < CollinearTolerance)
{
// The point back1 can be considered as on the line from back2 to the toTest StrokeNode.
// Modify the previous point.
newPath[newPath.Count - 1] = path[i];
back1 = path[i];
i++;
#if POINTS_FILTER_TRACE
_collinearPointsScreened ++;
#endif
continue;
}
}
// Add the surviving point into the list.
newPath.Add(path[i]);
back2 = back1;
back1 = path[i];
i++;
}
#if POINTS_FILTER_TRACE
_totalPointsScreened += path.Length - newPath.Count;
#endif
return newPath.ToArray();
}
#endregion
#region Fields
private StrokeNodeIterator _nodeIterator;
private List<StrokeNode> _erasingStrokeNodes = null;
private List<Rect> _erasingStrokeNodeBounds = null;
private Rect _bounds = Rect.Empty;
#if POINTS_FILTER_TRACE
private int _totalPointsAdded = 0;
private int _totalPointsScreened = 0;
private int _collinearPointsScreened = 0;
#endif
// The collinear tolerance used in points filtering algorithm. The valie
// should be further tuned considering trade-off of performance and accuracy.
// In general, the larger the value, more points are filtered but less accurate.
// For a value of 0.5, typically 70% - 80% percent of the points are filtered out.
private static readonly double CollinearTolerance = 0.1f;
#endregion
}
#endregion
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.ProjectManagement;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType
{
internal class GenerateTypeDialogViewModel : AbstractNotifyPropertyChanged
{
private Document _document;
private INotificationService _notificationService;
private IProjectManagementService _projectManagementService;
private ISyntaxFactsService _syntaxFactsService;
private IGeneratedCodeRecognitionService _generatedCodeService;
private GenerateTypeDialogOptions _generateTypeDialogOptions;
private string _typeName;
private bool _isNewFile;
private Dictionary<string, Accessibility> _accessListMap;
private Dictionary<string, TypeKind> _typeKindMap;
private List<string> _csharpAccessList;
private List<string> _visualBasicAccessList;
private List<string> _csharpTypeKindList;
private List<string> _visualBasicTypeKindList;
private string _csharpExtension = ".cs";
private string _visualBasicExtension = ".vb";
// reserved names that cannot be a folder name or filename
private string[] _reservedKeywords = new string[]
{
"con", "prn", "aux", "nul",
"com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9",
"lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "clock$"
};
// Below code details with the Access List and the manipulation
public List<string> AccessList { get; private set; }
private int _accessSelectIndex;
public int AccessSelectIndex
{
get
{
return _accessSelectIndex;
}
set
{
SetProperty(ref _accessSelectIndex, value);
}
}
private string _selectedAccessibilityString;
public string SelectedAccessibilityString
{
get
{
return _selectedAccessibilityString;
}
set
{
SetProperty(ref _selectedAccessibilityString, value);
}
}
public Accessibility SelectedAccessibility
{
get
{
Contract.Assert(_accessListMap.ContainsKey(SelectedAccessibilityString), "The Accessibility Key String not present");
return _accessListMap[SelectedAccessibilityString];
}
}
private List<string> _kindList;
public List<string> KindList
{
get
{
return _kindList;
}
set
{
SetProperty(ref _kindList, value);
}
}
private int _kindSelectIndex;
public int KindSelectIndex
{
get
{
return _kindSelectIndex;
}
set
{
SetProperty(ref _kindSelectIndex, value);
}
}
private string _selectedTypeKindString;
public string SelectedTypeKindString
{
get
{
return _selectedTypeKindString;
}
set
{
SetProperty(ref _selectedTypeKindString, value);
}
}
public TypeKind SelectedTypeKind
{
get
{
Contract.Assert(_typeKindMap.ContainsKey(SelectedTypeKindString), "The TypeKind Key String not present");
return _typeKindMap[SelectedTypeKindString];
}
}
private void PopulateTypeKind(TypeKind typeKind, string csharpkKey, string visualBasicKey)
{
_typeKindMap.Add(visualBasicKey, typeKind);
_typeKindMap.Add(csharpkKey, typeKind);
_csharpTypeKindList.Add(csharpkKey);
_visualBasicTypeKindList.Add(visualBasicKey);
}
private void PopulateTypeKind(TypeKind typeKind, string visualBasicKey)
{
_typeKindMap.Add(visualBasicKey, typeKind);
_visualBasicTypeKindList.Add(visualBasicKey);
}
private void PopulateAccessList(string key, Accessibility accessibility, string languageName = null)
{
if (languageName == null)
{
_csharpAccessList.Add(key);
_visualBasicAccessList.Add(key);
}
else if (languageName == LanguageNames.CSharp)
{
_csharpAccessList.Add(key);
}
else
{
Contract.Assert(languageName == LanguageNames.VisualBasic, "Currently only C# and VB are supported");
_visualBasicAccessList.Add(key);
}
_accessListMap.Add(key, accessibility);
}
private void InitialSetup(string languageName)
{
_accessListMap = new Dictionary<string, Accessibility>();
_typeKindMap = new Dictionary<string, TypeKind>();
_csharpAccessList = new List<string>();
_visualBasicAccessList = new List<string>();
_csharpTypeKindList = new List<string>();
_visualBasicTypeKindList = new List<string>();
// Populate the AccessListMap
if (!_generateTypeDialogOptions.IsPublicOnlyAccessibility)
{
PopulateAccessList("Default", Accessibility.NotApplicable);
PopulateAccessList("internal", Accessibility.Internal, LanguageNames.CSharp);
PopulateAccessList("Friend", Accessibility.Internal, LanguageNames.VisualBasic);
}
PopulateAccessList("public", Accessibility.Public, LanguageNames.CSharp);
PopulateAccessList("Public", Accessibility.Public, LanguageNames.VisualBasic);
// Populate the TypeKind
PopulateTypeKind();
}
private void PopulateTypeKind()
{
Contract.Assert(_generateTypeDialogOptions.TypeKindOptions != TypeKindOptions.None);
if (TypeKindOptionsHelper.IsClass(_generateTypeDialogOptions.TypeKindOptions))
{
PopulateTypeKind(TypeKind.Class, "class", "Class");
}
if (TypeKindOptionsHelper.IsEnum(_generateTypeDialogOptions.TypeKindOptions))
{
PopulateTypeKind(TypeKind.Enum, "enum", "Enum");
}
if (TypeKindOptionsHelper.IsStructure(_generateTypeDialogOptions.TypeKindOptions))
{
PopulateTypeKind(TypeKind.Structure, "struct", "Structure");
}
if (TypeKindOptionsHelper.IsInterface(_generateTypeDialogOptions.TypeKindOptions))
{
PopulateTypeKind(TypeKind.Interface, "interface", "Interface");
}
if (TypeKindOptionsHelper.IsDelegate(_generateTypeDialogOptions.TypeKindOptions))
{
PopulateTypeKind(TypeKind.Delegate, "delegate", "Delegate");
}
if (TypeKindOptionsHelper.IsModule(_generateTypeDialogOptions.TypeKindOptions))
{
_shouldChangeTypeKindListSelectedIndex = true;
PopulateTypeKind(TypeKind.Module, "Module");
}
}
internal bool TrySubmit()
{
if (this.IsNewFile)
{
var trimmedFileName = FileName.Trim();
// Case : \\Something
if (trimmedFileName.StartsWith("\\\\"))
{
SendFailureNotification(ServicesVSResources.IllegalCharactersInPath);
return false;
}
// Case : something\
if (string.IsNullOrWhiteSpace(trimmedFileName) || trimmedFileName.EndsWith("\\"))
{
SendFailureNotification(ServicesVSResources.PathCannotHaveEmptyFileName);
return false;
}
if (trimmedFileName.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
{
SendFailureNotification(ServicesVSResources.IllegalCharactersInPath);
return false;
}
var isRootOfTheProject = trimmedFileName.StartsWith("\\");
string implicitFilePath = null;
// Construct the implicit file path
if (isRootOfTheProject || this.SelectedProject != _document.Project)
{
if (!TryGetImplicitFilePath(this.SelectedProject.FilePath ?? string.Empty, ServicesVSResources.IllegalPathForProject, out implicitFilePath))
{
return false;
}
}
else
{
if (!TryGetImplicitFilePath(_document.FilePath, ServicesVSResources.IllegalPathForDocument, out implicitFilePath))
{
return false;
}
}
// Remove the '\' at the beginning if present
trimmedFileName = trimmedFileName.StartsWith("\\") ? trimmedFileName.Substring(1) : trimmedFileName;
// Construct the full path of the file to be created
this.FullFilePath = implicitFilePath + '\\' + trimmedFileName;
try
{
this.FullFilePath = Path.GetFullPath(this.FullFilePath);
}
catch (ArgumentNullException e)
{
SendFailureNotification(e.Message);
return false;
}
catch (ArgumentException e)
{
SendFailureNotification(e.Message);
return false;
}
catch (SecurityException e)
{
SendFailureNotification(e.Message);
return false;
}
catch (NotSupportedException e)
{
SendFailureNotification(e.Message);
return false;
}
catch (PathTooLongException e)
{
SendFailureNotification(e.Message);
return false;
}
// Path.GetFullPath does not remove the spaces infront of the filename or folder name . So remove it
var lastIndexOfSeparatorInFullPath = this.FullFilePath.LastIndexOf('\\');
if (lastIndexOfSeparatorInFullPath != -1)
{
var fileNameInFullPathInContainers = this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
this.FullFilePath = string.Join("\\", fileNameInFullPathInContainers.Select(str => str.TrimStart()));
}
string projectRootPath = null;
if (this.SelectedProject.FilePath == null)
{
projectRootPath = string.Empty;
}
else if (!TryGetImplicitFilePath(this.SelectedProject.FilePath, ServicesVSResources.IllegalPathForProject, out projectRootPath))
{
return false;
}
if (this.FullFilePath.StartsWith(projectRootPath))
{
// The new file will be within the root of the project
var folderPath = this.FullFilePath.Substring(projectRootPath.Length);
var containers = folderPath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
// Folder name was mentioned
if (containers.Count() > 1)
{
_fileName = containers.Last();
Folders = new List<string>(containers);
Folders.RemoveAt(Folders.Count - 1);
if (Folders.Any(folder => !(_syntaxFactsService.IsValidIdentifier(folder) || _syntaxFactsService.IsVerbatimIdentifier(folder))))
{
_areFoldersValidIdentifiers = false;
}
}
else if (containers.Count() == 1)
{
// File goes at the root of the Directory
_fileName = containers[0];
Folders = null;
}
else
{
SendFailureNotification(ServicesVSResources.IllegalCharactersInPath);
return false;
}
}
else
{
// The new file will be outside the root of the project and folders will be null
Folders = null;
var lastIndexOfSeparator = this.FullFilePath.LastIndexOf('\\');
if (lastIndexOfSeparator == -1)
{
SendFailureNotification(ServicesVSResources.IllegalCharactersInPath);
return false;
}
_fileName = this.FullFilePath.Substring(lastIndexOfSeparator + 1);
}
// Check for reserved words in the folder or filename
if (this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).Any(s => _reservedKeywords.Contains(s, StringComparer.OrdinalIgnoreCase)))
{
SendFailureNotification(ServicesVSResources.FilePathCannotUseReservedKeywords);
return false;
}
// We check to see if file path of the new file matches the filepath of any other existing file or if the Folders and FileName matches any of the document then
// we say that the file already exists.
if (this.SelectedProject.Documents.Where(n => n != null).Where(n => n.FilePath == FullFilePath).Any() ||
(this.Folders != null && this.FileName != null &&
this.SelectedProject.Documents.Where(n => n.Name != null && n.Folders.Count > 0 && n.Name == this.FileName && this.Folders.SequenceEqual(n.Folders)).Any()) ||
File.Exists(FullFilePath))
{
SendFailureNotification(ServicesVSResources.FileAlreadyExists);
return false;
}
}
return true;
}
private bool TryGetImplicitFilePath(string implicitPathContainer, string message, out string implicitPath)
{
var indexOfLastSeparator = implicitPathContainer.LastIndexOf('\\');
if (indexOfLastSeparator == -1)
{
SendFailureNotification(message);
implicitPath = null;
return false;
}
implicitPath = implicitPathContainer.Substring(0, indexOfLastSeparator);
return true;
}
private void SendFailureNotification(string message)
{
_notificationService.SendNotification(message, severity: NotificationSeverity.Information);
}
private Project _selectedProject;
public Project SelectedProject
{
get
{
return _selectedProject;
}
set
{
var previousProject = _selectedProject;
if (SetProperty(ref _selectedProject, value))
{
NotifyPropertyChanged("DocumentList");
this.DocumentSelectIndex = 0;
this.ProjectSelectIndex = this.ProjectList.FindIndex(p => p.Project == _selectedProject);
if (_selectedProject != _document.Project)
{
// Restrict the Access List Options
// 3 in the list represent the Public. 1-based array.
this.AccessSelectIndex = this.AccessList.IndexOf("public") == -1 ?
this.AccessList.IndexOf("Public") : this.AccessList.IndexOf("public");
Contract.Assert(this.AccessSelectIndex != -1);
this.IsAccessListEnabled = false;
}
else
{
// Remove restriction
this.IsAccessListEnabled = true;
}
if (previousProject != null && _projectManagementService != null)
{
this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace);
}
// Update the TypeKindList if required
if (previousProject != null && previousProject.Language != _selectedProject.Language)
{
if (_selectedProject.Language == LanguageNames.CSharp)
{
var previousSelectedIndex = _kindSelectIndex;
this.KindList = _csharpTypeKindList;
if (_shouldChangeTypeKindListSelectedIndex)
{
this.KindSelectIndex = 0;
}
else
{
this.KindSelectIndex = previousSelectedIndex;
}
}
else
{
var previousSelectedIndex = _kindSelectIndex;
this.KindList = _visualBasicTypeKindList;
if (_shouldChangeTypeKindListSelectedIndex)
{
this.KindSelectIndex = 0;
}
else
{
this.KindSelectIndex = previousSelectedIndex;
}
}
}
// Update File Extension
UpdateFileNameExtension();
}
}
}
private int _projectSelectIndex;
public int ProjectSelectIndex
{
get
{
return _projectSelectIndex;
}
set
{
SetProperty(ref _projectSelectIndex, value);
}
}
public List<ProjectSelectItem> ProjectList { get; private set; }
private Project _previouslyPopulatedProject = null;
private List<DocumentSelectItem> _previouslyPopulatedDocumentList = null;
public IEnumerable<DocumentSelectItem> DocumentList
{
get
{
if (_previouslyPopulatedProject == _selectedProject)
{
return _previouslyPopulatedDocumentList;
}
_previouslyPopulatedProject = _selectedProject;
_previouslyPopulatedDocumentList = new List<DocumentSelectItem>();
// Check for the current project
if (_selectedProject == _document.Project)
{
// populate the current document
_previouslyPopulatedDocumentList.Add(new DocumentSelectItem(_document, "<Current File>"));
// Set the initial selected Document
this.SelectedDocument = _document;
// Populate the rest of the documents for the project
_previouslyPopulatedDocumentList.AddRange(_document.Project.Documents
.Where(d => d != _document && !_generatedCodeService.IsGeneratedCode(d))
.Select(d => new DocumentSelectItem(d)));
}
else
{
_previouslyPopulatedDocumentList.AddRange(_selectedProject.Documents
.Where(d => !_generatedCodeService.IsGeneratedCode(d))
.Select(d => new DocumentSelectItem(d)));
this.SelectedDocument = _selectedProject.Documents.FirstOrDefault();
}
this.IsExistingFileEnabled = _previouslyPopulatedDocumentList.Count == 0 ? false : true;
this.IsNewFile = this.IsExistingFileEnabled ? this.IsNewFile : true;
return _previouslyPopulatedDocumentList;
}
}
private bool _isExistingFileEnabled = true;
public bool IsExistingFileEnabled
{
get
{
return _isExistingFileEnabled;
}
set
{
SetProperty(ref _isExistingFileEnabled, value);
}
}
private int _documentSelectIndex;
public int DocumentSelectIndex
{
get
{
return _documentSelectIndex;
}
set
{
SetProperty(ref _documentSelectIndex, value);
}
}
private Document _selectedDocument;
public Document SelectedDocument
{
get
{
return _selectedDocument;
}
set
{
SetProperty(ref _selectedDocument, value);
}
}
private string _fileName;
public string FileName
{
get
{
return _fileName;
}
set
{
SetProperty(ref _fileName, value);
}
}
public List<string> Folders;
public string TypeName
{
get
{
return _typeName;
}
set
{
SetProperty(ref _typeName, value);
}
}
public bool IsNewFile
{
get
{
return _isNewFile;
}
set
{
SetProperty(ref _isNewFile, value);
}
}
public bool IsExistingFile
{
get
{
return !_isNewFile;
}
set
{
SetProperty(ref _isNewFile, !value);
}
}
private bool _isAccessListEnabled;
private bool _shouldChangeTypeKindListSelectedIndex = false;
public bool IsAccessListEnabled
{
get
{
return _isAccessListEnabled;
}
set
{
SetProperty(ref _isAccessListEnabled, value);
}
}
private bool _areFoldersValidIdentifiers = true;
public bool AreFoldersValidIdentifiers
{
get
{
if (_areFoldersValidIdentifiers)
{
var workspace = this.SelectedProject.Solution.Workspace as VisualStudioWorkspaceImpl;
var project = workspace?.GetHostProject(this.SelectedProject.Id) as AbstractProject;
return !(project?.IsWebSite == true);
}
return false;
}
}
public IList<string> ProjectFolders { get; private set; }
public string FullFilePath { get; private set; }
internal void UpdateFileNameExtension()
{
var currentFileName = this.FileName.Trim();
if (!string.IsNullOrWhiteSpace(currentFileName) && !currentFileName.EndsWith("\\"))
{
if (this.SelectedProject.Language == LanguageNames.CSharp)
{
// For CSharp
currentFileName = UpdateExtension(currentFileName, _csharpExtension, _visualBasicExtension);
}
else
{
// For Visual Basic
currentFileName = UpdateExtension(currentFileName, _visualBasicExtension, _csharpExtension);
}
}
this.FileName = currentFileName;
}
private string UpdateExtension(string currentFileName, string desiredFileExtension, string undesiredFileExtension)
{
if (currentFileName.EndsWith(desiredFileExtension, StringComparison.OrdinalIgnoreCase))
{
// No change required
return currentFileName;
}
// Remove the undesired extension
if (currentFileName.EndsWith(undesiredFileExtension, StringComparison.OrdinalIgnoreCase))
{
currentFileName = currentFileName.Substring(0, currentFileName.Length - undesiredFileExtension.Length);
}
// Append the desired extension
return currentFileName + desiredFileExtension;
}
internal GenerateTypeDialogViewModel(
Document document,
INotificationService notificationService,
IProjectManagementService projectManagementService,
ISyntaxFactsService syntaxFactsService,
IGeneratedCodeRecognitionService generatedCodeService,
GenerateTypeDialogOptions generateTypeDialogOptions,
string typeName,
string fileExtension,
bool isNewFile,
string accessSelectString,
string typeKindSelectString)
{
_generateTypeDialogOptions = generateTypeDialogOptions;
InitialSetup(document.Project.Language);
var dependencyGraph = document.Project.Solution.GetProjectDependencyGraph();
// Initialize the dependencies
var projectListing = new List<ProjectSelectItem>();
// Populate the project list
// Add the current project
projectListing.Add(new ProjectSelectItem(document.Project));
// Add the rest of the projects
// Adding dependency graph to avoid cyclic dependency
projectListing.AddRange(document.Project.Solution.Projects
.Where(p => p != document.Project && !dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(p.Id).Contains(document.Project.Id))
.Select(p => new ProjectSelectItem(p)));
this.ProjectList = projectListing;
_typeName = generateTypeDialogOptions.IsAttribute && !typeName.EndsWith("Attribute") ? typeName + "Attribute" : typeName;
this.FileName = typeName + fileExtension;
_document = document;
this.SelectedProject = document.Project;
this.SelectedDocument = document;
_notificationService = notificationService;
_generatedCodeService = generatedCodeService;
this.AccessList = document.Project.Language == LanguageNames.CSharp ?
_csharpAccessList :
_visualBasicAccessList;
this.AccessSelectIndex = this.AccessList.Contains(accessSelectString) ?
this.AccessList.IndexOf(accessSelectString) : 0;
this.IsAccessListEnabled = true;
this.KindList = document.Project.Language == LanguageNames.CSharp ?
_csharpTypeKindList :
_visualBasicTypeKindList;
this.KindSelectIndex = this.KindList.Contains(typeKindSelectString) ?
this.KindList.IndexOf(typeKindSelectString) : 0;
this.ProjectSelectIndex = 0;
this.DocumentSelectIndex = 0;
_isNewFile = isNewFile;
_syntaxFactsService = syntaxFactsService;
_projectManagementService = projectManagementService;
if (projectManagementService != null)
{
this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace);
}
else
{
this.ProjectFolders = SpecializedCollections.EmptyList<string>();
}
}
public class ProjectSelectItem
{
private Project _project;
public string Name
{
get
{
return _project.Name;
}
}
public Project Project
{
get
{
return _project;
}
}
public ProjectSelectItem(Project project)
{
_project = project;
}
}
public class DocumentSelectItem
{
private Document _document;
public Document Document
{
get
{
return _document;
}
}
private string _name;
public string Name
{
get
{
return _name;
}
}
public DocumentSelectItem(Document document, string documentName)
{
_document = document;
_name = documentName;
}
public DocumentSelectItem(Document document)
{
_document = document;
if (document.Folders.Count == 0)
{
_name = document.Name;
}
else
{
_name = string.Join("\\", document.Folders) + "\\" + document.Name;
}
}
}
}
}
| |
//
// Font.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin 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 Xwt.Backends;
using System.Windows.Markup;
using System.ComponentModel;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace Xwt.Drawing
{
[TypeConverter (typeof(FontValueConverter))]
[ValueSerializer (typeof(FontValueSerializer))]
public sealed class Font: XwtObject
{
FontBackendHandler handler;
public Font (object backend): this (backend, null)
{
}
internal Font (object backend, Toolkit toolkit)
{
if (toolkit != null)
ToolkitEngine = toolkit;
handler = ToolkitEngine.FontBackendHandler;
if (backend == null)
throw new ArgumentNullException ("backend");
Backend = backend;
}
/// <summary>
/// Creates a new font description from a string representation in the form "[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]"
/// </summary>
/// <returns>
/// The new font
/// </returns>
/// <param name='name'>
/// Font description
/// </param>
/// <remarks>
/// Creates a new font description from a string representation in the form "[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]",
/// where FAMILY-LIST is a comma separated list of families optionally terminated by a comma, STYLE_OPTIONS is a
/// whitespace separated list of words where each WORD describes one of style, weight or stretch, and SIZE is a
/// decimal number (size in points). Any one of the options may be absent. If FAMILY-LIST is absent, the default
/// font family will be used. If STYLE-OPTIONS is missing, then all style options will be set to the default values.
/// If SIZE is missing, the size in the resulting font description will be set to the default font size.
/// If the font doesn't exist, it returns the system font.
/// </remarks>
public static Font FromName (string name)
{
var toolkit = Toolkit.CurrentEngine;
var handler = toolkit.FontBackendHandler;
double size = -1;
FontStyle style = FontStyle.Normal;
FontWeight weight = FontWeight.Normal;
FontStretch stretch = FontStretch.Normal;
int i = name.LastIndexOf (' ');
int lasti = name.Length;
do {
string token = name.Substring (i + 1, lasti - i - 1);
FontStyle st;
FontWeight fw;
FontStretch fs;
double siz;
if (double.TryParse (token, NumberStyles.Any, CultureInfo.InvariantCulture, out siz)) // Try parsing the number first, since Enum.TryParse can also parse numbers
size = siz;
else if (Enum.TryParse<FontStyle> (token, true, out st) && st != FontStyle.Normal)
style = st;
else if (Enum.TryParse<FontWeight> (token, true, out fw) && fw != FontWeight.Normal)
weight = fw;
else if (Enum.TryParse<FontStretch> (token, true, out fs) && fs != FontStretch.Normal)
stretch = fs;
else if (token.Length > 0)
break;
lasti = i;
if (i <= 0)
break;
i = name.LastIndexOf (' ', i - 1);
} while (true);
string fname = lasti > 0 ? name.Substring (0, lasti) : string.Empty;
fname = fname.Length > 0 ? GetSupportedFont (fname) : Font.SystemFont.Family;
if (size == -1)
size = SystemFont.Size;
var fb = handler.Create (fname, size, style, weight, stretch);
if (fb != null)
return new Font (fb, toolkit);
else
return Font.SystemFont;
}
static string GetSupportedFont (string fontNames)
{
LoadInstalledFonts ();
int i = fontNames.IndexOf (',');
if (i == -1) {
var f = fontNames.Trim ();
string nf;
if (installedFonts.TryGetValue (f, out nf))
return nf;
else
return GetDefaultFont (f);
}
string[] names = fontNames.Split (new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
if (names.Length == 0)
throw new ArgumentException ("Font family name not provided");
foreach (var name in names) {
var n = name.Trim ();
if (installedFonts.ContainsKey (n))
return n;
}
return GetDefaultFont (fontNames.Trim (' ',','));
}
static string GetDefaultFont (string unknownFont)
{
Console.WriteLine ("Font '" + unknownFont + "' not available in the system. Using '" + Font.SystemFont.Family + "' instead");
return Font.SystemFont.Family;
}
static Dictionary<string,string> installedFonts;
static ReadOnlyCollection<string> installedFontsArray;
static void LoadInstalledFonts ()
{
if (installedFonts == null) {
installedFonts = new Dictionary<string,string> (StringComparer.OrdinalIgnoreCase);
foreach (var f in Toolkit.CurrentEngine.FontBackendHandler.GetInstalledFonts ())
installedFonts [f] = f;
installedFontsArray = new ReadOnlyCollection<string> (installedFonts.Values.ToArray ());
}
}
public static ReadOnlyCollection<string> AvailableFontFamilies {
get {
LoadInstalledFonts ();
return installedFontsArray;
}
}
public static Font SystemFont {
get { return Toolkit.CurrentEngine.FontBackendHandler.SystemFont; }
}
public static Font SystemMonospaceFont {
get {
return Toolkit.CurrentEngine.FontBackendHandler.SystemMonospaceFont;
}
}
public static Font SystemSerifFont {
get {
return Toolkit.CurrentEngine.FontBackendHandler.SystemSerifFont;
}
}
public static Font SystemSansSerifFont {
get {
return Toolkit.CurrentEngine.FontBackendHandler.SystemSansSerifFont;
}
}
/// <summary>
/// Returns a copy of the font using the provided font family
/// </summary>
/// <returns>The new font</returns>
/// <param name="fontFamily">A comma separated list of families</param>
public Font WithFamily (string fontFamily)
{
fontFamily = GetSupportedFont (fontFamily);
return new Font (ToolkitEngine.FontBackendHandler.SetFamily (Backend, fontFamily), ToolkitEngine);
}
public string Family {
get {
return handler.GetFamily (Backend);
}
}
/// <summary>
/// Font size. It can be points or pixels, depending on the value of the SizeUnit property
/// </summary>
public double Size {
get {
return handler.GetSize (Backend);
}
}
public Font WithSize (double size)
{
return new Font (handler.SetSize (Backend, size));
}
public Font WithScaledSize (double scale)
{
return new Font (handler.SetSize (Backend, Size * scale), ToolkitEngine);
}
public FontStyle Style {
get {
return handler.GetStyle (Backend);
}
}
public Font WithStyle (FontStyle style)
{
return new Font (handler.SetStyle (Backend, style), ToolkitEngine);
}
public FontWeight Weight {
get {
return handler.GetWeight (Backend);
}
}
public Font WithWeight (FontWeight weight)
{
return new Font (handler.SetWeight (Backend, weight), ToolkitEngine);
}
public FontStretch Stretch {
get {
return handler.GetStretch (Backend);
}
}
public Font WithStretch (FontStretch stretch)
{
return new Font (handler.SetStretch (Backend, stretch), ToolkitEngine);
}
public override string ToString ()
{
StringBuilder sb = new StringBuilder (Family);
if (Style != FontStyle.Normal)
sb.Append (' ').Append (Style);
if (Weight != FontWeight.Normal)
sb.Append (' ').Append (Weight);
if (Stretch != FontStretch.Normal)
sb.Append (' ').Append (Stretch);
sb.Append (' ').Append (Size.ToString (CultureInfo.InvariantCulture));
return sb.ToString ();
}
public override bool Equals (object obj)
{
var other = obj as Font;
if (other == null)
return false;
return Family == other.Family && Style == other.Style && Weight == other.Weight && Stretch == other.Stretch && Size == other.Size;
}
public override int GetHashCode ()
{
return ToString().GetHashCode ();
}
}
public enum FontStyle
{
Normal,
Oblique,
Italic
}
public enum FontWeight
{
/// The ultralight weight (200)
Ultralight = 200,
/// The light weight (300)
Light = 300,
/// The default weight (400)
Normal = 400,
/// The semi bold weight (600)
Semibold = 600,
/// The bold weight (700)
Bold = 700,
/// The ultrabold weight (800)
Ultrabold = 800,
/// The heavy weight (900)
Heavy = 900
}
public enum FontStretch
{
/// <summary>
/// 4x more condensed than Pango.Stretch.Normal
/// </summary>
UltraCondensed,
/// <summary>
/// 3x more condensed than Pango.Stretch.Normal
/// </summary>
ExtraCondensed,
/// <summary>
/// 2x more condensed than Pango.Stretch.Normal
/// </summary>
Condensed,
/// <summary>
/// 1x more condensed than Pango.Stretch.Normal
/// </summary>
SemiCondensed,
/// <summary>
/// The normal width
/// </summary>
Normal,
/// <summary>
/// 1x more expanded than Pango.Stretch.Normal
/// </summary>
SemiExpanded,
/// <summary>
/// 2x more expanded than Pango.Stretch.Normal
/// </summary>
Expanded,
/// <summary>
/// 3x more expanded than Pango.Stretch.Normal
/// </summary>
ExtraExpanded,
/// <summary>
/// 4x more expanded than Pango.Stretch.Normal
/// </summary>
UltraExpanded
}
class FontValueConverter: TypeConverter
{
public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
}
class FontValueSerializer: ValueSerializer
{
public override bool CanConvertFromString (string value, IValueSerializerContext context)
{
return true;
}
public override bool CanConvertToString (object value, IValueSerializerContext context)
{
return true;
}
public override string ConvertToString (object value, IValueSerializerContext context)
{
return value.ToString ();
}
public override object ConvertFromString (string value, IValueSerializerContext context)
{
return Font.FromName (value);
}
}
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using RTSMiner.Managers;
using RTSMiner.Other;
using System;
using System.Collections.Generic;
using VoidEngine.VGame;
using VoidEngine.VGUI;
namespace RTSMiner
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
public enum GameLevels
{
SPLASH,
MENU,
OPTIONS,
GAME
}
#region Variables
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
#region Options stuff
/// <summary>
/// The current window Size
/// </summary>
public Point WindowSize = new Point(1200, 720);//new Point(800, 480);
/// <summary>
/// Gets or sets if vsync is active;
/// </summary>
public bool isVSync
{
get;
set;
}
/// <summary>
/// Gets or sets if the options are confirmed.
/// </summary>
public bool OptionsComfirmed
{
get;
set;
}
/// <summary>
/// Gets or sets if the options have been changed.
/// </summary>
public int isOptionsChanged
{
get;
protected set;
}
/// <summary>
/// Gets or sets if the options have been changed.
/// </summary>
public int OldIsOptionsChanged
{
get;
protected set;
}
#endregion
#region Other stuff
/// <summary>
/// The random generator for stuff.
/// </summary>
public Random random = new Random();
/// <summary>
/// The current and previous keyboard states.
/// </summary>
public KeyboardState keyboardState, previousKeyboardState;
#endregion
#region Managers
public GameManager gameManager;
MainMenuManager mainMenuManager;
OptionsManager optionsManager;
#endregion
#region Textures
/// <summary>
/// The texture of the cursor.
/// </summary>
public Texture2D cursorTexture;
/// <summary>
/// The SpriteFont for debuging the game.
/// </summary>
public SpriteFont segoeUIMonoDebug;
/// <summary>
/// The SpriteFont for buttons.
/// </summary>
public SpriteFont segoeUIBold;
/// <summary>
/// The larger button terxture.
/// </summary>
public Texture2D button1Texture;
/// <summary>
/// The smaller button terxture.
/// </summary>
public Texture2D button2Texture;
/// <summary>
/// The background tiles.
/// </summary>
public Texture2D backgroundHeavy;
#endregion
#region Gui stuff
/// <summary>
/// Used to control the cursor.
/// </summary>
public Cursor cursor;
/// <summary>
/// The current game level or screen.
/// </summary>
protected GameLevels currentGameLevel;
#endregion
#region Tile stuff
/// <summary>
/// The list of tiles for the background.
/// </summary>
public List<Tile> BackgroundTilesList = new List<Tile>();
protected bool isBackgroundGenerated;
#endregion
#region Debug Stuff
/// <summary>
/// The value to debug the game.
/// </summary>
public bool GameDebug = true;
/// <summary>
/// The label used for debuging.
/// </summary>
public Label debugLabel;
/// <summary>
/// The list of strings that are used for debuging.
/// </summary>
public string[] debugStrings = new string[10];
#endregion
#endregion
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
LoadImages();
// Create the managers.
gameManager = new GameManager(this);
mainMenuManager = new MainMenuManager(this);
optionsManager = new OptionsManager(this);
// Add the managers to components.
Components.Add(gameManager);
Components.Add(mainMenuManager);
Components.Add(optionsManager);
// Disable the managers.
gameManager.Enabled = false;
gameManager.Visible = false;
mainMenuManager.Enabled = false;
mainMenuManager.Visible = false;
optionsManager.Enabled = false;
optionsManager.Visible = false;
cursor = new Cursor(cursorTexture, Vector2.Zero);
OptionsComfirmed = true;
// Create the debug label.
if (GameDebug)
{
debugLabel = new Label(new Vector2(0, 0), segoeUIMonoDebug, 1.0f, Color.White, "");
}
OptionsComfirmed = true;
// TODO: use this.Content to load your game content here
SetCurrentLevel(GameLevels.MENU);
}
protected void LoadImages()
{
// Load textures.
cursorTexture = Content.Load<Texture2D>(@"images\cursor\cursor1");
button1Texture = Content.Load<Texture2D>(@"images\gui\button2");
button2Texture = Content.Load<Texture2D>(@"images\gui\button1");
backgroundHeavy = Content.Load<Texture2D>(@"images\gui\backgroundHeavy");
// Load fonts.
segoeUIMonoDebug = Content.Load<SpriteFont>(@"fonts\segoeuimonodebug");
segoeUIBold = Content.Load<SpriteFont>(@"fonts\segoeuibold");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
{
this.Exit();
}
if (OptionsComfirmed)
{
if (WindowSize != new Point(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight))
{
graphics.PreferredBackBufferWidth = WindowSize.X;
graphics.PreferredBackBufferHeight = WindowSize.Y;
}
graphics.SynchronizeWithVerticalRetrace = isVSync;
graphics.ApplyChanges();
if (!isBackgroundGenerated)
{
GenerateBackground();
}
OptionsComfirmed = false;
OldIsOptionsChanged = isOptionsChanged;
isOptionsChanged += 1;
}
// Tell if the game is in debug mode.
if (GameDebug)
{
// Set the debug label's text.
debugLabel.Text = debugStrings[0] + "\n" +
debugStrings[1] + "\n" +
debugStrings[2] + "\n" +
debugStrings[3] + "\n" +
debugStrings[4] + "\n" +
debugStrings[5] + "\n" +
debugStrings[6] + "\n" +
debugStrings[7] + "\n" +
debugStrings[8] + "\n" +
debugStrings[9] + "\n";
}
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
public void GenerateBackground()
{
Point screenTileSize = new Point((int)(WindowSize.X / 128) + 1, (int)(WindowSize.X / 128) + 1);
for (int x = 0; x < screenTileSize.X; x++)
{
for (int y = 0; y < screenTileSize.Y; y++)
{
BackgroundTilesList.Add(new Tile(backgroundHeavy, new Vector2(x * 128, y * 128), 0, random.Next(743874982), Color.White));
}
}
isBackgroundGenerated = true;
}
/// <summary>
/// This sets the current scene or level that the game is at.
/// </summary>
/// <param name="level">The game level to change to.</param>
public void SetCurrentLevel(GameLevels level)
{
if (currentGameLevel != level)
{
currentGameLevel = level;
//splashScreenManager.Enabled = false;
//splashScreenManager.Visible = false;
mainMenuManager.Enabled = false;
mainMenuManager.Visible = false;
gameManager.Enabled = false;
gameManager.Visible = false;
optionsManager.Enabled = false;
optionsManager.Visible = false;
isBackgroundGenerated = false;
}
switch (currentGameLevel)
{
case GameLevels.SPLASH:
//splashScreenManager.Enabled = true;
//splashScreenManager.Visible = true;
break;
case GameLevels.MENU:
mainMenuManager.Enabled = true;
mainMenuManager.Visible = true;
break;
case GameLevels.OPTIONS:
optionsManager.Enabled = true;
optionsManager.Visible = true;
break;
case GameLevels.GAME:
gameManager.Enabled = true;
gameManager.Visible = true;
break;
default:
break;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Channels.Tests
{
public abstract class ChannelTestBase : TestBase
{
protected abstract Channel<int> CreateChannel();
protected abstract Channel<int> CreateFullChannel();
protected virtual bool RequiresSingleReader => false;
protected virtual bool RequiresSingleWriter => false;
[Fact]
public void ValidateDebuggerAttributes()
{
Channel<int> c = CreateChannel();
for (int i = 1; i <= 10; i++)
{
c.Writer.WriteAsync(i);
}
DebuggerAttributes.ValidateDebuggerDisplayReferences(c);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(c);
}
[Fact]
public void Cast_MatchesInOut()
{
Channel<int> c = CreateChannel();
ChannelReader<int> rc = c;
ChannelWriter<int> wc = c;
Assert.Same(rc, c.Reader);
Assert.Same(wc, c.Writer);
}
[Fact]
public void Completion_Idempotent()
{
Channel<int> c = CreateChannel();
Task completion = c.Reader.Completion;
Assert.Equal(TaskStatus.WaitingForActivation, completion.Status);
Assert.Same(completion, c.Reader.Completion);
c.Writer.Complete();
Assert.Same(completion, c.Reader.Completion);
Assert.Equal(TaskStatus.RanToCompletion, completion.Status);
}
[Fact]
public async Task Complete_AfterEmpty_NoWaiters_TriggersCompletion()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await c.Reader.Completion;
}
[Fact]
public async Task Complete_AfterEmpty_WaitingReader_TriggersCompletion()
{
Channel<int> c = CreateChannel();
Task<int> r = c.Reader.ReadAsync().AsTask();
c.Writer.Complete();
await c.Reader.Completion;
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => r);
}
[Fact]
public async Task Complete_BeforeEmpty_WaitingReaders_TriggersCompletion()
{
Channel<int> c = CreateChannel();
Task<int> read = c.Reader.ReadAsync().AsTask();
c.Writer.Complete();
await c.Reader.Completion;
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => read);
}
[Fact]
public void Complete_Twice_ThrowsInvalidOperationException()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.ThrowsAny<InvalidOperationException>(() => c.Writer.Complete());
}
[Fact]
public void TryComplete_Twice_ReturnsTrueThenFalse()
{
Channel<int> c = CreateChannel();
Assert.True(c.Writer.TryComplete());
Assert.False(c.Writer.TryComplete());
Assert.False(c.Writer.TryComplete());
}
[Fact]
public async Task TryComplete_ErrorsPropage()
{
Channel<int> c;
// Success
c = CreateChannel();
Assert.True(c.Writer.TryComplete());
await c.Reader.Completion;
// Error
c = CreateChannel();
Assert.True(c.Writer.TryComplete(new FormatException()));
await Assert.ThrowsAsync<FormatException>(() => c.Reader.Completion);
// Canceled
c = CreateChannel();
var cts = new CancellationTokenSource();
cts.Cancel();
Assert.True(c.Writer.TryComplete(new OperationCanceledException(cts.Token)));
await AssertCanceled(c.Reader.Completion, cts.Token);
}
[Fact]
public void SingleProducerConsumer_ConcurrentReadWrite_Success()
{
Channel<int> c = CreateChannel();
const int NumItems = 100000;
Task.WaitAll(
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
await c.Writer.WriteAsync(i);
}
}),
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
Assert.Equal(i, await c.Reader.ReadAsync());
}
}));
}
[Fact]
public void SingleProducerConsumer_PingPong_Success()
{
Channel<int> c1 = CreateChannel();
Channel<int> c2 = CreateChannel();
const int NumItems = 100000;
Task.WaitAll(
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
Assert.Equal(i, await c1.Reader.ReadAsync());
await c2.Writer.WriteAsync(i);
}
}),
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
await c1.Writer.WriteAsync(i);
Assert.Equal(i, await c2.Reader.ReadAsync());
}
}));
}
[Theory]
[InlineData(1, 1)]
[InlineData(1, 10)]
[InlineData(10, 1)]
[InlineData(10, 10)]
public void ManyProducerConsumer_ConcurrentReadWrite_Success(int numReaders, int numWriters)
{
if (RequiresSingleReader && numReaders > 1)
{
return;
}
if (RequiresSingleWriter && numWriters > 1)
{
return;
}
Channel<int> c = CreateChannel();
const int NumItems = 10000;
long readTotal = 0;
int remainingWriters = numWriters;
int remainingItems = NumItems;
Task[] tasks = new Task[numWriters + numReaders];
for (int i = 0; i < numReaders; i++)
{
tasks[i] = Task.Run(async () =>
{
try
{
while (await c.Reader.WaitToReadAsync())
{
if (c.Reader.TryRead(out int value))
{
Interlocked.Add(ref readTotal, value);
}
}
}
catch (ChannelClosedException) { }
});
}
for (int i = 0; i < numWriters; i++)
{
tasks[numReaders + i] = Task.Run(async () =>
{
while (true)
{
int value = Interlocked.Decrement(ref remainingItems);
if (value < 0)
{
break;
}
await c.Writer.WriteAsync(value + 1);
}
if (Interlocked.Decrement(ref remainingWriters) == 0)
{
c.Writer.Complete();
}
});
}
Task.WaitAll(tasks);
Assert.Equal((NumItems * (NumItems + 1L)) / 2, readTotal);
}
[Fact]
public void WaitToReadAsync_DataAvailableBefore_CompletesSynchronously()
{
Channel<int> c = CreateChannel();
Task write = c.Writer.WriteAsync(42);
Task<bool> read = c.Reader.WaitToReadAsync();
Assert.Equal(TaskStatus.RanToCompletion, read.Status);
}
[Fact]
public void WaitToReadAsync_DataAvailableAfter_CompletesAsynchronously()
{
Channel<int> c = CreateChannel();
Task<bool> read = c.Reader.WaitToReadAsync();
Assert.False(read.IsCompleted);
Task write = c.Writer.WriteAsync(42);
Assert.True(read.Result);
}
[Fact]
public void WaitToReadAsync_AfterComplete_SynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Task<bool> read = c.Reader.WaitToReadAsync();
Assert.Equal(TaskStatus.RanToCompletion, read.Status);
Assert.False(read.Result);
}
[Fact]
public void WaitToReadAsync_BeforeComplete_AsynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
Task<bool> read = c.Reader.WaitToReadAsync();
Assert.False(read.IsCompleted);
c.Writer.Complete();
Assert.False(read.Result);
}
[Fact]
public void WaitToWriteAsync_AfterComplete_SynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Task<bool> write = c.Writer.WaitToWriteAsync();
Assert.Equal(TaskStatus.RanToCompletion, write.Status);
Assert.False(write.Result);
}
[Fact]
public void TryRead_DataAvailable_Success()
{
Channel<int> c = CreateChannel();
Task write = c.Writer.WriteAsync(42);
Assert.True(c.Reader.TryRead(out int result));
Assert.Equal(42, result);
}
[Fact]
public void TryRead_AfterComplete_ReturnsFalse()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.False(c.Reader.TryRead(out int result));
}
[Fact]
public void TryWrite_AfterComplete_ReturnsFalse()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.False(c.Writer.TryWrite(42));
}
[Fact]
public async Task WriteAsync_AfterComplete_ThrowsException()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => c.Writer.WriteAsync(42));
}
[Fact]
public async Task Complete_WithException_PropagatesToCompletion()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
Assert.Same(exc, await Assert.ThrowsAsync<FormatException>(() => c.Reader.Completion));
}
[Fact]
public async Task Complete_WithCancellationException_PropagatesToCompletion()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
cts.Cancel();
Exception exc = null;
try { cts.Token.ThrowIfCancellationRequested(); }
catch (Exception e) { exc = e; }
c.Writer.Complete(exc);
await AssertCanceled(c.Reader.Completion, cts.Token);
}
[Fact]
public async Task Complete_WithException_PropagatesToExistingWriter()
{
Channel<int> c = CreateFullChannel();
if (c != null)
{
Task write = c.Writer.WriteAsync(42);
var exc = new FormatException();
c.Writer.Complete(exc);
Assert.Same(exc, (await Assert.ThrowsAsync<ChannelClosedException>(() => write)).InnerException);
}
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWriter()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
Task write = c.Writer.WriteAsync(42);
Assert.Same(exc, (await Assert.ThrowsAsync<ChannelClosedException>(() => write)).InnerException);
}
[Fact]
public async Task Complete_WithException_PropagatesToExistingWaitingReader()
{
Channel<int> c = CreateChannel();
Task<bool> read = c.Reader.WaitToReadAsync();
var exc = new FormatException();
c.Writer.Complete(exc);
await Assert.ThrowsAsync<FormatException>(() => read);
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWaitingReader()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
Task<bool> read = c.Reader.WaitToReadAsync();
await Assert.ThrowsAsync<FormatException>(() => read);
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWaitingWriter()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
Task<bool> write = c.Writer.WaitToWriteAsync();
await Assert.ThrowsAsync<FormatException>(() => write);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void ManyWriteAsync_ThenManyTryRead_Success(int readMode)
{
if (RequiresSingleReader || RequiresSingleWriter)
{
return;
}
Channel<int> c = CreateChannel();
const int NumItems = 2000;
Task[] writers = new Task[NumItems];
for (int i = 0; i < writers.Length; i++)
{
writers[i] = c.Writer.WriteAsync(i);
}
Task<int>[] readers = new Task<int>[NumItems];
for (int i = 0; i < readers.Length; i++)
{
int result;
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.All(writers, w => Assert.True(w.IsCompleted));
}
[Fact]
public void Precancellation_Writing_ReturnsSuccessImmediately()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
cts.Cancel();
Task writeTask = c.Writer.WriteAsync(42, cts.Token);
Assert.True(writeTask.Status == TaskStatus.Canceled || writeTask.Status == TaskStatus.RanToCompletion, $"Status == {writeTask.Status}");
Task<bool> waitTask = c.Writer.WaitToWriteAsync(cts.Token);
Assert.True(writeTask.Status == TaskStatus.Canceled || writeTask.Status == TaskStatus.RanToCompletion, $"Status == {writeTask.Status}");
if (waitTask.Status == TaskStatus.RanToCompletion)
{
Assert.True(waitTask.Result);
}
}
[Fact]
public void Write_WaitToReadAsync_CompletesSynchronously()
{
Channel<int> c = CreateChannel();
c.Writer.WriteAsync(42);
AssertSynchronousTrue(c.Reader.WaitToReadAsync());
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Layouts
{
using NLog.LayoutRenderers;
using NLog.LayoutRenderers.Wrappers;
using NLog.Layouts;
using NLog.Targets;
using Xunit;
public class SimpleLayoutParserTests : NLogTestBase
{
[Fact]
public void SimpleTest()
{
SimpleLayout l = "${message}";
Assert.Equal(1, l.Renderers.Count);
Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]);
}
[Fact]
public void UnclosedTest()
{
new SimpleLayout("${message");
}
[Fact]
public void SingleParamTest()
{
SimpleLayout l = "${mdc:item=AAA}";
Assert.Equal(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA", mdc.Item);
}
[Fact]
public void ValueWithColonTest()
{
SimpleLayout l = "${mdc:item=AAA\\:}";
Assert.Equal(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA:", mdc.Item);
}
[Fact]
public void ValueWithBracketTest()
{
SimpleLayout l = "${mdc:item=AAA\\}\\:}";
Assert.Equal("${mdc:item=AAA\\}\\:}", l.Text);
//Assert.Equal(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA}:", mdc.Item);
}
[Fact]
public void DefaultValueTest()
{
SimpleLayout l = "${mdc:BBB}";
//Assert.Equal(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("BBB", mdc.Item);
}
[Fact]
public void DefaultValueWithBracketTest()
{
SimpleLayout l = "${mdc:AAA\\}\\:}";
Assert.Equal(l.Text, "${mdc:AAA\\}\\:}");
Assert.Equal(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA}:", mdc.Item);
}
[Fact]
public void DefaultValueWithOtherParametersTest()
{
SimpleLayout l = "${exception:message,type:separator=x}";
Assert.Equal(1, l.Renderers.Count);
ExceptionLayoutRenderer elr = l.Renderers[0] as ExceptionLayoutRenderer;
Assert.NotNull(elr);
Assert.Equal("message,type", elr.Format);
Assert.Equal("x", elr.Separator);
}
[Fact]
public void EmptyValueTest()
{
SimpleLayout l = "${mdc:item=}";
Assert.Equal(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("", mdc.Item);
}
[Fact]
public void NestedLayoutTest()
{
SimpleLayout l = "${rot13:inner=${ndc:topFrames=3:separator=x}}";
Assert.Equal(1, l.Renderers.Count);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Equal(1, nestedLayout.Renderers.Count);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.NotNull(ndcLayoutRenderer);
Assert.Equal(3, ndcLayoutRenderer.TopFrames);
Assert.Equal("x", ndcLayoutRenderer.Separator);
}
[Fact]
public void DoubleNestedLayoutTest()
{
SimpleLayout l = "${rot13:inner=${rot13:inner=${ndc:topFrames=3:separator=x}}}";
Assert.Equal(1, l.Renderers.Count);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout0 = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout0);
Assert.Equal("${rot13:inner=${ndc:topFrames=3:separator=x}}", nestedLayout0.Text);
var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
var nestedLayout = innerRot13.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Equal(1, nestedLayout.Renderers.Count);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.NotNull(ndcLayoutRenderer);
Assert.Equal(3, ndcLayoutRenderer.TopFrames);
Assert.Equal("x", ndcLayoutRenderer.Separator);
}
[Fact]
public void DoubleNestedLayoutWithDefaultLayoutParametersTest()
{
SimpleLayout l = "${rot13:${rot13:${ndc:topFrames=3:separator=x}}}";
Assert.Equal(1, l.Renderers.Count);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout0 = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout0);
Assert.Equal("${rot13:${ndc:topFrames=3:separator=x}}", nestedLayout0.Text);
var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
var nestedLayout = innerRot13.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Equal(1, nestedLayout.Renderers.Count);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.NotNull(ndcLayoutRenderer);
Assert.Equal(3, ndcLayoutRenderer.TopFrames);
Assert.Equal("x", ndcLayoutRenderer.Separator);
}
[Fact]
public void AmbientPropertyTest()
{
SimpleLayout l = "${message:padding=10}";
Assert.Equal(1, l.Renderers.Count);
var pad = l.Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void MissingLayoutRendererTest()
{
Assert.Throws<NLogConfigurationException>(() =>
{
SimpleLayout l = "${rot13:${foobar}}";
});
}
[Fact]
public void DoubleAmbientPropertyTest()
{
SimpleLayout l = "${message:uppercase=true:padding=10}";
Assert.Equal(1, l.Renderers.Count);
var upperCase = l.Renderers[0] as UppercaseLayoutRendererWrapper;
Assert.NotNull(upperCase);
var pad = ((SimpleLayout)upperCase.Inner).Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void ReverseDoubleAmbientPropertyTest()
{
SimpleLayout l = "${message:padding=10:uppercase=true}";
Assert.Equal(1, l.Renderers.Count);
var pad = ((SimpleLayout)l).Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var upperCase = ((SimpleLayout)pad.Inner).Renderers[0] as UppercaseLayoutRendererWrapper;
Assert.NotNull(upperCase);
var message = ((SimpleLayout)upperCase.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void EscapeTest()
{
AssertEscapeRoundTrips(string.Empty);
AssertEscapeRoundTrips("hello ${${}} world!");
AssertEscapeRoundTrips("hello $");
AssertEscapeRoundTrips("hello ${");
AssertEscapeRoundTrips("hello $${{");
AssertEscapeRoundTrips("hello ${message}");
AssertEscapeRoundTrips("hello ${${level}}");
AssertEscapeRoundTrips("hello ${${level}${message}}");
}
[Fact]
public void EvaluateTest()
{
var logEventInfo = LogEventInfo.CreateNullEvent();
logEventInfo.Level = LogLevel.Warn;
Assert.Equal("Warn", SimpleLayout.Evaluate("${level}", logEventInfo));
}
[Fact]
public void EvaluateTest2()
{
Assert.Equal("Off", SimpleLayout.Evaluate("${level}"));
Assert.Equal(string.Empty, SimpleLayout.Evaluate("${message}"));
Assert.Equal(string.Empty, SimpleLayout.Evaluate("${logger}"));
}
private static void AssertEscapeRoundTrips(string originalString)
{
string escapedString = SimpleLayout.Escape(originalString);
SimpleLayout l = escapedString;
string renderedString = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal(originalString, renderedString);
}
[Fact]
public void LayoutParserEscapeCodesForRegExTestV1()
{
MappedDiagnosticsContext.Clear();
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name=""searchExp""
value=""(?<!\\d[ -]*)(?\u003a(?<digits>\\d)[ -]*)\u007b8,16\u007d(?=(\\d[ -]*)\u007b3\u007d(\\d)(?![ -]\\d))""
/>
<variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" />
<targets>
<target name=""d1"" type=""Debug"" layout=""${message1}"" />
</targets>
<rules>
<logger name=""*"" minlevel=""Trace"" writeTo=""d1"" />
</rules>
</nlog>");
var d1 = configuration.FindTargetByName("d1") as DebugTarget;
Assert.NotNull(d1);
var layout = d1.Layout as SimpleLayout;
Assert.NotNull(layout);
var c = layout.Renderers.Count;
Assert.Equal(1, c);
var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper;
Assert.NotNull(l1);
Assert.Equal(true, l1.Regex);
Assert.Equal(true, l1.IgnoreCase);
Assert.Equal(@"::", l1.ReplaceWith);
Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor);
}
[Fact]
public void LayoutParserEscapeCodesForRegExTestV2()
{
MappedDiagnosticsContext.Clear();
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name=""searchExp""
value=""(?<!\\d[ -]*)(?\:(?<digits>\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))""
/>
<variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" />
<targets>
<target name=""d1"" type=""Debug"" layout=""${message1}"" />
</targets>
<rules>
<logger name=""*"" minlevel=""Trace"" writeTo=""d1"" />
</rules>
</nlog>");
var d1 = configuration.FindTargetByName("d1") as DebugTarget;
Assert.NotNull(d1);
var layout = d1.Layout as SimpleLayout;
Assert.NotNull(layout);
var c = layout.Renderers.Count;
Assert.Equal(1, c);
var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper;
Assert.NotNull(l1);
Assert.Equal(true, l1.Regex);
Assert.Equal(true, l1.IgnoreCase);
Assert.Equal(@"::", l1.ReplaceWith);
Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor);
}
[Fact]
public void InnerLayoutWithColonTest_with_workaround()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test${literal:text=\:} Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test: Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithColonTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\: Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test: Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithSlashSingleTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test\\Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithSlashTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test\\Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest2()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\\}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal(@"Test{Hello\}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_reverse()
{
SimpleLayout l = @"${when:Inner=Test{Hello\}:when=1 == 1}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_no_escape()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest()
{
SimpleLayout l = @"${when:when=1 == 1:inner=Log_{#\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Log_{#}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest_need_escape()
{
SimpleLayout l = @"${when:when=1 == 1:inner=L\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("L}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape()
{
SimpleLayout l = @"${when:when=1 == 1:inner=\}{.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("}{.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape2()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}{.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}{.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape3()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape4()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape5()
{
SimpleLayout l = @"${when:when=1 == 1:inner=\}{a\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("}{a}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest_and_layoutrender()
{
SimpleLayout l = @"${when:when=1 == 1:inner=${counter}/Log_{#\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("1/Log_{#}.log", l.Render(le));
}
}
}
| |
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 d3ssignalr.Areas.HelpPage.ModelDescriptions;
using d3ssignalr.Areas.HelpPage.Models;
namespace d3ssignalr.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);
}
}
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green ([email protected])
*
* SharpNEAT is free software; you can redistribute it and/or modify
* it under the terms of The MIT License (MIT).
*
* You should have received a copy of the MIT License
* along with SharpNEAT; if not, see https://opensource.org/licenses/MIT.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using SharpNeat.Core;
namespace SharpNeat.DistanceMetrics
{
// TODO: Include coefficients and constant present on ManhattanDistance metric.
/// <summary>
/// Euclidean distance metric.
///
/// The Euclidean distance is given by sqrt(sum(delta^2))
/// Where [delta] is the absolute position difference in a given dimension (on a given axis).
/// </summary>
public class EuclideanDistanceMetric : IDistanceMetric
{
#region IDistanceMetric Members
/// <summary>
/// Tests if the distance between two positions is less than some threshold.
///
/// A simple way of implementing this method would be to calculate the distance between the
/// two coordinates and test if it is less than the threshold. However, that approach requires that all of the
/// elements in both CoordinateVectors be fully compared. We can improve performance in the general case
/// by testing if the threshold has been passed after each vector element comparison thus allowing an early exit
/// from the method for many calls. Further to this, we can begin comparing from the ends of the vectors where
/// differences are most likely to occur.
/// </summary>
public bool TestDistance(CoordinateVector p1, CoordinateVector p2, double threshold)
{
// Instead of calculating the euclidean distance we calculate distance squared (we skip the final sqrt
// part of the formula). If we then square the threshold value this obviates the need to take the square
// root when comparing our accumulating calculated distance with the threshold.
threshold = threshold * threshold;
KeyValuePair<ulong,double>[] arr1 = p1.CoordArray;
KeyValuePair<ulong,double>[] arr2 = p2.CoordArray;
// Store these heavily used values locally.
int arr1Length = arr1.Length;
int arr2Length = arr2.Length;
//--- Test for special cases.
if(0 == arr1Length && 0 == arr2Length)
{ // Both arrays are empty. No disparities, therefore the distance is zero.
return 0.0 < threshold;
}
double distance = 0.0;
if(0 == arr1Length)
{ // All arr2 elements are mismatches.
// p1 doesn't specify a value in these dimensions therefore we take its position to be 0 in all of them.
for(int i=0; i<arr2Length; i++) {
distance += arr2[i].Value * arr2[i].Value;
}
return distance < threshold;
}
if(0 == arr2Length)
{ // All arr1 elements are mismatches.
// p2 doesn't specify a value in these dimensions therefore we take it's position to be 0 in all of them.
for(int i=0; i<arr1Length; i++) {
distance += arr1[i].Value * arr1[i].Value;
}
return distance < threshold;
}
//----- Both arrays contain elements. Compare the contents starting from the ends where the greatest discrepancies
// between coordinates are expected to occur. Generally this should result in less element comparisons
// before the threshold is passed and we exit the method.
int arr1Idx = arr1Length - 1;
int arr2Idx = arr2Length - 1;
KeyValuePair<ulong,double> elem1 = arr1[arr1Idx];
KeyValuePair<ulong,double> elem2 = arr2[arr2Idx];
for(;;)
{
if(elem2.Key > elem1.Key)
{
// p1 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += elem2.Value * elem2.Value;
// Move to the next element in arr2.
arr2Idx--;
}
else if(elem1.Key == elem2.Key)
{
// Matching elements. Note that abs() isn't required because we square the result.
double tmp = elem1.Value - elem2.Value;
distance += tmp * tmp;
// Move to the next element in both lists.
arr1Idx--;
arr2Idx--;
}
else // elem1.Key > elem2.Key
{
// p2 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += elem1.Value * elem1.Value;
// Move to the next element in arr1.
arr1Idx--;
}
// Test the threshold.
if(distance >= threshold) {
return false;
}
// Check if we have exhausted one or both of the arrays.
if(arr1Idx < 0)
{ // Any remaining arr2 elements are mismatches.
for(int i=arr2Idx; i > -1; i--) {
distance += arr2[i].Value * arr2[i].Value;
}
return distance < threshold;
}
if(arr2Idx < 0)
{ // All remaining arr1 elements are mismatches.
for(int i=arr1Idx; i > -1; i--) {
distance += arr1[i].Value * arr1[i].Value;
}
return distance < threshold;
}
elem1 = arr1[arr1Idx];
elem2 = arr2[arr2Idx];
}
}
/// <summary>
/// Gets the distance between two positions.
/// </summary>
public double GetDistance(CoordinateVector p1, CoordinateVector p2)
{
KeyValuePair<ulong,double>[] arr1 = p1.CoordArray;
KeyValuePair<ulong,double>[] arr2 = p2.CoordArray;
// Store these heavily used values locally.
int arr1Length = arr1.Length;
int arr2Length = arr2.Length;
//--- Test for special cases.
if(0 == arr1Length && 0 == arr2Length)
{ // Both arrays are empty. No disparities, therefore the distance is zero.
return 0.0;
}
double distance = 0;
if(0 == arr1Length)
{ // All arr2 genes are mismatches.
for(int i=0; i<arr2Length; i++) {
distance += arr2[i].Value * arr2[i].Value;
}
return Math.Sqrt(distance);
}
if(0 == arr2Length)
{ // All arr1 elements are mismatches.
for(int i=0; i<arr1Length; i++) {
distance += arr1[i].Value * arr1[i].Value;
}
return Math.Sqrt(distance);
}
//----- Both arrays contain elements.
int arr1Idx = 0;
int arr2Idx = 0;
KeyValuePair<ulong,double> elem1 = arr1[arr1Idx];
KeyValuePair<ulong,double> elem2 = arr2[arr2Idx];
for(;;)
{
if(elem1.Key < elem2.Key)
{
// p2 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += elem1.Value * elem1.Value;
// Move to the next element in arr1.
arr1Idx++;
}
else if(elem1.Key == elem2.Key)
{
// Matching elements. Note that abs() isn't required because we square the result.
double tmp = elem1.Value - elem2.Value;
distance += tmp * tmp;
// Move to the next element in both arrays.
arr1Idx++;
arr2Idx++;
}
else // elem2.Key < elem1.Key
{
// p1 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += elem2.Value * elem2.Value;
// Move to the next element in arr2.
arr2Idx++;
}
// Check if we have exhausted one or both of the arrays.
if(arr1Idx == arr1.Length)
{ // All remaining arr2 elements are mismatches.
for(int i=arr2Idx; i<arr2Length; i++) {
distance += arr2[i].Value * arr2[i].Value;
}
return Math.Sqrt(distance);
}
if(arr2Idx == arr2Length)
{ // All remaining arr1 elements are mismatches.
for(int i=arr1Idx; i<arr1.Length; i++) {
distance += arr1[i].Value * arr1[i].Value;
}
return Math.Sqrt(distance);
}
elem1 = arr1[arr1Idx];
elem2 = arr2[arr2Idx];
}
}
/// <summary>
/// Calculates the centroid for the given set of points.
/// For the Euclidean distance metric the centroid is given by calculating the componentwise mean over the
/// set of points.
/// </summary>
public CoordinateVector CalculateCentroid(IList<CoordinateVector> coordList)
{
// Special case - one item in list, it *is* the centroid.
if(1 == coordList.Count) {
return coordList[0];
}
// Each coordinate element has an ID. Here we calculate the total for each ID across all CoordinateVectors,
// then divide the totals by the number of CoordinateVectors to get the average for each ID. That is, we
// calculate the component-wise mean.
//
// Coord elements within a CoordinateVector must be sorted by ID, therefore we use a SortedDictionary here
// when building the centroid coordinate to eliminate the need to sort elements later.
//
// We use SortedDictionary and not SortedList for performance. SortedList is fastest for insertion
// only if the inserts are in order (sorted). However, this is generally not the case here because although
// coordinate IDs are sorted within the source CoordinateVectors, not all IDs exist within all CoordinateVectors
// therefore a low ID may be presented to coordElemTotals after a higher ID.
SortedDictionary<ulong, double[]> coordElemTotals = new SortedDictionary<ulong,double[]>();
// Loop over coords.
foreach(CoordinateVector coord in coordList)
{
// Loop over each element within the current coord.
foreach(KeyValuePair<ulong,double> coordElem in coord.CoordArray)
{
// If the ID has previously been encountered then add the current element value to it, otherwise
// add a new double[1] to hold the value..
// Note that we wrap the double value in an object so that we do not have to re-insert values
// to increment them. In tests this approach was about 40% faster (including GC overhead).
double[] doubleWrapper;
if(coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper)) {
doubleWrapper[0] += coordElem.Value;
}
else {
coordElemTotals.Add(coordElem.Key, new double[]{coordElem.Value});
}
}
}
// Put the unique coord elems from coordElemTotals into a list, dividing each element's value
// by the total number of coords as we go.
double coordCountReciprocol = 1.0 / (double)coordList.Count;
KeyValuePair<ulong,double>[] centroidElemArr = new KeyValuePair<ulong,double>[coordElemTotals.Count];
int i=0;
foreach(KeyValuePair<ulong,double[]> coordElem in coordElemTotals)
{ // For speed we multiply by reciprocal instead of dividing by coordCount.
centroidElemArr[i++] = new KeyValuePair<ulong,double>(coordElem.Key, coordElem.Value[0] * coordCountReciprocol);
}
// Use the new list of elements to construct a centroid CoordinateVector.
return new CoordinateVector(centroidElemArr);
}
/// <summary>
/// Parallelized version of CalculateCentroid().
/// </summary>
public CoordinateVector CalculateCentroidParallel(IList<CoordinateVector> coordList)
{
// Special case - one item in list, it *is* the centroid.
if (1 == coordList.Count)
{
return coordList[0];
}
// Each coordinate element has an ID. Here we calculate the total for each ID across all CoordinateVectors,
// then divide the totals by the number of CoordinateVectors to get the average for each ID. That is, we
// calculate the component-wise mean.
// ConcurrentDictionary provides a low-locking strategy that greatly improves performance here
// compared to using mutual exclusion locks or even ReadWriterLock(s).
ConcurrentDictionary<ulong,double[]> coordElemTotals = new ConcurrentDictionary<ulong, double[]>();
// Loop over coords.
Parallel.ForEach(coordList, delegate(CoordinateVector coord)
{
// Loop over each element within the current coord.
foreach (KeyValuePair<ulong, double> coordElem in coord.CoordArray)
{
// If the ID has previously been encountered then add the current element value to it, otherwise
// add a new double[1] to hold the value.
// Note that we wrap the double value in an object so that we do not have to re-insert values
// to increment them. In tests this approach was about 40% faster (including GC overhead).
// If position is zero then (A) skip doing any work, and (B) zero will break the following logic.
if (coordElem.Value == 0.0) {
continue;
}
double[] doubleWrapper;
if (coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper))
{ // By locking just the specific object that holds the value we are incrementing
// we greatly reduce the amount of lock contention.
lock(doubleWrapper)
{
doubleWrapper[0] += coordElem.Value;
}
}
else
{
doubleWrapper = new double[] { coordElem.Value };
if (!coordElemTotals.TryAdd(coordElem.Key, doubleWrapper))
{
if(coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper))
{
lock (doubleWrapper)
{
doubleWrapper[0] += coordElem.Value;
}
}
}
}
}
});
// Put the unique coord elems from coordElemTotals into a list, dividing each element's value
// by the total number of coords as we go.
double coordCountReciprocol = 1.0 / (double)coordList.Count;
KeyValuePair<ulong, double>[] centroidElemArr = new KeyValuePair<ulong, double>[coordElemTotals.Count];
int i = 0;
foreach (KeyValuePair<ulong, double[]> coordElem in coordElemTotals)
{ // For speed we multiply by reciprocal instead of dividing by coordCount.
centroidElemArr[i++] = new KeyValuePair<ulong, double>(coordElem.Key, coordElem.Value[0] * coordCountReciprocol);
}
// Coord elements within a CoordinateVector must be sorted by ID.
Array.Sort(centroidElemArr, delegate(KeyValuePair<ulong, double> x, KeyValuePair<ulong, double> y)
{
if (x.Key < y.Key) {
return -1;
}
if (x.Key > y.Key) {
return 1;
}
return 0;
});
// Use the new list of elements to construct a centroid CoordinateVector.
return new CoordinateVector(centroidElemArr);
}
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Reactive;
using System.Reactive.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
namespace GitHub.UI
{
[ContentProperty("TextBox")]
public class RichTextBoxAutoCompleteTextInput : IAutoCompleteTextInput
{
private static readonly int newLineLength = Environment.NewLine.Length;
const int promptRichTextBoxCaretIndexAdjustments = 2;
RichTextBox textBox;
public event PropertyChangedEventHandler PropertyChanged;
TextPointer ContentStart
{
get { return textBox.Document.ContentStart; }
}
TextPointer ContentEnd
{
get
{
// RichTextBox always appends a new line at the end. So we need to back that shit up.
return textBox.Document.ContentEnd.GetPositionAtOffset(-1 * newLineLength)
?? textBox.Document.ContentEnd;
}
}
public void Select(int position, int length)
{
var textRange = new TextRange(ContentStart, ContentEnd);
if (textRange.Text.Length >= (position + length))
{
var start = textRange.Start.GetPositionAtOffset(GetOffsetIndex(position), LogicalDirection.Forward);
var end = textRange.Start.GetPositionAtOffset(GetOffsetIndex(position + length), LogicalDirection.Backward);
if (start != null && end != null)
textBox.Selection.Select(start, end);
}
}
public void SelectAll()
{
textBox.Selection.Select(ContentStart, ContentEnd);
}
public int CaretIndex
{
get
{
var start = ContentStart;
var caret = textBox.CaretPosition;
var range = new TextRange(start, caret);
return range.Text.Length;
}
set
{
Select(value, 0);
Debug.Assert(value == CaretIndex,
String.Format(CultureInfo.InvariantCulture,
"I just set the caret index to '{0}' but it's '{1}'", value, CaretIndex));
}
}
public int SelectionStart
{
get
{
return new TextRange(ContentStart, textBox.Selection.Start).Text.Length;
}
}
public int SelectionLength
{
get { return CaretIndex - SelectionStart; }
}
#if DEBUG
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
#endif
public string Text
{
get
{
return new TextRange(ContentStart, ContentEnd).Text;
}
set
{
textBox.Document.Blocks.Clear();
if (!string.IsNullOrEmpty(value))
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(value)))
{
var contents = new TextRange(ContentStart, ContentEnd);
contents.Load(stream, DataFormats.Text);
}
}
}
}
public IObservable<EventPattern<KeyEventArgs>> PreviewKeyDown
{
get;
private set;
}
public IObservable<EventPattern<RoutedEventArgs>> SelectionChanged { get; private set; }
public IObservable<EventPattern<TextChangedEventArgs>> TextChanged { get; private set; }
public UIElement Control { get { return textBox; } }
public Point GetPositionFromCharIndex(int charIndex)
{
var offset = new TextRange(ContentStart, textBox.CaretPosition)
.Start
.GetPositionAtOffset(charIndex, LogicalDirection.Forward);
return offset != null
? offset.GetCharacterRect(LogicalDirection.Forward).BottomLeft
: new Point(0, 0);
}
public Thickness Margin
{
get { return textBox.Margin; }
set { textBox.Margin = value; }
}
public void Focus()
{
Keyboard.Focus(textBox);
}
public RichTextBox TextBox
{
get
{
return textBox;
}
set
{
if (value != textBox)
{
textBox = value;
PreviewKeyDown = Observable.FromEventPattern<KeyEventHandler, KeyEventArgs>(
h => textBox.PreviewKeyDown += h,
h => textBox.PreviewKeyDown -= h);
SelectionChanged = Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
h => textBox.SelectionChanged += h,
h => textBox.SelectionChanged -= h);
TextChanged = Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>(
h => textBox.TextChanged += h,
h => textBox.TextChanged -= h);
NotifyPropertyChanged("Control");
}
}
}
// This is a fudge factor needed because of PromptRichTextBox. When commit messages are 51 characters or more,
// The PromptRichTextBox applies a styling that fucks up the CaretPosition by 2. :(
// This method helps us account for that.
int GetOffsetIndex(int selectionEnd)
{
if (textBox is PromptRichTextBox && selectionEnd >= PromptRichTextBox.BadCommitMessageLength)
{
return selectionEnd + promptRichTextBoxCaretIndexAdjustments;
}
return selectionEnd;
}
private void NotifyPropertyChanged(String info)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using ARSoft.Tools.Net;
using ARSoft.Tools.Net.Dns;
namespace ASC.Common.Utils
{
public class DnsLookup
{
private readonly IDnsResolver _sDnsResolver;
private readonly DnsClient _dnsClient;
public DnsLookup()
{
_dnsClient = DnsClient.Default;
_sDnsResolver = new DnsStubResolver(_dnsClient);
}
/// <summary>
/// Get domain MX records
/// </summary>
/// <param name="domainName">domain name</param>
/// <exception cref="ArgumentNullException">if domainName is empty</exception>
/// <exception cref="ArgumentException">if domainName is invalid</exception>
/// <returns>list of MxRecord</returns>
public List<MxRecord> GetDomainMxRecords(string domainName)
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentNullException("domainName");
var mxRecords = DnsResolve<MxRecord>(domainName, RecordType.Mx);
return mxRecords;
}
/// <summary>
/// Check existance of MX record in domain DNS
/// </summary>
/// <param name="domainName">domain name</param>
/// <param name="mxRecord">MX record value</param>
/// <exception cref="ArgumentNullException">if domainName is empty</exception>
/// <exception cref="ArgumentException">if domainName is invalid</exception>
/// <returns>true if exists and vice versa</returns>
public bool IsDomainMxRecordExists(string domainName, string mxRecord)
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentNullException("domainName");
if (string.IsNullOrEmpty(mxRecord))
throw new ArgumentNullException("mxRecord");
var mxDomain = DomainName.Parse(mxRecord);
var records = GetDomainMxRecords(domainName);
return records.Any(
mx => mx.ExchangeDomainName.Equals(mxDomain));
}
/// <summary>
/// Check domain existance
/// </summary>
/// <param name="domainName"></param>
/// <exception cref="ArgumentNullException">if domainName is empty</exception>
/// <exception cref="ArgumentException">if domainName is invalid</exception>
/// <exception cref="SystemException">if DNS request failed</exception>
/// <returns>true if any DNS record exists and vice versa</returns>
public bool IsDomainExists(string domainName)
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentNullException("domainName");
var dnsMessage = GetDnsMessage(domainName);
return dnsMessage.AnswerRecords.Any();
}
/// <summary>
/// Get domain A records
/// </summary>
/// <param name="domainName">domain name</param>
/// <exception cref="ArgumentNullException">if domainName is empty</exception>
/// <exception cref="ArgumentException">if domainName is invalid</exception>
/// <returns>list of ARecord</returns>
public List<ARecord> GetDomainARecords(string domainName)
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentNullException("domainName");
var aRecords = DnsResolve<ARecord>(domainName, RecordType.A);
return aRecords;
}
/// <summary>
/// Get domain IP addresses list
/// </summary>
/// <param name="domainName">domain name</param>
/// <exception cref="ArgumentNullException">if domainName is empty</exception>
/// <exception cref="ArgumentException">if domainName is invalid</exception>
/// <returns>list of IPAddress</returns>
public List<IPAddress> GetDomainIPs(string domainName)
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentNullException("domainName");
var addresses = _sDnsResolver.ResolveHost(domainName);
return addresses;
}
/// <summary>
/// Get domain TXT records
/// </summary>
/// <param name="domainName">domain name</param>
/// <exception cref="ArgumentNullException">if domainName is empty</exception>
/// <exception cref="ArgumentException">if domainName is invalid</exception>
/// <returns>list of TxtRecord</returns>
public List<TxtRecord> GetDomainTxtRecords(string domainName)
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentNullException("domainName");
var txtRecords = DnsResolve<TxtRecord>(domainName, RecordType.Txt);
return txtRecords;
}
/// <summary>
/// Check existance of TXT record in domain DNS
/// </summary>
/// <param name="domainName">domain name</param>
/// <param name="recordValue">TXT record value</param>
/// <exception cref="ArgumentNullException">if domainName is empty</exception>
/// <exception cref="ArgumentException">if domainName is invalid</exception>
/// <returns>true if exists and vice versa</returns>
public bool IsDomainTxtRecordExists(string domainName, string recordValue)
{
var txtRecords = GetDomainTxtRecords(domainName);
return
txtRecords.Any(
txtRecord =>
txtRecord.TextData.Trim('\"').Equals(recordValue, StringComparison.InvariantCultureIgnoreCase));
}
/// <summary>
/// Check existance of DKIM record in domain DNS
/// </summary>
/// <param name="domainName">domain name</param>
/// <param name="dkimSelector">DKIM selector (example is "dkim")</param>
/// <param name="dkimValue">DKIM record value</param>
/// <exception cref="ArgumentNullException">if domainName is empty</exception>
/// <exception cref="ArgumentException">if domainName is invalid</exception>
/// <returns>true if exists and vice versa</returns>
public bool IsDomainDkimRecordExists(string domainName, string dkimSelector, string dkimValue)
{
var dkimRecordName = dkimSelector + "._domainkey." + domainName;
var txtRecords = GetDomainTxtRecords(dkimRecordName);
return txtRecords.Any(txtRecord => txtRecord.TextData.Trim('\"').Equals(dkimValue));
}
/// <summary>
/// Check existance Domain in PTR record
/// </summary>
/// <param name="ipAddress">IP address for PTR check</param>
/// <param name="domainName">PTR domain name</param>
/// <exception cref="ArgumentNullException">if domainName or ipAddress is empty/null</exception>
/// <exception cref="ArgumentException">if domainName is invalid</exception>
/// <returns>true if exists and vice versa</returns>
public bool IsDomainPtrRecordExists(IPAddress ipAddress, string domainName)
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentNullException("domainName");
if (ipAddress == null)
throw new ArgumentNullException("ipAddress");
var domain = DomainName.Parse(domainName);
var ptrDomain = _sDnsResolver.ResolvePtr(ipAddress);
return ptrDomain.Equals(domain);
}
/// <summary>
/// Check existance Domain in PTR record
/// </summary>
/// <param name="ipAddress">IP address for PTR check</param>
/// <param name="domainName">PTR domain name</param>
/// <exception cref="ArgumentNullException">if domainName or ipAddress is empty/null</exception>
/// <exception cref="ArgumentException">if domainName is invalid</exception>
/// <exception cref="FormatException">if ipAddress is invalid</exception>
/// <returns>true if exists and vice versa</returns>
public bool IsDomainPtrRecordExists(string ipAddress, string domainName)
{
return IsDomainPtrRecordExists(IPAddress.Parse(ipAddress), domainName);
}
private DnsMessage GetDnsMessage(string domainName, RecordType? type = null)
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentNullException("domainName");
var domain = DomainName.Parse(domainName);
var dnsMessage = type.HasValue ? _dnsClient.Resolve(domain, type.Value) : _dnsClient.Resolve(domain);
if ((dnsMessage == null) ||
((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain)))
{
throw new SystemException(); // DNS request failed
}
return dnsMessage;
}
private List<T> DnsResolve<T>(string domainName, RecordType type)
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentNullException("domainName");
var dnsMessage = GetDnsMessage(domainName, type);
return dnsMessage.AnswerRecords.Where(r => r.RecordType == type).Cast<T>().ToList();
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using GodLesZ.Library.Json.Linq;
using GodLesZ.Library.Json.Serialization;
using GodLesZ.Library.Json.Utilities;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
#endif
namespace GodLesZ.Library.Json.Schema
{
/// <summary>
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
/// </summary>
public class JsonSchemaGenerator
{
/// <summary>
/// Gets or sets how undefined schemas are handled by the serializer.
/// </summary>
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
private IContractResolver _contractResolver;
/// <summary>
/// Gets or sets the contract resolver.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
return DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
private class TypeSchema
{
public Type Type { get; private set; }
public JsonSchema Schema { get; private set;}
public TypeSchema(Type type, JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(schema, "schema");
Type = type;
Schema = schema;
}
}
private JsonSchemaResolver _resolver;
private readonly IList<TypeSchema> _stack = new List<TypeSchema>();
private JsonSchema _currentSchema;
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
private void Push(TypeSchema typeSchema)
{
_currentSchema = typeSchema.Schema;
_stack.Add(typeSchema);
_resolver.LoadedSchemas.Add(typeSchema.Schema);
}
private TypeSchema Pop()
{
TypeSchema popped = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
TypeSchema newValue = _stack.LastOrDefault();
if (newValue != null)
{
_currentSchema = newValue.Schema;
}
else
{
_currentSchema = null;
}
return popped;
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type)
{
return Generate(type, new JsonSchemaResolver(), false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{
return Generate(type, resolver, false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, bool rootSchemaNullable)
{
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
_resolver = resolver;
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
}
private string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
return null;
}
private string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type);
if (descriptionAttribute != null)
return descriptionAttribute.Description;
#endif
return null;
}
private string GetTypeId(Type type, bool explicitOnly)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
return containerAttribute.Id;
if (explicitOnly)
return null;
switch (UndefinedSchemaIdHandling)
{
case UndefinedSchemaIdHandling.UseTypeName:
return type.FullName;
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
return type.AssemblyQualifiedName;
default:
return null;
}
}
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
{
ValidationUtils.ArgumentNotNull(type, "type");
string resolvedId = GetTypeId(type, false);
string explicitId = GetTypeId(type, true);
if (!string.IsNullOrEmpty(resolvedId))
{
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
if (resolvedSchema != null)
{
// resolved schema is not null but referencing member allows nulls
// change resolved schema to allow nulls. hacky but what are ya gonna do?
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
resolvedSchema.Type |= JsonSchemaType.Null;
if (required && resolvedSchema.Required != true)
resolvedSchema.Required = true;
return resolvedSchema;
}
}
// test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type))
{
throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
}
JsonContract contract = ContractResolver.ResolveContract(type);
JsonConverter converter;
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
{
JsonSchema converterSchema = converter.GetSchema();
if (converterSchema != null)
return converterSchema;
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
CurrentSchema.Id = explicitId;
if (required)
CurrentSchema.Required = true;
CurrentSchema.Title = GetTitle(type);
CurrentSchema.Description = GetDescription(type);
if (converter != null)
{
// todo: Add GetSchema to JsonConverter and use here?
CurrentSchema.Type = JsonSchemaType.Any;
}
else
{
switch (contract.ContractType)
{
case JsonContractType.Object:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateObjectSchema(type, (JsonObjectContract) contract);
break;
case JsonContractType.Array:
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
}
break;
case JsonContractType.Primitive:
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof (FlagsAttribute), true))
{
CurrentSchema.Enum = new List<JToken>();
EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
}
}
break;
case JsonContractType.String:
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
? JsonSchemaType.String
: AddNullType(JsonSchemaType.String, valueRequired);
CurrentSchema.Type = schemaType;
break;
case JsonContractType.Dictionary:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
JsonContract keyContract = ContractResolver.ResolveContract(keyType);
// can be converted to a string
if (keyContract.ContractType == JsonContractType.Primitive)
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
}
}
break;
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
case JsonContractType.Serializable:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateISerializableContract(type, (JsonISerializableContract) contract);
break;
#endif
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE40)
case JsonContractType.Dynamic:
#endif
case JsonContractType.Linq:
CurrentSchema.Type = JsonSchemaType.Any;
break;
default:
throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
}
}
return Pop().Schema;
}
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired)
{
if (valueRequired != Required.Always)
return type | JsonSchemaType.Null;
return type;
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private void GenerateObjectSchema(Type type, JsonObjectContract contract)
{
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
foreach (JsonProperty property in contract.Properties)
{
if (!property.Ignored)
{
bool optional = property.NullValueHandling == NullValueHandling.Ignore ||
HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) ||
property.ShouldSerialize != null ||
property.GetIsSpecified != null;
JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional);
if (property.DefaultValue != null)
propertySchema.Default = JToken.FromObject(property.DefaultValue);
CurrentSchema.Properties.Add(property.PropertyName, propertySchema);
}
}
if (type.IsSealed())
CurrentSchema.AllowAdditionalProperties = false;
}
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
private void GenerateISerializableContract(Type type, JsonISerializableContract contract)
{
CurrentSchema.AllowAdditionalProperties = true;
}
#endif
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
{
// default value is Any
if (value == null)
return true;
bool match = ((value & flag) == flag);
if (match)
return true;
// integer is a subset of float
if (value == JsonSchemaType.Float && flag == JsonSchemaType.Integer)
return true;
return false;
}
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
{
JsonSchemaType schemaType = JsonSchemaType.None;
if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
{
schemaType = JsonSchemaType.Null;
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
}
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type);
switch (typeCode)
{
case PrimitiveTypeCode.Empty:
case PrimitiveTypeCode.Object:
return schemaType | JsonSchemaType.String;
#if !(NETFX_CORE || PORTABLE)
case PrimitiveTypeCode.DBNull:
return schemaType | JsonSchemaType.Null;
#endif
case PrimitiveTypeCode.Boolean:
return schemaType | JsonSchemaType.Boolean;
case PrimitiveTypeCode.Char:
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.SByte:
case PrimitiveTypeCode.Byte:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.UInt32:
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
#if !(PORTABLE || NET35 || NET20 || WINDOWS_PHONE || SILVERLIGHT)
case PrimitiveTypeCode.BigInteger:
#endif
return schemaType | JsonSchemaType.Integer;
case PrimitiveTypeCode.Single:
case PrimitiveTypeCode.Double:
case PrimitiveTypeCode.Decimal:
return schemaType | JsonSchemaType.Float;
// convert to string?
case PrimitiveTypeCode.DateTime:
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
#endif
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.String:
case PrimitiveTypeCode.Uri:
case PrimitiveTypeCode.Guid:
case PrimitiveTypeCode.TimeSpan:
case PrimitiveTypeCode.Bytes:
return schemaType | JsonSchemaType.String;
default:
throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System.IO;
using NodeDefinition;
using Pathfinding;
using Particles2DPipelineSample;
namespace HackPrototype
{
class CurrencyStringer
{
public StringBuilder outputstring;
private StringBuilder workingstring;
public CurrencyStringer(UInt64 startingamount)
{
outputstring = new StringBuilder();
workingstring = new StringBuilder();
UpdateString(startingamount);
}
public void UpdateString(UInt64 amount)
{
workingstring.Remove(0, workingstring.Length);
workingstring.Append(amount);
int oldlength = workingstring.Length;
int numcommas = (oldlength - 1) / 3;
int newlength = oldlength + numcommas;
char[] old_workingarray = new char[oldlength];
//workingstring.CopyTo(0, old_workingarray, 0, oldlength); //NOT SUPPORTED ON WP7
for (int i = 0; i < oldlength; i++)
{
old_workingarray[i] = workingstring[i];
}
char[] new_workingarray = new char[newlength];
if (oldlength > 4)
{
int old_counter = oldlength - 1;
int commacounter = 1;
for (int i = newlength - 1; i >= 0; i--, commacounter++)
{
if (commacounter % 4 == 0)
{
new_workingarray[i] = ',';
}
else
{
new_workingarray[i] = old_workingarray[old_counter];
old_counter--;
}
}
}
else
{
//workingstring.CopyTo(0, new_workingarray, 0, oldlength); //NOT SUPPORTED ON WP7
new_workingarray = new char[oldlength];
for (int i = 0; i < oldlength; i++)
{
new_workingarray[i] = workingstring[i];
}
}
outputstring.Remove(0, outputstring.Length);
outputstring.Append('$');
outputstring.Append(new_workingarray);
}
}
public class WaveAccountingEntry
{
public int c_wave;
public UInt64 c_score;
public WaveAccountingEntry()
{
c_wave = 0;
c_score = 0;
}
public WaveAccountingEntry(int wave, UInt64 score)
{
c_wave = wave;
c_score = score;
}
}
public class WaveAccountingTable
{
List<WaveAccountingEntry> entries;
int maxentries;
public WaveAccountingTable(int maxWaves)
{
maxentries = maxWaves;
entries = new List<WaveAccountingEntry>();
FillWithEmpty();
}
public void FillWithEmpty()
{
entries.Clear();
for(int i = 0; i < maxentries; i++)
{
entries.Add(new WaveAccountingEntry(i + 1, 0));
}
}
public List<WaveAccountingEntry> GetEntries()
{
return entries;
}
public bool ModifyEntry(int wave, UInt64 score)
{
if (wave > 0 && wave <= maxentries)
{
//find it
for (int i = 0; i < maxentries; i++)
{
if (entries[i].c_wave == wave)
{
entries[i].c_score = score;
return true;
}
}
return false;
}
else
return false;
}
public void Load(List<WaveAccountingEntry> list)
{
this.entries.Clear();
this.maxentries = list.Count;
FillWithEmpty();
for (int i = 0; i < list.Count; i++)
{
entries[i] = list[i];
}
}
}
class HackGameBoard_Scoring
{
//ACTUAL SCORE METRICS
UInt64 score = 0;
UInt64 scoreLeftToAdd = 0;
float scoreToAddPerSecond = 0.0f;
float score_UpdateTimeLeft = 0.0f;
float score_UpdateTimeMax = 2.0f;
HackGameBoard board;
CurrencyStringer scorestring = new CurrencyStringer(0);
public UInt64 GetScore()
{
return score;
}
public HackGameBoard_Scoring(HackGameBoard ourBoard)
{
board = ourBoard;
}
public enum HackGameBoard_Scoring_DisplayState
{
HackGameBoard_Scoring_DisplayState_Up,
HackGameBoard_Scoring_DisplayState_PoppingUp,
HackGameBoard_Scoring_DisplayState_PoppingDown,
HackGameBoard_Scoring_DisplayState_Down
}
public HackGameBoard_Scoring_DisplayState state = HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_Down;
public Vector2 DrawLocation_Shell = new Vector2(0, 380);
public Vector2 DrawLocation_AlertShell = new Vector2(402, 382);
public Vector2 DrawLocation_BonusShell = new Vector2(502, 382);
public Vector2 DrawLocation_ScoreText = new Vector2(13, 393);
public Vector2 DrawLocation_TargetSlices = new Vector2(402, 382);
public Vector2 DrawLocation_AlertLightOne = new Vector2(405, 430);
public Vector2 DrawLocation_AlertLightTwo = new Vector2(435, 430);
public Vector2 DrawLocation_AlertLightThree = new Vector2(465, 430);
public Vector2 Offset_Up = new Vector2(0, 0);
public Vector2 Offset_Down = new Vector2(0, 99);
public float offsetT = 0.0f;
public float popUpSpeed = 1.4f;
public float popDownSpeed = 1.4f;
FlashingElement AlertLightOne_Flash = new FlashingElement(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOff);
FlashingElement AlertLightTwo_Flash = new FlashingElement(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOff);
FlashingElement AlertLightThree_Flash = new FlashingElement(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOff);
int currentAlertLevel = 0;
public const float alertFlashSpeed = 0.50f;
public const float alertFlashLength = 3.0f;
public void AddScore(int scoreToAddOn)
{
if (scoreToAddOn <= 0)
return;
board.GetMedia().StartMoneyLoopSound();
if (score_UpdateTimeLeft <= 0.0f)
{
score_UpdateTimeLeft = score_UpdateTimeMax;
}
else
{
score_UpdateTimeLeft += score_UpdateTimeMax;
}
scoreLeftToAdd += (UInt64)scoreToAddOn;
scoreToAddPerSecond = (float)scoreLeftToAdd / score_UpdateTimeMax;
}
public int GetCurrentAlertLevel()
{
return currentAlertLevel;
}
public void SetCurrentAlertLevel(int level)
{
//can't be greater than 3 or less than zero
if (level > 3)
level = 3;
if (level < 0)
level = 0;
//first, check delta between current and new
if (currentAlertLevel == level)
return; //no change
else if (currentAlertLevel > level)
{
//flash only the lowest level
if (level == 0)
{
AlertLightOne_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOff);
AlertLightTwo_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOff);
AlertLightThree_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOff);
}
else if (level == 1)
{
AlertLightOne_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_Normal);
AlertLightOne_Flash.ChangeToModeAfter(alertFlashLength, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOn);
AlertLightTwo_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOff);
AlertLightThree_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOff);
}
else if (level == 2)
{
AlertLightOne_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOn);
AlertLightTwo_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_Normal);
AlertLightTwo_Flash.ChangeToModeAfter(alertFlashLength, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOn);
AlertLightThree_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOff);
}
else
{
AlertLightOne_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOn);
AlertLightTwo_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOn);
AlertLightThree_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_Normal);
AlertLightThree_Flash.ChangeToModeAfter(alertFlashLength, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOn);
}
}
else
{
//don't touch other levels, let them do what they do.
if (level == 1)
{
AlertLightOne_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_Normal);
AlertLightOne_Flash.ChangeToModeAfter(alertFlashLength, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOn);
}
else if (level == 2)
{
AlertLightTwo_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_Normal);
AlertLightTwo_Flash.ChangeToModeAfter(alertFlashLength, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOn);
}
else
{
AlertLightThree_Flash.Reset(alertFlashSpeed, false, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_Normal);
AlertLightThree_Flash.ChangeToModeAfter(alertFlashLength, FlashingElement.FlashingElement_OperationType.FlashingElement_OperationType_StayOn);
}
}
//and finally - set it.
currentAlertLevel = level;
}
public void DrawSelf(HackNodeGameBoardMedia drawing, SpriteBatch spriteBatch, GraphicsDevice GraphicsDevice, HackGameAgent_Player player)
{
Vector2 offset = GetCurrentOffset();
spriteBatch.Draw(drawing.LowerUI_Shell, DrawLocation_Shell + offset, Color.White);
//spriteBatch.Draw(drawing.LowerUI_AlertShell, DrawLocation_AlertShell + offset, Color.White);
//spriteBatch.Draw(drawing.LowerUI_BonusShell, DrawLocation_BonusShell + offset, Color.White);
//Draw the numbers
spriteBatch.DrawString(drawing.LowerUI_Score_Font, scorestring.outputstring, DrawLocation_ScoreText + offset, Color.Red);
//Draw the alert lights
//spriteBatch.Draw(AlertLightOne_Flash.IsOn() ? drawing.LowerUI_Alert_Light_On : drawing.LowerUI_Alert_Light_Off, DrawLocation_AlertLightOne + offset, Color.White);
//spriteBatch.Draw(AlertLightTwo_Flash.IsOn() ? drawing.LowerUI_Alert_Light_On : drawing.LowerUI_Alert_Light_Off, DrawLocation_AlertLightTwo + offset, Color.White);
//spriteBatch.Draw(AlertLightThree_Flash.IsOn() ? drawing.LowerUI_Alert_Light_On : drawing.LowerUI_Alert_Light_Off, DrawLocation_AlertLightThree + offset, Color.White);
//Draw the target slice
float currentTargetCompletion = 0.0f;
if (board != null && board.GetTargetCashToExit() > 0)
{
currentTargetCompletion = (float)((double)(GetScore()) / (double)(board.GetTargetCashToExit()));
}
Texture2D chosenTargetSprite;
if (currentTargetCompletion >= 1.0f)
{
chosenTargetSprite = drawing.TargetSlice_100_Percent;
}
else if (currentTargetCompletion >= 0.75f)
{
chosenTargetSprite = drawing.TargetSlice_75_Percent;
}
else if (currentTargetCompletion >= 0.50f)
{
chosenTargetSprite = drawing.TargetSlice_50_Percent;
}
else if (currentTargetCompletion >= 0.25f)
{
chosenTargetSprite = drawing.TargetSlice_25_Percent;
}
else
{
chosenTargetSprite = drawing.TargetSlice_0_Percent;
}
if (chosenTargetSprite != null)
{
spriteBatch.Draw(chosenTargetSprite, DrawLocation_TargetSlices + offset, Color.White);
}
}
public void UpdateSelf(GameTime time)
{
/*
switch (state)
{
case HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_Up:
currentStayUpTime -= (float)time.ElapsedGameTime.TotalSeconds;
if (currentStayUpTime <= 0.0f)
{
offsetT = 0.0f;
state = HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_PoppingDown;
}
break;
case HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_PoppingDown:
offsetT += popDownSpeed * (float)time.ElapsedGameTime.TotalSeconds;
if (offsetT >= 1.0f)
{
state = HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_Down;
}
break;
case HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_PoppingUp:
offsetT += popUpSpeed * (float)time.ElapsedGameTime.TotalSeconds;
if (offsetT >= 1.0f)
{
state = HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_Up;
}
break;
}*/
//update any score left to add
if (scoreLeftToAdd > 0)
{
score_UpdateTimeLeft -= (float)time.ElapsedGameTime.TotalSeconds;
UInt64 scoreDelta = (UInt64)MathHelper.Min((scoreToAddPerSecond * (float)time.ElapsedGameTime.TotalSeconds), (float)scoreLeftToAdd);
score += scoreDelta;
scorestring.UpdateString(score);
scoreLeftToAdd -= scoreDelta;
if (scoreLeftToAdd <= 0)
{
scoreLeftToAdd = 0;
score_UpdateTimeLeft = 0.0f;
//stop the sound
board.GetMedia().StopMoneyLoopSound();
}
}
//update all blinkenlights
AlertLightOne_Flash.Update(time);
AlertLightTwo_Flash.Update(time);
AlertLightThree_Flash.Update(time);
}
public Vector2 GetCurrentOffset()
{
/*
Vector2 returnVec = new Vector2();
switch (state)
{
case HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_Up:
returnVec = Offset_Up;
break;
case HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_Down:
returnVec = Offset_Down;
break;
case HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_PoppingDown:
returnVec.X = Offset_Up.X + (Offset_Down.X - Offset_Up.X) * offsetT;
returnVec.Y = Offset_Up.Y + (Offset_Down.Y - Offset_Up.Y) * offsetT;
break;
case HackGameBoard_Scoring_DisplayState.HackGameBoard_Scoring_DisplayState_PoppingUp:
returnVec.X = Offset_Down.X + (Offset_Up.X - Offset_Down.X) * offsetT;
returnVec.Y = Offset_Down.Y + (Offset_Up.Y - Offset_Down.Y) * offsetT;
break;
}*/
Vector2 returnVec = Offset_Up;
//BUGBUG: temporary addition hack to correct for portrait mode
returnVec.Y += 320.0f;
return returnVec;
}
}
}
| |
using System;
using System.Collections.Generic;
using IdmNet.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// ReSharper disable ObjectCreationAsStatement
// ReSharper disable UseObjectOrCollectionInitializer
namespace IdmNet.Models.Tests
{
[TestClass]
public class SynchronizationRuleTests
{
private SynchronizationRule _it;
public SynchronizationRuleTests()
{
_it = new SynchronizationRule();
}
[TestMethod]
public void It_has_a_paremeterless_constructor()
{
Assert.AreEqual("SynchronizationRule", _it.ObjectType);
}
[TestMethod]
public void It_has_a_constructor_that_takes_an_IdmResource()
{
var resource = new IdmResource
{
DisplayName = "My Display Name",
Creator = new Person { DisplayName = "Creator Display Name", ObjectID = "Creator ObjectID"},
};
var it = new SynchronizationRule(resource);
Assert.AreEqual("SynchronizationRule", it.ObjectType);
Assert.AreEqual("My Display Name", it.DisplayName);
Assert.AreEqual("Creator Display Name", it.Creator.DisplayName);
}
[TestMethod]
public void It_has_a_constructor_that_takes_an_IdmResource_without_Creator()
{
var resource = new IdmResource
{
DisplayName = "My Display Name",
};
var it = new SynchronizationRule(resource);
Assert.AreEqual("My Display Name", it.DisplayName);
Assert.IsNull(it.Creator);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void It_throws_when_you_try_to_set_ObjectType_to_anything_other_than_its_primary_ObjectType()
{
_it.ObjectType = "Invalid Object Type";
}
[TestMethod]
public void It_can_get_and_set_CreateConnectedSystemObject()
{
// Act
_it.CreateConnectedSystemObject = true;
// Assert
Assert.AreEqual(true, _it.CreateConnectedSystemObject);
}
[TestMethod]
public void It_can_get_and_set_CreateILMObject()
{
// Act
_it.CreateILMObject = true;
// Assert
Assert.AreEqual(true, _it.CreateILMObject);
}
[TestMethod]
public void It_can_get_and_set_FlowType()
{
// Act
_it.FlowType = 123;
// Assert
Assert.AreEqual(123, _it.FlowType);
}
[TestMethod]
public void It_has_Dependency_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.Dependency);
}
[TestMethod]
public void It_has_Dependency_which_can_be_set_back_to_null()
{
// Arrange
var testSynchronizationRule = new SynchronizationRule { DisplayName = "Test SynchronizationRule" };
_it.Dependency = testSynchronizationRule;
// Act
_it.Dependency = null;
// Assert
Assert.IsNull(_it.Dependency);
}
[TestMethod]
public void It_can_get_and_set_Dependency()
{
// Act
var testSynchronizationRule = new SynchronizationRule { DisplayName = "Test SynchronizationRule" };
_it.Dependency = testSynchronizationRule;
// Assert
Assert.AreEqual(testSynchronizationRule.DisplayName, _it.Dependency.DisplayName);
}
[TestMethod]
public void It_can_get_and_set_DisconnectConnectedSystemObject()
{
// Act
_it.DisconnectConnectedSystemObject = true;
// Assert
Assert.AreEqual(true, _it.DisconnectConnectedSystemObject);
}
[TestMethod]
public void It_has_ExistenceTest_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.ExistenceTest);
}
[TestMethod]
public void It_has_ExistenceTest_which_can_be_set_back_to_null()
{
// Arrange
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
_it.ExistenceTest = list;
// Act
_it.ExistenceTest = null;
// Assert
Assert.IsNull(_it.ExistenceTest);
}
[TestMethod]
public void It_can_get_and_set_ExistenceTest()
{
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
// Act
_it.ExistenceTest = list;
// Assert
Assert.AreEqual("foo1", _it.ExistenceTest[0]);
Assert.AreEqual("foo2", _it.ExistenceTest[1]);
}
[TestMethod]
public void It_can_get_and_set_ConnectedSystem()
{
// Act
_it.ConnectedSystem = "A string";
// Assert
Assert.AreEqual("A string", _it.ConnectedSystem);
}
[TestMethod]
public void It_can_get_and_set_ConnectedObjectType()
{
// Act
_it.ConnectedObjectType = "A string";
// Assert
Assert.AreEqual("A string", _it.ConnectedObjectType);
}
[TestMethod]
public void It_can_get_and_set_ConnectedSystemScope()
{
// Act
_it.ConnectedSystemScope = "A string";
// Assert
Assert.AreEqual("A string", _it.ConnectedSystemScope);
}
[TestMethod]
public void It_can_get_and_set_ILMObjectType()
{
// Act
_it.ILMObjectType = "A string";
// Assert
Assert.AreEqual("A string", _it.ILMObjectType);
}
[TestMethod]
public void It_has_InitialFlow_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.InitialFlow);
}
[TestMethod]
public void It_has_InitialFlow_which_can_be_set_back_to_null()
{
// Arrange
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
_it.InitialFlow = list;
// Act
_it.InitialFlow = null;
// Assert
Assert.IsNull(_it.InitialFlow);
}
[TestMethod]
public void It_can_get_and_set_InitialFlow()
{
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
// Act
_it.InitialFlow = list;
// Assert
Assert.AreEqual("foo1", _it.InitialFlow[0]);
Assert.AreEqual("foo2", _it.InitialFlow[1]);
}
[TestMethod]
public void It_has_ManagementAgentID_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.ManagementAgentID);
}
[TestMethod]
public void It_has_ManagementAgentID_which_can_be_set_back_to_null()
{
// Arrange
var testma_data = new ma_data { DisplayName = "Test ma_data" };
_it.ManagementAgentID = testma_data;
// Act
_it.ManagementAgentID = null;
// Assert
Assert.IsNull(_it.ManagementAgentID);
}
[TestMethod]
public void It_can_get_and_set_ManagementAgentID()
{
// Act
var testma_data = new ma_data { DisplayName = "Test ma_data" };
_it.ManagementAgentID = testma_data;
// Assert
Assert.AreEqual(testma_data.DisplayName, _it.ManagementAgentID.DisplayName);
}
[TestMethod]
public void It_has_msidmOutboundIsFilterBased_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.msidmOutboundIsFilterBased);
}
[TestMethod]
public void It_has_msidmOutboundIsFilterBased_which_can_be_set_back_to_null()
{
// Arrange
_it.msidmOutboundIsFilterBased = true;
// Act
_it.msidmOutboundIsFilterBased = null;
// Assert
Assert.IsNull(_it.msidmOutboundIsFilterBased);
}
[TestMethod]
public void It_can_get_and_set_msidmOutboundIsFilterBased()
{
// Act
_it.msidmOutboundIsFilterBased = true;
// Assert
Assert.AreEqual(true, _it.msidmOutboundIsFilterBased);
}
[TestMethod]
public void It_can_get_and_set_msidmOutboundScopingFilters()
{
// Act
_it.msidmOutboundScopingFilters = "A string";
// Assert
Assert.AreEqual("A string", _it.msidmOutboundScopingFilters);
}
[TestMethod]
public void It_has_PersistentFlow_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.PersistentFlow);
}
[TestMethod]
public void It_has_PersistentFlow_which_can_be_set_back_to_null()
{
// Arrange
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
_it.PersistentFlow = list;
// Act
_it.PersistentFlow = null;
// Assert
Assert.IsNull(_it.PersistentFlow);
}
[TestMethod]
public void It_can_get_and_set_PersistentFlow()
{
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
// Act
_it.PersistentFlow = list;
// Assert
Assert.AreEqual("foo1", _it.PersistentFlow[0]);
Assert.AreEqual("foo2", _it.PersistentFlow[1]);
}
[TestMethod]
public void It_has_Precedence_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.Precedence);
}
[TestMethod]
public void It_has_Precedence_which_can_be_set_back_to_null()
{
// Arrange
_it.Precedence = 123;
// Act
_it.Precedence = null;
// Assert
Assert.IsNull(_it.Precedence);
}
[TestMethod]
public void It_can_get_and_set_Precedence()
{
// Act
_it.Precedence = 123;
// Assert
Assert.AreEqual(123, _it.Precedence);
}
[TestMethod]
public void It_can_get_and_set_RelationshipCriteria()
{
// Act
_it.RelationshipCriteria = "A string";
// Assert
Assert.AreEqual("A string", _it.RelationshipCriteria);
}
[TestMethod]
public void It_has_SynchronizationRuleParameters_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.SynchronizationRuleParameters);
}
[TestMethod]
public void It_has_SynchronizationRuleParameters_which_can_be_set_back_to_null()
{
// Arrange
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
_it.SynchronizationRuleParameters = list;
// Act
_it.SynchronizationRuleParameters = null;
// Assert
Assert.IsNull(_it.SynchronizationRuleParameters);
}
[TestMethod]
public void It_can_get_and_set_SynchronizationRuleParameters()
{
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
// Act
_it.SynchronizationRuleParameters = list;
// Assert
Assert.AreEqual("foo1", _it.SynchronizationRuleParameters[0]);
Assert.AreEqual("foo2", _it.SynchronizationRuleParameters[1]);
}
}
}
| |
//
// PersistentColumnController.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Hyena.Data;
using Hyena.Data.Gui;
using Banshee.Sources;
using Banshee.Configuration;
namespace Banshee.Collection.Gui
{
public class PersistentColumnController : ColumnController
{
private string root_namespace;
private bool loaded = false;
private bool pending_changes;
private uint timer_id = 0;
private string parent_source_ns;
private string source_ns;
private Source source;
public Source Source {
get { return source; }
set {
if (source == value) {
return;
}
if (source != null) {
Save ();
}
source = value;
source_ns = parent_source_ns = null;
if (source != null) {
// If we have a parent, use their UniqueId as a fallback in
// case this source's column settings haven't been changed
// from its parents
parent_source_ns = String.Format ("{0}.{1}.", root_namespace, source.ParentConfigurationId);
source_ns = String.Format ("{0}.{1}.", root_namespace, source.ConfigurationId);
Load ();
}
}
}
public PersistentColumnController (string rootNamespace) : base ()
{
if (String.IsNullOrEmpty (rootNamespace)) {
throw new ArgumentException ("Argument must not be null or empty", "rootNamespace");
}
root_namespace = rootNamespace;
}
public void Load ()
{
lock (this) {
if (source == null) {
return;
}
loaded = false;
int i = 0;
foreach (Column column in this) {
if (column.Id != null) {
column.Visible = Get<bool> (column.Id, "visible", column.Visible);
column.Width = Get<double> (column.Id, "width", column.Width);
column.OrderHint = Get<int> (column.Id, "order", i);
} else {
column.OrderHint = -1;
}
i++;
}
Columns.Sort ((a, b) => a.OrderHint.CompareTo (b.OrderHint));
string sort_column_id = Get<string> ("sort", "column", null);
if (sort_column_id != null) {
ISortableColumn sort_column = null;
foreach (Column column in this) {
if (column.Id == sort_column_id) {
sort_column = column as ISortableColumn;
break;
}
}
if (sort_column != null) {
int sort_dir = Get<int> ("sort", "direction", 0);
SortType sort_type = sort_dir == 0 ? SortType.None : sort_dir == 1 ? SortType.Ascending : SortType.Descending;
sort_column.SortType = sort_type;
base.SortColumn = sort_column;
}
} else {
base.SortColumn = null;
}
loaded = true;
}
OnUpdated ();
}
public override ISortableColumn SortColumn {
set { base.SortColumn = value; Save (); }
}
public void Save ()
{
if (timer_id == 0) {
timer_id = GLib.Timeout.Add (500, OnTimeout);
} else {
pending_changes = true;
}
}
private bool OnTimeout ()
{
if (pending_changes) {
pending_changes = false;
return true;
} else {
SaveCore ();
timer_id = 0;
return false;
}
}
private void SaveCore ()
{
lock (this) {
if (source == null) {
return;
}
for (int i = 0; i < Count; i++) {
if (Columns[i].Id != null) {
Save (Columns[i], i);
}
}
if (SortColumn != null) {
Set<string> ("sort", "column", SortColumn.Id);
Set<int> ("sort", "direction", (int)SortColumn.SortType);
}
}
}
private void Set<T> (string ns, string key, T val)
{
string conf_ns = source_ns + ns;
T result;
if (source_ns != parent_source_ns) {
if (!ConfigurationClient.Instance.TryGet (conf_ns, key, out result) && val != null &&
val.Equals (ConfigurationClient.Instance.Get<T> (parent_source_ns + ns, key, default (T)))) {
conf_ns = null;
}
}
if (conf_ns != null) {
ConfigurationClient.Instance.Set<T> (conf_ns, key, val);
}
}
private T Get<T> (string ns, string key, T fallback)
{
T result;
if (ConfigurationClient.Instance.TryGet<T> (source_ns + ns, key, out result)) {
return result;
}
if (source_ns != parent_source_ns) {
return ConfigurationClient.Instance.Get<T> (parent_source_ns + ns, key, fallback);
}
return fallback;
}
private void Save (Column column, int index)
{
Set<int> (column.Id, "order", index);
Set<bool> (column.Id, "visible", column.Visible);
Set<double> (column.Id, "width", column.Width);
}
protected override void OnWidthsChanged ()
{
if (loaded) {
Save ();
}
base.OnWidthsChanged ();
}
public override bool EnableColumnMenu {
get { return true; }
}
}
}
| |
// Copyright 2018 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.LongRunning.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using apis = Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>Generated snippets</summary>
public class GeneratedOperationsClientSnippets
{
/// <summary>Snippet for GetOperationAsync</summary>
public async Task GetOperationAsync()
{
// Snippet: GetOperationAsync(string,CallSettings)
// Additional: GetOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
Operation response = await operationsClient.GetOperationAsync(name);
// End snippet
}
/// <summary>Snippet for GetOperation</summary>
public void GetOperation()
{
// Snippet: GetOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
Operation response = operationsClient.GetOperation(name);
// End snippet
}
/// <summary>Snippet for GetOperationAsync</summary>
public async Task GetOperationAsync_RequestObject()
{
// Snippet: GetOperationAsync(GetOperationRequest,CallSettings)
// Additional: GetOperationAsync(GetOperationRequest,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
GetOperationRequest request = new GetOperationRequest
{
Name = "",
};
// Make the request
Operation response = await operationsClient.GetOperationAsync(request);
// End snippet
}
/// <summary>Snippet for GetOperation</summary>
public void GetOperation_RequestObject()
{
// Snippet: GetOperation(GetOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
GetOperationRequest request = new GetOperationRequest
{
Name = "",
};
// Make the request
Operation response = operationsClient.GetOperation(request);
// End snippet
}
/// <summary>Snippet for ListOperationsAsync</summary>
public async Task ListOperationsAsync()
{
// Snippet: ListOperationsAsync(string,string,string,int?,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
string filter = "";
// Make the request
PagedAsyncEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperationsAsync(name, filter);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Operation 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((ListOperationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
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<Operation> 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 (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListOperations</summary>
public void ListOperations()
{
// Snippet: ListOperations(string,string,string,int?,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
string filter = "";
// Make the request
PagedEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperations(name, filter);
// Iterate over all response items, lazily performing RPCs as required
foreach (Operation 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 (ListOperationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
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<Operation> 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 (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListOperationsAsync</summary>
public async Task ListOperationsAsync_RequestObject()
{
// Snippet: ListOperationsAsync(ListOperationsRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
ListOperationsRequest request = new ListOperationsRequest
{
Name = "",
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperationsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Operation 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((ListOperationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
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<Operation> 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 (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListOperations</summary>
public void ListOperations_RequestObject()
{
// Snippet: ListOperations(ListOperationsRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
ListOperationsRequest request = new ListOperationsRequest
{
Name = "",
Filter = "",
};
// Make the request
PagedEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperations(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Operation 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 (ListOperationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
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<Operation> 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 (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CancelOperationAsync</summary>
public async Task CancelOperationAsync()
{
// Snippet: CancelOperationAsync(string,CallSettings)
// Additional: CancelOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
await operationsClient.CancelOperationAsync(name);
// End snippet
}
/// <summary>Snippet for CancelOperation</summary>
public void CancelOperation()
{
// Snippet: CancelOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
operationsClient.CancelOperation(name);
// End snippet
}
/// <summary>Snippet for CancelOperationAsync</summary>
public async Task CancelOperationAsync_RequestObject()
{
// Snippet: CancelOperationAsync(CancelOperationRequest,CallSettings)
// Additional: CancelOperationAsync(CancelOperationRequest,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
CancelOperationRequest request = new CancelOperationRequest
{
Name = "",
};
// Make the request
await operationsClient.CancelOperationAsync(request);
// End snippet
}
/// <summary>Snippet for CancelOperation</summary>
public void CancelOperation_RequestObject()
{
// Snippet: CancelOperation(CancelOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
CancelOperationRequest request = new CancelOperationRequest
{
Name = "",
};
// Make the request
operationsClient.CancelOperation(request);
// End snippet
}
/// <summary>Snippet for DeleteOperationAsync</summary>
public async Task DeleteOperationAsync()
{
// Snippet: DeleteOperationAsync(string,CallSettings)
// Additional: DeleteOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
await operationsClient.DeleteOperationAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteOperation</summary>
public void DeleteOperation()
{
// Snippet: DeleteOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
operationsClient.DeleteOperation(name);
// End snippet
}
/// <summary>Snippet for DeleteOperationAsync</summary>
public async Task DeleteOperationAsync_RequestObject()
{
// Snippet: DeleteOperationAsync(DeleteOperationRequest,CallSettings)
// Additional: DeleteOperationAsync(DeleteOperationRequest,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
DeleteOperationRequest request = new DeleteOperationRequest
{
Name = "",
};
// Make the request
await operationsClient.DeleteOperationAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteOperation</summary>
public void DeleteOperation_RequestObject()
{
// Snippet: DeleteOperation(DeleteOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
DeleteOperationRequest request = new DeleteOperationRequest
{
Name = "",
};
// Make the request
operationsClient.DeleteOperation(request);
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DevExpress.Mvvm.Native {
[DebuggerStepThrough]
public
static class MayBe {
public static TR With<TI, TR>(this TI input, Func<TI, TR> evaluator)
where TI : class
where TR : class {
if(input == null)
return null;
return evaluator(input);
}
public static TR WithString<TR>(this string input, Func<string, TR> evaluator)
where TR : class {
if(string.IsNullOrEmpty(input))
return null;
return evaluator(input);
}
public static TR Return<TI, TR>(this TI? input, Func<TI?, TR> evaluator, Func<TR> fallback) where TI : struct {
if(!input.HasValue)
return fallback != null ? fallback() : default(TR);
return evaluator(input.Value);
}
public static TR Return<TI, TR>(this TI input, Func<TI, TR> evaluator, Func<TR> fallback) where TI : class {
if(input == null)
return fallback != null ? fallback() : default(TR);
return evaluator(input);
}
public static bool ReturnSuccess<TI>(this TI input) where TI : class {
return input != null;
}
public static TI If<TI>(this TI input, Func<TI, bool> evaluator) where TI : class {
if(input == null)
return null;
return evaluator(input) ? input : null;
}
public static TI IfNot<TI>(this TI input, Func<TI, bool> evaluator) where TI : class {
if(input == null)
return null;
return evaluator(input) ? null : input;
}
public static TI Do<TI>(this TI input, Action<TI> action) where TI : class {
if(input == null)
return null;
action(input);
return input;
}
}
public
static class DictionaryExtensions {
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> createValueDelegate) {
TValue result;
if(!dictionary.TryGetValue(key, out result)) {
dictionary[key] = (result = createValueDelegate());
}
return result;
}
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> createValueDelegate) {
TValue result;
if(!dictionary.TryGetValue(key, out result)) {
dictionary[key] = (result = createValueDelegate(key));
}
return result;
}
#if !WINUI && (!DXCORE3 || MVVM)
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) {
TValue result;
dictionary.TryGetValue(key, out result);
return result;
}
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue) {
TValue result;
if(dictionary.TryGetValue(key, out result))
return result;
return defaultValue;
}
#endif
}
public
static class EmptyArray<TElement> {
public static readonly TElement[] Instance = new TElement[0];
}
public
struct UnitT { }
public
sealed class VoidT {
VoidT() { }
}
public
static class LinqExtensions {
public static bool IsEmptyOrSingle<T>(this IEnumerable<T> source) {
return !source.Any() || !source.Skip(1).Any();
}
public static bool IsSingle<T>(this IEnumerable<T> source) {
return source.Any() && !source.Skip(1).Any();
}
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {
if(source == null)
return;
foreach(T t in source)
action(t);
}
public static void ForEach<T>(this IEnumerable<T> source, Action<T, int> action) {
if(source == null)
return;
int index = 0;
foreach(T t in source)
action(t, index++);
}
public static void ForEach<TFirst, TSecond>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Action<TFirst, TSecond> action) {
using(var en1 = first.GetEnumerator())
using(var en2 = second.GetEnumerator()) {
while(en1.MoveNext() && en2.MoveNext()) {
action(en1.Current, en2.Current);
}
}
}
public static int IndexOf<T>(this IEnumerable<T> source, Predicate<T> predicate) {
int index = 0;
foreach(var item in source) {
if(predicate(item))
return index;
index++;
}
return -1;
}
public static TAccumulate AggregateUntil<T, TAccumulate>(this IEnumerable<T> source, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func, Func<TAccumulate, bool> stop) {
foreach(var item in source) {
if(stop(seed)) break;
seed = func(seed, item);
}
return seed;
}
public static IEnumerable<T> Unfold<T>(T seed, Func<T, T> next, Func<T, bool> stop) {
for(var current = seed; !stop(current); current = next(current)) {
yield return current;
}
}
public static IEnumerable<T> Yield<T>(this T singleElement) {
yield return singleElement;
}
public static IEnumerable<T> YieldIfNotNull<T>(this T singleElement) {
if(singleElement != null)
yield return singleElement;
}
public static IEnumerable<string> YieldIfNotEmpty(this string singleElement) {
if(!string.IsNullOrEmpty(singleElement))
yield return singleElement;
}
public static T[] YieldToArray<T>(this T singleElement) {
return new[] { singleElement };
}
public static T[] YieldIfNotNullToArray<T>(this T singleElement) {
return singleElement == null ? EmptyArray<T>.Instance : new[] { singleElement };
}
public static string[] YieldIfNotEmptyToArray(this string singleElement) {
return string.IsNullOrEmpty(singleElement) ? EmptyArray<string>.Instance : new[] { singleElement };
}
public static void ForEach<T>(this IEnumerable<T> source, Func<T, int, IEnumerable<T>> getItems, Action<T, int> action) {
source.ForEachCore(getItems, action, 0);
}
static void ForEachCore<T>(this IEnumerable<T> source, Func<T, int, IEnumerable<T>> getItems, Action<T, int> action, int level) {
source.ForEach(x => action(x, level));
if(source.Any())
source.SelectMany(x => getItems(x, level + 1)).ForEachCore(getItems, action, level + 1);
}
public static IEnumerable<T> Flatten<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> getItems) {
return source.Flatten((x, _) => getItems(x));
}
struct EnumeratorAndLevel<T> {
public readonly IEnumerator<T> En;
public readonly int Level;
public EnumeratorAndLevel(IEnumerator<T> en, int level) {
En = en;
Level = level;
}
}
public static IEnumerable<T> Flatten<T>(this IEnumerable<T> source, Func<T, int, IEnumerable<T>> getItems) {
var stack = new Stack<EnumeratorAndLevel<T>>();
try {
var root = source.GetEnumerator();
if(root.MoveNext())
stack.Push(new EnumeratorAndLevel<T>(root, 0));
while(stack.Count != 0) {
var top = stack.Peek();
var current = top.En.Current;
yield return current;
if(!top.En.MoveNext())
stack.Pop();
var children = getItems(current, top.Level)?.GetEnumerator();
if(children?.MoveNext() == true) {
stack.Push(new EnumeratorAndLevel<T>(children, top.Level + 1));
}
}
} finally {
foreach(var enumAndLevel in stack)
enumAndLevel.En.Dispose();
}
}
public static T MinByLast<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector) where TKey : IComparable {
var comparer = Comparer<TKey>.Default;
return source.Aggregate((x, y) => comparer.Compare(keySelector(x), keySelector(y)) < 0 ? x : y);
}
public static T MinBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector) where TKey : IComparable {
var comparer = Comparer<TKey>.Default;
return source.Aggregate((x, y) => comparer.Compare(keySelector(x), keySelector(y)) <= 0 ? x : y);
}
public static T MaxBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector) where TKey : IComparable {
var comparer = Comparer<TKey>.Default;
return source.Aggregate((x, y) => comparer.Compare(keySelector(x), keySelector(y)) >= 0 ? x : y);
}
public static IEnumerable<T> InsertDelimiter<T>(this IEnumerable<T> source, T delimiter) {
using(var en = source.GetEnumerator()) {
if(en.MoveNext())
yield return en.Current;
while(en.MoveNext()) {
yield return delimiter;
yield return en.Current;
}
}
}
public static string ConcatStringsWithDelimiter(this IEnumerable<string> source, string delimiter) {
return string.Join(delimiter, source);
}
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, ListSortDirection sortDirection) {
return sortDirection == ListSortDirection.Ascending ?
source.OrderBy(keySelector) :
source.OrderByDescending(keySelector);
}
public static Func<T> Memoize<T>(this Func<T> getValue) {
var lazy = new Lazy<T>(getValue);
return () => lazy.Value;
}
public static Func<TIn, TOut> Memoize<TIn, TOut>(this Func<TIn, TOut> getValue) {
var dict = new Dictionary<TIn, TOut>();
return x => dict.GetOrAdd(x, getValue);
}
public static T WithReturnValue<T>(this Func<Lazy<T>, T> func) {
var t = default(T);
var tHasValue = false;
t = func(new Lazy<T>(() => {
if(!tHasValue)
throw new InvalidOperationException("Fix");
return t;
}));
tHasValue = true;
return t;
}
public static bool AllEqual<T>(this IEnumerable<T> source, Func<T, T, bool> comparer = null) {
if(!source.Any())
return true;
comparer = comparer ?? ((x, y) => EqualityComparer<T>.Default.Equals(x, y));
var first = source.First();
return source.Skip(1).All(x => comparer(x, first));
}
public static Action CombineActions(params Action[] actions) {
return () => actions.ForEach(x => x());
}
public static Action<T> CombineActions<T>(params Action<T>[] actions) {
return p => actions.ForEach(x => x(p));
}
public static Action<T1, T2> CombineActions<T1, T2>(params Action<T1, T2>[] actions) {
return (p1, p2) => actions.ForEach(x => x(p1, p2));
}
public static ReadOnlyObservableCollection<T> ToReadOnlyObservableCollection<T>(this IEnumerable<T> source) {
return new ReadOnlyObservableCollection<T>(source.ToObservableCollection());
}
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source) {
return new ObservableCollection<T>(source);
}
public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> source) {
return source.ToList().AsReadOnly();
}
public static IEnumerable<T> InsertDelimiter<T>(this IEnumerable<T> source, Func<T> delimiter) {
var firstItem = true;
foreach(var item in source) {
if(firstItem)
firstItem = false;
else
yield return delimiter();
yield return item;
}
}
}
public
sealed class TaskLinq<T> {
public TaskLinq(Task<T> task, TaskLinq.Chain chain) {
Task = task;
Chain = chain;
}
internal readonly Task<T> Task;
internal readonly TaskLinq.Chain Chain;
}
public
static class TaskLinq {
public static TaskLinq<T> Linq<T>(this Task<T> task, TaskScheduler scheduler = null) {
return task.Linq(new Chain(scheduler));
}
public static TaskLinq<T> Linq<T>(this Task<T> task, Chain chain) {
return new TaskLinq<T>(task, chain);
}
public sealed class Chain {
readonly RunFuture RunFuture = new RunFuture();
public readonly SchedulerFuture SchedulerFuture;
public Chain(SchedulerFuture schedulerFuture, Action run = null) {
SchedulerFuture = schedulerFuture;
RunFuture.Continue(run);
}
public Chain(TaskScheduler scheduler = null, Action run = null) : this(new SchedulerFuture(scheduler), run) { }
public void Continue(Chain chain) {
SchedulerFuture.Continue(chain.SchedulerFuture.Run);
RunFuture.Continue(chain.RunFuture.Run);
}
public void Run(TaskScheduler scheduler) {
if(scheduler == null)
throw new ArgumentNullException("scheduler");
SchedulerFuture.Run(scheduler);
RunFuture.Run();
}
}
sealed class RunFuture {
readonly object sync = new object();
Action @continue;
bool ran;
public void Continue(Action action) {
if(!ran) {
lock(sync) {
if(!ran) {
@continue += action;
return;
}
}
}
action?.Invoke();
}
public void Run() {
Action action;
if(!ran) {
lock(sync) {
if(!ran) {
ran = true;
action = @continue;
@continue = null;
} else {
return;
}
}
} else {
return;
}
action?.Invoke();
}
}
public sealed class SchedulerFuture {
readonly object sync = new object();
#if DEBUG
static int nextId = 0;
public readonly int Id = Interlocked.Increment(ref nextId);
#endif
TaskScheduler scheduler;
Action<TaskScheduler> @continue;
public SchedulerFuture(TaskScheduler scheduler = null) {
this.scheduler = scheduler;
}
public void Continue(Action<TaskScheduler> action) {
if(scheduler == null) {
lock(sync) {
if(scheduler == null) {
@continue += action;
return;
}
}
}
action(scheduler);
}
public void Run(TaskScheduler scheduler) {
if(scheduler == null)
throw new ArgumentNullException("scheduler");
Action<TaskScheduler> action;
if(this.scheduler == null) {
lock(sync) {
if(this.scheduler == null) {
this.scheduler = scheduler;
action = @continue;
@continue = null;
} else {
CheckScheduler(scheduler);
return;
}
}
} else {
CheckScheduler(scheduler);
return;
}
action?.Invoke(this.scheduler);
}
void CheckScheduler(TaskScheduler scheduler) {
if((this.scheduler == TaskScheduler.Default) == (scheduler == TaskScheduler.Default)) return;
int id;
#if DEBUG
id = Id;
#else
id = 0;
#endif
throw new InvalidOperationException("SchedulerFuture: " + id + " " + this.scheduler.Id + " " + scheduler.Id + " " + TaskScheduler.Default.Id);
}
}
public static SynchronizationContext RethrowAsyncExceptionsContext = null;
public static TaskLinq<UnitT> LongRunning() { return StartNew(TaskCreationOptions.LongRunning); }
public static TaskLinq<UnitT> ThreadPool() { return StartNew(TaskCreationOptions.None); }
#if DEBUG
internal static int StartNewThreadId;
#endif
static TaskLinq<UnitT> StartNew(TaskCreationOptions creationOptions) {
var task = new Task<UnitT>(() => {
#if DEBUG
StartNewThreadId = Thread.CurrentThread.ManagedThreadId;
#endif
return default(UnitT);
}, CancellationToken.None, creationOptions);
var chain = new Chain(TaskScheduler.Default, () => task.Start(TaskScheduler.Default));
return task.Linq(chain);
}
public static TaskLinq<UnitT> Wait(Func<Action, Action> subscribe, Func<bool> ready, TaskScheduler scheduler = null) {
return Wait(subscribe, ready, new Chain(scheduler));
}
public static TaskLinq<UnitT> Wait(Func<Action, Action> subscribe, Func<bool> ready, Chain chain) {
return ready() ? default(UnitT).Promise() : On(subscribe, chain);
}
public static TaskLinq<UnitT> On(Func<Action, Action> subscribe, TaskScheduler scheduler = null) {
return On(subscribe, new Chain(scheduler));
}
public static TaskLinq<UnitT> On(Func<Action, Action> subscribe, Chain chain) {
return On<UnitT>(x => subscribe(() => x(default(UnitT))), chain);
}
public static TaskLinq<T> On<T>(Func<Action<T>, Action> subscribe, TaskScheduler scheduler = null) {
return On<T>(subscribe, new Chain(scheduler));
}
public static TaskLinq<T> On<T>(Func<Action<T>, Action> subscribe, Chain chain) {
var taskSource = new TaskCompletionSource<T>();
LinqExtensions.WithReturnValue<Action>(unsubscribe => subscribe(x => {
unsubscribe.Value();
taskSource.SetResult(x);
}));
return taskSource.Task.Linq(chain);
}
static Task<T> Run<T>(this TaskLinq<T> task, Chain chain) {
chain.Continue(task.Chain);
return task.Task;
}
static TaskScheduler InvalidScheduler() {
throw new InvalidOperationException("TaskScheduler.Current == TaskScheduler.Default && SynchronizationContext.Current == null");
}
public static Task<T> Schedule<T>(this TaskLinq<T> task, TaskScheduler scheduler = null) {
scheduler = scheduler ?? (TaskScheduler.Current != TaskScheduler.Default ? TaskScheduler.Current : SynchronizationContext.Current == null ? InvalidScheduler() : TaskScheduler.FromCurrentSynchronizationContext());
return task.Schedule(new SchedulerFuture(scheduler));
}
public static Task<T> Schedule<T>(this TaskLinq<T> task, SchedulerFuture schedulerFuture) {
schedulerFuture.Continue(task.Chain.Run);
return task.Task;
}
public static Task<T> Future<T>(this T value) {
var taskSource = new TaskCompletionSource<T>();
taskSource.SetResult(value);
return taskSource.Task;
}
public static Task<T> FutureException<T>(this Exception e) {
var taskSource = new TaskCompletionSource<T>();
taskSource.SetException(e);
return taskSource.Task;
}
public static Task<T> FutureCanceled<T>() {
var taskSource = new TaskCompletionSource<T>();
taskSource.SetCanceled();
return taskSource.Task;
}
public static TaskLinq<T> Promise<T>(this T value, Chain chain) { return value.Future().Linq(chain); }
public static TaskLinq<T> PromiseException<T>(this Exception e, Chain chain) { return e.FutureException<T>().Linq(chain); }
public static TaskLinq<T> PromiseCanceled<T>(Chain chain) { return FutureCanceled<T>().Linq(chain); }
public static TaskLinq<T> Promise<T>(this T value, TaskScheduler scheduler = null) { return value.Promise(new Chain(scheduler)); }
public static TaskLinq<T> PromiseException<T>(this Exception e, TaskScheduler scheduler = null) { return e.PromiseException<T>(new Chain(scheduler)); }
public static TaskLinq<T> PromiseCanceled<T>(TaskScheduler scheduler = null) { return PromiseCanceled<T>(new Chain(scheduler)); }
public static TaskLinq<T> Where<T>(this TaskLinq<T> task, Func<T, bool> predicate) {
var chain = task.Chain;
var taskSource = new TaskCompletionSource<T>();
taskSource.SetResultFromTask(chain.SchedulerFuture, task.Task, (ts, taskResult) => {
ts.SetResultSafe(() => predicate(taskResult), (ts_, predicateResult) => {
if(predicateResult)
ts_.SetResult(taskResult);
else
ts_.SetCanceled();
});
});
return taskSource.Task.Linq(chain);
}
public static TaskLinq<UnitT> Where(this TaskLinq<UnitT> task, Func<bool> predicate) {
return task.Where(_ => predicate());
}
public static TaskLinq<TR> Select<TI, TR>(this TaskLinq<TI> task, Func<TI, TR> selector) {
var chain = task.Chain;
var taskSource = new TaskCompletionSource<TR>();
taskSource.SetResultFromTask(chain.SchedulerFuture, task.Task, (ts, taskResult) => ts.SetResultSafe(() => selector(taskResult)));
return taskSource.Task.Linq(chain);
}
public static TaskLinq<UnitT> Select<TI>(this TaskLinq<TI> task, Action<TI> selector) {
return task.Select(x => { selector(x); return default(UnitT); });
}
public static TaskLinq<TR> Select<TR>(this TaskLinq<UnitT> task, Func<TR> selector) {
return task.Select(_ => selector());
}
public static TaskLinq<T> Select<T>(this TaskLinq<T> task, Action selector) {
return task.Select(x => { selector(); return x; });
}
public static TaskLinq<TR> SelectMany<TI, TR>(this TaskLinq<TI> task, Func<TI, TaskLinq<TR>> selector) {
return task.SelectMany(selector, (_, x) => x);
}
public static TaskLinq<TR> SelectMany<TR>(this TaskLinq<UnitT> task, Func<TaskLinq<TR>> selector) {
return task.SelectMany(_ => selector());
}
public static TaskLinq<T> SelectUnit<T>(this TaskLinq<T> task, Func<TaskLinq<UnitT>> selector) {
return task.SelectMany(x => selector().Select(() => x));
}
public static TaskLinq<TR> SelectMany<TI, TC, TR>(this TaskLinq<TI> task, Func<TI, TaskLinq<TC>> selector, Func<TI, TC, TR> projector) {
var chain = task.Chain;
var taskSource = new TaskCompletionSource<TR>();
taskSource.SetResultFromTask(chain.SchedulerFuture, task.Task, (ts, taskResult) => ts.SetResultFromTaskSafe(chain.SchedulerFuture, () => selector(taskResult).Run(chain), (ts_, selectorResult) => ts_.SetResultSafe(() => projector(taskResult, selectorResult))));
return taskSource.Task.Linq(chain);
}
public static Task Finish<T>(this Task<T> task) {
return task.ContinueWith(t => {
if(t.IsFaulted)
RethrowAsyncExceptionsContext.Do(x => x.Post(_ => { throw new AggregateException(t.Exception.InnerExceptions); }, default(UnitT)));
return default(UnitT);
}, TaskContinuationOptions.ExecuteSynchronously);
}
public static Task Execute(this TaskLinq<UnitT> task, Action action, TaskScheduler scheduler = null) {
return task.Execute(_ => action(), scheduler);
}
public static Task Execute(this TaskLinq<UnitT> task, Action action, SchedulerFuture schedulerFuture) {
return task.Execute(_ => action(), schedulerFuture);
}
public static Task Execute<T>(this TaskLinq<T> task, Action<T> action, TaskScheduler scheduler = null) {
return task.Select(r => { action(r); return r; }).Schedule(scheduler).Finish();
}
public static Task Execute<T>(this TaskLinq<T> task, Action<T> action, SchedulerFuture schedulerFuture) {
return task.Select(r => { action(r); return r; }).Schedule(schedulerFuture).Finish();
}
static void SetResultFromTask<T>(this TaskCompletionSource<T> taskSource, SchedulerFuture continueWithScheduler, Task<T> task, Action<TaskCompletionSource<T>> setCanceledAction = null, Action<TaskCompletionSource<T>, Exception> setExceptionAction = null) {
taskSource.SetResultFromTask(continueWithScheduler, task, (ts, taskResult) => ts.SetResult(taskResult), setCanceledAction, setExceptionAction);
}
static void SetResultFromTask<TI, TR>(this TaskCompletionSource<TR> taskSource, SchedulerFuture continueWithScheduler, Task<TI> task, Action<TaskCompletionSource<TR>, TI> setResultAction, Action<TaskCompletionSource<TR>> setCanceledAction = null, Action<TaskCompletionSource<TR>, Exception> setExceptionAction = null) {
setCanceledAction = setCanceledAction ?? (t => t.SetCanceled());
setExceptionAction = setExceptionAction ?? ((t, e) => t.SetException(e));
continueWithScheduler.Continue(scheduler => {
task.ContinueWith(t => {
if(t.IsCanceled)
setCanceledAction(taskSource);
else if(t.IsFaulted)
setExceptionAction(taskSource, t.Exception.InnerException);
else
setResultAction(taskSource, t.Result);
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
});
}
static void SetResultFromTaskSafe<T>(this TaskCompletionSource<T> taskSource, SchedulerFuture continueWithScheduler, Func<Task<T>> getTask, Action<TaskCompletionSource<T>> setCanceledAction = null, Action<TaskCompletionSource<T>, Exception> setExceptionAction = null) {
taskSource.SetResultFromTaskSafe(continueWithScheduler, getTask, (ts, taskResult) => ts.SetResult(taskResult), setCanceledAction, setExceptionAction);
}
static void SetResultFromTaskSafe<TI, TR>(this TaskCompletionSource<TR> taskSource, SchedulerFuture continueWithScheduler, Func<Task<TI>> getTask, Action<TaskCompletionSource<TR>, TI> setResultAction, Action<TaskCompletionSource<TR>> setCanceledAction = null, Action<TaskCompletionSource<TR>, Exception> setExceptionAction = null) {
Task<TI> task;
try {
task = getTask();
} catch(Exception e) {
taskSource.SetException(e);
return;
}
taskSource.SetResultFromTask(continueWithScheduler, task, setResultAction, setCanceledAction, setExceptionAction);
}
public static TaskLinq<T> IfException<T>(this TaskLinq<T> task, Func<Exception, TaskLinq<T>> handler) {
var chain = task.Chain;
var result = new TaskCompletionSource<T>();
result.SetResultFromTask(chain.SchedulerFuture, task.Task, setExceptionAction: (r, e) => r.SetResultFromTaskSafe(chain.SchedulerFuture, () => handler(e).Run(chain)));
return result.Task.Linq(chain);
}
public static TaskLinq<T> IfException<T>(this TaskLinq<T> task, Func<Exception, T> handler) {
var chain = task.Chain;
var result = new TaskCompletionSource<T>();
result.SetResultFromTask(chain.SchedulerFuture, task.Task, setExceptionAction: (r, e) => r.SetResultSafe(() => handler(e)));
return result.Task.Linq(chain);
}
public static TaskLinq<T> MapException<T>(this TaskLinq<T> task, Func<Exception, Exception> transform) {
var chain = task.Chain;
var result = new TaskCompletionSource<T>();
result.SetResultFromTask(chain.SchedulerFuture, task.Task, setExceptionAction: (r, e) => r.SetExceptionSafe(() => transform(e)));
return result.Task.Linq(chain);
}
public static TaskLinq<T> IfCanceled<T>(this TaskLinq<T> task, Func<Task<T>> handler) {
var chain = task.Chain;
var result = new TaskCompletionSource<T>();
result.SetResultFromTask(chain.SchedulerFuture, task.Task, setCanceledAction: r => r.SetResultFromTaskSafe(chain.SchedulerFuture, handler));
return result.Task.Linq(chain);
}
public static TaskLinq<T> IfCanceled<T>(this TaskLinq<T> task, Func<T> handler) {
var chain = task.Chain;
var result = new TaskCompletionSource<T>();
result.SetResultFromTask(chain.SchedulerFuture, task.Task, setCanceledAction: r => r.SetResultSafe(handler));
return result.Task.Linq(chain);
}
static void SetExceptionSafe<T>(this TaskCompletionSource<T> taskSource, Func<Exception> getException) {
taskSource.SetResultSafe(() => {
var e = getException();
if(e == null)
throw new InvalidOperationException("getException() == null");
return e;
}, (ts, result) => ts.SetException(result));
}
static void SetResultSafe<T>(this TaskCompletionSource<T> taskSource, Func<T> getResult) {
taskSource.SetResultSafe(getResult, (ts, result) => ts.SetResult(result));
}
static void SetResultSafe<TI, TR>(this TaskCompletionSource<TR> taskSource, Func<TI> getResult, Action<TaskCompletionSource<TR>, TI> setResultAction) {
TI result;
Exception exception;
try {
result = getResult();
exception = null;
} catch(Exception e) {
result = default(TI);
exception = e;
}
if(exception != null)
taskSource.SetException(exception);
else
setResultAction(taskSource, result);
}
public static TaskLinq<T> WithDefaultScheduler<T>(Func<TaskLinq<T>> action) {
if(TaskScheduler.Current == TaskScheduler.Default)
return action();
var synchronizationContext = SynchronizationContext.Current;
if(synchronizationContext == null)
throw new InvalidOperationException("SynchronizationContext.Current == null");
var linqScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var threadId = Thread.CurrentThread.ManagedThreadId;
var continueTask = new TaskCompletionSource<TaskLinq<T>>();
var startTask = new TaskCompletionSource<UnitT>();
startTask.SetResult(default(UnitT));
startTask.Task.ContinueWith(_ => {
if(Thread.CurrentThread.ManagedThreadId == threadId)
SetResultSafe(continueTask, action);
else
synchronizationContext.Post(__ => SetResultSafe(continueTask, action), default(UnitT));
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
return continueTask.Task.Linq(linqScheduler).SelectMany(x => x);
}
}
}
| |
/*
Copyright (c) 2015, Robert R. Khalikov
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.
*/
class MyFileFilter : WcLib.FileFilter
{
public enum Mode
{
Delete, Move, Copy, Skip
}
public void Run( string inputDir, string outputDir, WcLib.PatternList patternList, Mode mode, string logCategory = "" )
{
m_mode = mode;
m_logCategory = logCategory.Length > 0 ? "WcCleaner-" + logCategory : "WcCleaner";
m_inputDir = inputDir;
m_outputDir = outputDir;
Run( inputDir, patternList );
}
protected override void ProcessFile( string file, WcLib.FileState fileState )
{
if ( fileState == WcLib.FileState.Selected )
{
WcLib.Log.WriteLine( m_logCategory, file );
if ( m_mode != Mode.Skip )
{
string outputFileName = null;
if ( m_mode == Mode.Move || m_mode == Mode.Copy )
{
string relativeFileName = file.Substring( m_inputDir.Length );
if ( relativeFileName.StartsWith( new string( System.IO.Path.DirectorySeparatorChar, 1 ) ) ||
relativeFileName.StartsWith( new string( System.IO.Path.AltDirectorySeparatorChar, 1 ) ) )
{
relativeFileName = relativeFileName.Substring( 1 );
}
outputFileName = System.IO.Path.Combine( m_outputDir, relativeFileName );
string outputDirectory = System.IO.Path.GetDirectoryName( outputFileName );
if ( !System.IO.Directory.Exists( outputDirectory ) )
{
System.IO.Directory.CreateDirectory( outputDirectory );
}
WcLib.Log.WriteLine( m_logCategory + "-Output", outputFileName );
}
try
{
switch ( m_mode )
{
case Mode.Delete:
{
System.IO.File.Delete( file );
break;
}
case Mode.Move:
{
System.IO.File.Move( file, outputFileName );
break;
}
case Mode.Copy:
{
System.IO.File.Copy( file, outputFileName );
break;
}
}
}
catch ( System.Exception e )
{
WcLib.Log.WriteLine( m_logCategory + "-Errors", e.ToString() );
}
}
}
}
protected override void LeaveDirectory( string directory )
{
bool isEmpty = true;
foreach ( string s in System.IO.Directory.GetFileSystemEntries( directory ) )
{
isEmpty = false;
break;
}
if ( isEmpty )
{
WcLib.Log.WriteLine( m_logCategory, directory );
if ( m_mode != Mode.Skip )
{
try
{
System.IO.Directory.Delete( directory );
}
catch ( System.Exception e )
{
WcLib.Log.WriteLine( m_logCategory + "-Errors", e.ToString() );
}
}
}
}
Mode m_mode;
string m_logCategory;
string m_inputDir;
string m_outputDir;
}
class MyLogManager : WcLib.LogManager, System.IDisposable
{
protected override System.IO.StreamWriter GetWriter( string category )
{
if ( !m_writers.ContainsKey( category ) )
{
m_writers.Add( category, new System.IO.StreamWriter( category + ".log" ) );
}
return m_writers[ category ];
}
public void Dispose()
{
foreach ( var writer in m_writers.Values )
{
writer.Close();
writer.Dispose();
}
m_writers.Clear();
}
System.Collections.Generic.Dictionary< string, System.IO.StreamWriter > m_writers = new System.Collections.Generic.Dictionary< string, System.IO.StreamWriter > ();
}
static class Program
{
static string errorLogCategory = "WcCleaner-Errors";
static void Main( string[] args )
{
using ( var logManager = new MyLogManager() )
{
WcLib.Log.SetManager( logManager );
try
{
RunCleaner( args );
}
catch ( System.Exception e )
{
WcLib.Log.WriteLine( errorLogCategory, e.ToString() );
}
}
}
static void RunCleaner( string[] args )
{
string argInputDir = "";
string argOutputDir = "";
string argPatternFile = "";
string argCategory = "";
bool argLogOnly = false;
bool argAuto = false;
MyFileFilter.Mode argMode = MyFileFilter.Mode.Delete;
System.Collections.Generic.List< string > argDefs = new System.Collections.Generic.List< string > ();
foreach ( string arg in args )
{
string lowercaseArg = arg.ToLower();
if ( lowercaseArg.StartsWith( "-dir=" ) ) argInputDir = System.IO.Path.GetFullPath( arg.Substring( 5 ) );
else if ( lowercaseArg.StartsWith( "-pattern=" ) ) argPatternFile = arg.Substring( 9 );
else if ( lowercaseArg.StartsWith( "-logonly" ) ) argLogOnly = true;
else if ( lowercaseArg.StartsWith( "-auto" ) ) argAuto = true;
else if ( lowercaseArg.StartsWith( "-category=" ) ) argCategory = arg.Substring( 10 );
else if ( lowercaseArg.StartsWith( "-def=" ) )
{
string[] defs = arg.Substring( 5 ).Split( new char[] { '+' }, System.StringSplitOptions.RemoveEmptyEntries );
if ( defs != null )
{
argDefs.AddRange( defs );
}
}
else if ( lowercaseArg.StartsWith( "-moveto=" ) )
{
argOutputDir = System.IO.Path.GetFullPath( arg.Substring( 8 ) );
argMode = MyFileFilter.Mode.Move;
}
else if ( lowercaseArg.StartsWith( "-copyto=" ) )
{
argOutputDir = System.IO.Path.GetFullPath( arg.Substring( 8 ) );
argMode = MyFileFilter.Mode.Copy;
}
}
if ( argCategory.Length > 0 )
{
errorLogCategory = "WcCleaner-" + argCategory + "-Errors";
}
if ( argLogOnly )
{
argMode = MyFileFilter.Mode.Skip;
}
if ( !ValidateInput( argInputDir, argPatternFile ) )
return;
WcLib.PatternList patternList = new WcLib.PatternList( argPatternFile, argDefs.ToArray() );
if ( argMode == MyFileFilter.Mode.Delete && !argAuto )
{
if ( !ConfirmFileDeletion( argInputDir, patternList.SourceFileName ) )
return;
}
new MyFileFilter().Run( argInputDir, argOutputDir, patternList, argMode, argCategory );
}
static bool ValidateInput( string inputDir, string patternFile )
{
if ( inputDir.Length < 1 )
{
System.Console.WriteLine( "ERROR: Input directory is not specified!" );
return false;
}
if ( !System.IO.Directory.Exists( inputDir ) )
{
System.Console.WriteLine( "ERROR: Input directory '{0}' doesn't exist!", inputDir );
return false;
}
if ( patternFile.Length < 1 )
{
System.Console.WriteLine( "ERROR: Pattern file is not specified!" );
return false;
}
return true;
}
static bool ConfirmFileDeletion( string inputDir, string patternFile )
{
System.Console.WriteLine( "WARNING: Do you confirm DELETION of files in '{0}' based on patterns in '{1}'? (Press Y or N)", inputDir, patternFile );
while ( true )
{
System.ConsoleKey pressedKey = System.Console.ReadKey( true ).Key;
if ( pressedKey == System.ConsoleKey.N )
{
System.Console.WriteLine( "Operation cancelled." );
return false;
}
if ( pressedKey == System.ConsoleKey.Y )
{
System.Console.WriteLine( "Running..." );
return true;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Castle.Facilities.NHibernateIntegration;
using Castle.Services.Transaction;
using Cuyahoga.Core.Util;
using NHibernate;
using NHibernate.Criterion;
using Cuyahoga.Core.Domain;
namespace Cuyahoga.Core.DataAccess
{
/// <summary>
/// Provides data access for user-related components.
/// </summary>
[Transactional]
public class UserDao : IUserDao
{
private ISessionManager _sessionManager;
private ICommonDao _commonDao;
/// <summary>
/// Default constructor;
/// </summary>
/// <param name="sessionManager"></param>
public UserDao(ISessionManager sessionManager, ICommonDao commonDao)
{
this._sessionManager = sessionManager;
this._commonDao = commonDao;
}
#region IUserDao Members
public User GetUserByUsernameAndPassword(string username, string password)
{
ISession session = this._sessionManager.OpenSession();
ICriteria crit = session.CreateCriteria(typeof(User));
crit.Add(Expression.Eq("UserName", username));
crit.Add(Expression.Eq("Password", password));
IList results = crit.List();
if (results.Count == 1)
{
return (User)results[0];
}
else if (results.Count > 1)
{
throw new Exception(String.Format("Multiple users found with the give username and password. Something is pretty wrong here"));
}
else
{
return null;
}
}
public User GetUserByUsernameAndEmail(string username, string email)
{
ISession session = this._sessionManager.OpenSession();
ICriteria crit = session.CreateCriteria(typeof(User));
crit.Add(Expression.Eq("UserName", username));
crit.Add(Expression.Eq("Email", email));
IList results = crit.List();
if (results.Count == 1)
{
return (User)results[0];
}
else
{
return null;
}
}
public IList FindUsersByUsername(string searchString)
{
if (searchString.Length > 0)
{
ISession session = this._sessionManager.OpenSession();
string hql = "from User u where u.UserName like ? order by u.UserName ";
return session.Find(hql, searchString + "%", NHibernateUtil.String);
}
else
{
return this._commonDao.GetAll(typeof(User), "UserName");
}
}
public IList<User> FindUsers(string username, int? roleId, bool? isActive, int? siteId, int pageSize, int pageNumber, out int totalCount)
{
ISession session = this._sessionManager.OpenSession();
ICriteria userCriteria = session.CreateCriteria(typeof(User));
ICriteria countCriteria = session.CreateCriteria(typeof(User), "userCount");
if (!String.IsNullOrEmpty(username))
{
userCriteria.Add(Expression.InsensitiveLike("UserName", username, MatchMode.Start));
countCriteria.Add(Expression.InsensitiveLike("UserName", username, MatchMode.Start));
}
if (roleId.HasValue)
{
userCriteria.CreateCriteria("Roles", "r1").Add(Expression.Eq("r1.Id", roleId));
countCriteria.CreateCriteria("Roles", "r1").Add(Expression.Eq("r1.Id", roleId));
}
if (isActive.HasValue)
{
userCriteria.Add(Expression.Eq("IsActive", isActive));
countCriteria.Add(Expression.Eq("IsActive", isActive));
}
// Filter users that are related to the given site. Don't do this when already filtering on a role
if (siteId.HasValue && ! roleId.HasValue)
{
// We need two subqueries to traverse two many-many relations. Directly creating
// criteria on the collection properties results in a cartesian product.
DetachedCriteria roleIdsForSite = DetachedCriteria.For(typeof (Role))
.SetProjection(Projections.Property("Id"))
.CreateCriteria("Sites", "site")
.Add(Expression.Eq("site.Id", siteId.Value));
DetachedCriteria userIdsForRoles = DetachedCriteria.For(typeof(User))
.SetProjection(Projections.Distinct(Projections.Property("Id")))
.CreateCriteria("Roles")
.Add(Subqueries.PropertyIn("Id", roleIdsForSite));
userCriteria.Add(Subqueries.PropertyIn("Id", userIdsForRoles));
countCriteria.Add(Subqueries.PropertyIn("Id", userIdsForRoles));
}
userCriteria.SetFirstResult((pageNumber - 1) * pageSize);
userCriteria.SetMaxResults(pageSize);
countCriteria.SetProjection(Projections.RowCount());
totalCount = (int) countCriteria.UniqueResult();
return userCriteria.List<User>();
}
public IList<Section> GetViewableSectionsByUser(User user)
{
string hql = "select s from User u join u.Roles as r, Section s join s.SectionPermissions sp " +
"where u.Id = :userId and r.Id = sp.Role.Id and sp.ViewAllowed = 1";
IQuery q = this._sessionManager.OpenSession().CreateQuery(hql);
q.SetInt32("userId", user.Id);
return q.List<Section>();
}
//TODO: check why this throws an ADO Exeption (NHibernate bug?)
//public IList<Section> GetViewableSectionsByRoles(IList<Role> roles)
//{
// string hql = "select s from Section s join s.SectionPermissions as sp where sp.Role in :roles and sp.ViewAllowed = 1";
// IQuery q = this._sessionManager.OpenSession().CreateQuery(hql);
// q.SetParameterList("roles", roles);
// return q.List<Section>();
//}
public IList<Section> GetViewableSectionsByAccessLevel(AccessLevel accessLevel)
{
int permission = (int)accessLevel;
string hql = "select s from Section s join s.SectionPermissions sp, Role r "+
"where r.PermissionLevel = :permission and r.Id = sp.Role.Id and sp.ViewAllowed = 1";
IQuery q = this._sessionManager.OpenSession().CreateQuery(hql);
q.SetInt32("permission", permission);
return q.List<Section>();
}
//public IList<Role> GetRolesByAccessLevel(AccessLevel accessLevel)
//{
// int permission = (int)accessLevel;
// string hql = "select r from Role r where r.PermissionLevel = :permission";
// IQuery q = this._sessionManager.OpenSession().CreateQuery(hql);
// q.SetInt32("permission", permission);
// return q.List<Role>();
//}
public IList<Role> GetRolesByRightName(string rightName)
{
string hql = "select r from Role r join r.Rights right where right.Name = :rightName";
IQuery q = this._sessionManager.OpenSession().CreateQuery(hql);
q.SetString("rightName", rightName);
return q.List<Role>();
}
public IList<Role> GetAllRolesBySite(Site site)
{
ISession session = this._sessionManager.OpenSession();
ICriteria crit = session.CreateCriteria(typeof (Role))
.AddOrder(Order.Asc("Name"))
.CreateCriteria("Sites")
.Add(Expression.Eq("Id", site.Id));
return crit.List<Role>();
}
[Transaction(TransactionMode.Requires)]
public void SaveOrUpdateUser(User user)
{
ISession session = this._sessionManager.OpenSession();
session.SaveOrUpdate(user);
}
[Transaction(TransactionMode.Requires)]
public void DeleteUser(User user)
{
ISession session = this._sessionManager.OpenSession();
session.Delete(user);
}
#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 Xunit;
namespace System.Diagnostics.TraceSourceTests
{
using Method = TestTraceListener.Method;
public class TraceClassTests : IDisposable
{
void IDisposable.Dispose()
{
TraceTestHelper.ResetState();
}
[Fact]
public void AutoFlushTest()
{
Trace.AutoFlush = false;
Assert.False(Trace.AutoFlush);
Trace.AutoFlush = true;
Assert.True(Trace.AutoFlush);
}
[Fact]
public void UseGlobalLockTest()
{
Trace.UseGlobalLock = true;
Assert.True(Trace.UseGlobalLock);
Trace.UseGlobalLock = false;
Assert.False(Trace.UseGlobalLock);
}
[Fact]
public void RefreshTest()
{
Trace.UseGlobalLock = true;
Assert.True(Trace.UseGlobalLock);
// NOTE: Refresh does not reset to default config values
Trace.Refresh();
Assert.True(Trace.UseGlobalLock);
}
[Theory]
[InlineData(1, 1)]
[InlineData(2, 2)]
[InlineData(-2, 0)]
public void IndentLevelTest(int indent, int expected)
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new DefaultTraceListener());
Trace.IndentLevel = indent;
Assert.Equal(expected, Trace.IndentLevel);
foreach (TraceListener listener in Trace.Listeners)
{
Assert.Equal(expected, listener.IndentLevel);
}
}
[Theory]
[InlineData(1, 1)]
[InlineData(2, 2)]
[InlineData(-2, 0)]
public void IndentSizeTest(int indent, int expected)
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new DefaultTraceListener());
Trace.IndentSize = indent;
Assert.Equal(expected, Trace.IndentSize);
foreach (TraceListener listener in Trace.Listeners)
{
Assert.Equal(expected, listener.IndentSize);
}
}
[Fact]
public void FlushTest()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Clear();
Trace.AutoFlush = false;
Trace.Listeners.Add(listener);
Trace.Write("Test");
Assert.DoesNotContain("Test", listener.Output);
Trace.Flush();
Assert.Contains("Test", listener.Output);
}
[Fact]
public void CloseTest()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.Close();
Assert.Equal(1, listener.GetCallCount(Method.Dispose));
}
[Fact]
public void Assert1Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.Assert(true);
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(0, listener.GetCallCount(Method.Fail));
Trace.Assert(false);
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(1, listener.GetCallCount(Method.Fail));
}
[Fact]
public void Assert2Test()
{
var listener = new TestTraceListener();
var text = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.Listeners.Add(text);
Trace.Assert(true, "Message");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(0, listener.GetCallCount(Method.Fail));
text.Flush();
Assert.DoesNotContain("Message", text.Output);
Trace.Assert(false, "Message");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(1, listener.GetCallCount(Method.Fail));
text.Flush();
Assert.Contains("Message", text.Output);
}
[Fact]
public void Assert3Test()
{
var listener = new TestTraceListener();
var text = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.Listeners.Add(text);
Trace.Assert(true, "Message", "Detail");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(0, listener.GetCallCount(Method.Fail));
text.Flush();
Assert.DoesNotContain("Message", text.Output);
Trace.Assert(false, "Message", "Detail");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(1, listener.GetCallCount(Method.Fail));
text.Flush();
Assert.Contains("Message", text.Output);
Assert.Contains("Detail", text.Output);
}
[Fact]
public void WriteTest()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.Write("Message", "Category");
Trace.Flush();
Assert.Equal("Category: Message", listener.Output);
}
[Fact]
public void WriteObject1Test()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.Write((Object)"Text");
listener.Flush();
Assert.Equal("Text", listener.Output);
}
[Fact]
public void WriteObject2Test()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.Write((Object)"Message", "Category");
Trace.Flush();
Assert.Equal("Category: Message", listener.Output);
}
[Fact]
public void WriteLineObjectTest()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLine((Object)"Text");
listener.Flush();
Assert.Equal("Text" + Environment.NewLine, listener.Output);
}
[Fact]
public void WriteLine1Test()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLine("Message", "Category");
listener.Flush();
Assert.Equal("Category: Message" + Environment.NewLine, listener.Output);
}
[Fact]
public void WriteLine2Test()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLine((Object)"Message", "Category");
listener.Flush();
Assert.Equal("Category: Message" + Environment.NewLine, listener.Output);
}
[Fact]
public void WriteIf1Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteIf(false, (Object)"Message");
Assert.Equal(0, listener.GetCallCount(Method.Write));
Trace.WriteIf(true, (Object)"Message");
Assert.Equal(1, listener.GetCallCount(Method.Write));
}
[Fact]
public void WriteIf2Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteIf(false, "Message");
Assert.Equal(0, listener.GetCallCount(Method.Write));
Trace.WriteIf(true, "Message");
Assert.Equal(1, listener.GetCallCount(Method.Write));
}
[Fact]
public void WriteIf3Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteIf(false, (Object)"Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.Write));
Trace.WriteIf(true, (Object)"Message", "Category");
Assert.Equal(1, listener.GetCallCount(Method.Write));
}
[Fact]
public void WriteIf4Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteIf(false, "Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.Write));
Trace.WriteIf(true, "Message", "Category");
Assert.Equal(1, listener.GetCallCount(Method.Write));
}
[Fact]
public void WriteLineIf1Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLineIf(false, (Object)"Message");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Trace.WriteLineIf(true, (Object)"Message");
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void WriteLineIf2Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLineIf(false, "Message");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Trace.WriteLineIf(true, "Message");
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void WriteLineIf3Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLineIf(false, (Object)"Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Trace.WriteLineIf(true, (Object)"Message", "Category");
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void WriteLineIf4Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLineIf(false, "Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Trace.WriteLineIf(true, "Message", "Category");
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void FailTest()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.Fail("Text");
Assert.Equal(1, listener.GetCallCount(Method.Fail));
Trace.Fail("Text", "Detail");
Assert.Equal(2, listener.GetCallCount(Method.Fail));
}
[Fact]
public void TraceTest01()
{
var textTL = new TestTextTraceListener();
Trace.Listeners.Add(textTL);
Trace.IndentLevel = 0;
Trace.WriteLine("Message start.");
Trace.IndentSize = 2;
Trace.IndentLevel = 2;
Trace.Write("This message should be indented.");
Trace.TraceError("This error not be indented.");
Trace.TraceError("{0}", "This error is indendented");
Trace.TraceWarning("This warning is indented");
Trace.TraceWarning("{0}", "This warning is also indented");
Trace.TraceInformation("This information in indented");
Trace.TraceInformation("{0}", "This information is also indented");
Trace.IndentSize = 0;
Trace.IndentLevel = 0;
Trace.WriteLine("Message end.");
textTL.Flush();
String newLine = Environment.NewLine;
var expected =
String.Format(
"Message start." + newLine + " This message should be indented.{0} Error: 0 : This error not be indented." + newLine + " {0} Error: 0 : This error is indendented" + newLine + " {0} Warning: 0 : This warning is indented" + newLine + " {0} Warning: 0 : This warning is also indented" + newLine + " {0} Information: 0 : This information in indented" + newLine + " {0} Information: 0 : This information is also indented" + newLine + "Message end." + newLine + "",
"DEFAULT_APPNAME" //DEFAULT_APPNAME this a bug which needs to be fixed.
);
Assert.Equal(expected, textTL.Output);
}
[Fact]
public void TraceTest02()
{
var textTL = new TestTextTraceListener();
Trace.Listeners.Add(textTL);
Trace.IndentLevel = 0;
Trace.IndentSize = 2;
Trace.WriteLineIf(true, "Message start.");
Trace.Indent();
Trace.Indent();
Trace.WriteIf(true, "This message should be indented.");
Trace.WriteIf(false, "This message should be ignored.");
Trace.Indent();
Trace.WriteLine("This should not be indented.");
Trace.WriteLineIf(false, "This message will be ignored");
Trace.Fail("This failure is reported", "with a detailed message");
Trace.Assert(false);
Trace.Assert(false, "This assert is reported");
Trace.Assert(true, "This assert is not reported");
Trace.Unindent();
Trace.Unindent();
Trace.Unindent();
Trace.WriteLine("Message end.");
textTL.Flush();
String newLine = Environment.NewLine;
var expected = "Message start." + newLine + " This message should be indented.This should not be indented." + newLine + " Fail: This failure is reported with a detailed message" + newLine + " Fail: " + newLine + " Fail: This assert is reported" + newLine + "Message end." + newLine;
Assert.Equal(expected, textTL.Output);
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Reflection.Emit
{
// TypeNameBuilder is NOT thread safe NOR reliable
internal class TypeNameBuilder
{
internal enum Format
{
ToString,
FullName,
AssemblyQualifiedName,
}
#region QCalls
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr CreateTypeNameBuilder();
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void ReleaseTypeNameBuilder(IntPtr pAQN);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void OpenGenericArguments(IntPtr tnb);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void CloseGenericArguments(IntPtr tnb);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void OpenGenericArgument(IntPtr tnb);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void CloseGenericArgument(IntPtr tnb);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddName(IntPtr tnb, string name);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddPointer(IntPtr tnb);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddByRef(IntPtr tnb);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddSzArray(IntPtr tnb);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddArray(IntPtr tnb, int rank);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddAssemblySpec(IntPtr tnb, string assemblySpec);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void ToString(IntPtr tnb, StringHandleOnStack retString);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void Clear(IntPtr tnb);
#endregion
#region Static Members
// TypeNameBuilder is NOT thread safe NOR reliable
[System.Security.SecuritySafeCritical] // auto-generated
internal static string ToString(Type type, Format format)
{
if (format == Format.FullName || format == Format.AssemblyQualifiedName)
{
if (!type.IsGenericTypeDefinition && type.ContainsGenericParameters)
return null;
}
TypeNameBuilder tnb = new TypeNameBuilder(CreateTypeNameBuilder());
tnb.Clear();
tnb.ConstructAssemblyQualifiedNameWorker(type, format);
string toString = tnb.ToString();
tnb.Dispose();
return toString;
}
#endregion
#region Private Data Members
private IntPtr m_typeNameBuilder;
#endregion
#region Constructor
private TypeNameBuilder(IntPtr typeNameBuilder) { m_typeNameBuilder = typeNameBuilder; }
[System.Security.SecurityCritical] // auto-generated
internal void Dispose() { ReleaseTypeNameBuilder(m_typeNameBuilder); }
#endregion
#region private Members
[System.Security.SecurityCritical] // auto-generated
private void AddElementType(Type elementType)
{
if (elementType.HasElementType)
AddElementType(elementType.GetElementType());
if (elementType.IsPointer)
AddPointer();
else if (elementType.IsByRef)
AddByRef();
else if (elementType.IsSzArray)
AddSzArray();
else if (elementType.IsArray)
AddArray(elementType.GetArrayRank());
}
[System.Security.SecurityCritical] // auto-generated
private void ConstructAssemblyQualifiedNameWorker(Type type, Format format)
{
Type rootType = type;
while (rootType.HasElementType)
rootType = rootType.GetElementType();
// Append namespace + nesting + name
List<Type> nestings = new List<Type>();
for (Type t = rootType; t != null; t = t.IsGenericParameter ? null : t.DeclaringType)
nestings.Add(t);
for (int i = nestings.Count - 1; i >= 0; i--)
{
Type enclosingType = nestings[i];
string name = enclosingType.Name;
if (i == nestings.Count - 1 && enclosingType.Namespace != null && enclosingType.Namespace.Length != 0)
name = enclosingType.Namespace + "." + name;
AddName(name);
}
// Append generic arguments
if (rootType.IsGenericType && (!rootType.IsGenericTypeDefinition || format == Format.ToString))
{
Type[] genericArguments = rootType.GetGenericArguments();
OpenGenericArguments();
for (int i = 0; i < genericArguments.Length; i++)
{
Format genericArgumentsFormat = format == Format.FullName ? Format.AssemblyQualifiedName : format;
OpenGenericArgument();
ConstructAssemblyQualifiedNameWorker(genericArguments[i], genericArgumentsFormat);
CloseGenericArgument();
}
CloseGenericArguments();
}
// Append pointer, byRef and array qualifiers
AddElementType(type);
if (format == Format.AssemblyQualifiedName)
AddAssemblySpec(type.Module.Assembly.FullName);
}
[System.Security.SecurityCritical] // auto-generated
private void OpenGenericArguments() { OpenGenericArguments(m_typeNameBuilder); }
[System.Security.SecurityCritical] // auto-generated
private void CloseGenericArguments() { CloseGenericArguments(m_typeNameBuilder); }
[System.Security.SecurityCritical] // auto-generated
private void OpenGenericArgument() { OpenGenericArgument(m_typeNameBuilder); }
[System.Security.SecurityCritical] // auto-generated
private void CloseGenericArgument() { CloseGenericArgument(m_typeNameBuilder); }
[System.Security.SecurityCritical] // auto-generated
private void AddName(string name) { AddName(m_typeNameBuilder, name); }
[System.Security.SecurityCritical] // auto-generated
private void AddPointer() { AddPointer(m_typeNameBuilder); }
[System.Security.SecurityCritical] // auto-generated
private void AddByRef() { AddByRef(m_typeNameBuilder); }
[System.Security.SecurityCritical] // auto-generated
private void AddSzArray() { AddSzArray(m_typeNameBuilder); }
[System.Security.SecurityCritical] // auto-generated
private void AddArray(int rank) { AddArray(m_typeNameBuilder, rank); }
[System.Security.SecurityCritical] // auto-generated
private void AddAssemblySpec(string assemblySpec) { AddAssemblySpec(m_typeNameBuilder, assemblySpec); }
[System.Security.SecuritySafeCritical] // auto-generated
public override string ToString() { string ret = null; ToString(m_typeNameBuilder, JitHelpers.GetStringHandleOnStack(ref ret)); return ret; }
[System.Security.SecurityCritical] // auto-generated
private void Clear() { Clear(m_typeNameBuilder); }
#endregion
}
}
| |
//
// API.AI .NET SDK tests - client-side tests for API.AI
// =================================================
//
// Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
// https://www.api.ai
//
// ***********************************************************************************************************************
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//
// ***********************************************************************************************************************
using System;
using System.Linq;
using NUnit.Framework;
using ApiAiSDK;
using ApiAiSDK.Model;
using System.Collections.Generic;
namespace ApiAiSDK.Tests
{
[TestFixture]
public class AIDataServiceTests
{
private const string SUBSCRIPTION_KEY = "cb9693af-85ce-4fbf-844a-5563722fc27f";
private const string ACCESS_TOKEN = "3485a96fb27744db83e78b8c4bc9e7b7";
[Test]
public void TextRequestTest()
{
var dataService = CreateDataService();
var request = new AIRequest("Hello");
var response = dataService.Request(request);
Assert.IsNotNull(response);
Assert.AreEqual("greeting", response.Result.Action);
Assert.AreEqual("Hi! How are you?", response.Result.Fulfillment.Speech);
}
private AIDataService CreateDataService()
{
var config = new AIConfiguration(SUBSCRIPTION_KEY, ACCESS_TOKEN, SupportedLanguage.English);
var dataService = new AIDataService(config);
return dataService;
}
[Test]
public void DifferentAgentsTest()
{
var query = "I want pizza";
{
var dataService = CreateDataService();
var request = new AIRequest(query);
var response = dataService.Request(request);
Assert.IsNotNull(response.Result);
Assert.AreEqual("pizza", response.Result.Action);
}
{
var config = new AIConfiguration(SUBSCRIPTION_KEY, "968235e8e4954cf0bb0dc07736725ecd", SupportedLanguage.English);
var dataService = new AIDataService(config);
var request = new AIRequest(query);
var response = dataService.Request(request);
Assert.IsNotNull(response.Result);
Assert.IsTrue(string.IsNullOrEmpty(response.Result.Action));
}
}
[Test]
public void SessionTest()
{
var config = new AIConfiguration(SUBSCRIPTION_KEY, ACCESS_TOKEN, SupportedLanguage.English);
var firstService = new AIDataService(config);
var secondService = new AIDataService(config);
{
var weatherRequest = new AIRequest("weather");
var weatherResponse = MakeRequest(firstService, weatherRequest);
Assert.IsNotNull(weatherResponse);
}
{
var checkSecondRequest = new AIRequest("check weather");
var checkSecondResponse = MakeRequest(secondService, checkSecondRequest);
Assert.IsEmpty(checkSecondResponse.Result.Action);
}
{
var checkFirstRequest = new AIRequest("check weather");
var checkFirstResponse = MakeRequest(firstService, checkFirstRequest);
Assert.IsNotNull(checkFirstResponse.Result.Action);
Assert.IsTrue(checkFirstResponse.Result.Action.Equals("checked", StringComparison.InvariantCultureIgnoreCase));
}
}
[Test]
public void ParametersTest()
{
var dataService = CreateDataService();
var request = new AIRequest("what is your name");
var response = MakeRequest(dataService, request);
Assert.IsNotNull(response.Result.Parameters);
Assert.IsTrue(response.Result.Parameters.Count > 0);
Assert.IsTrue(response.Result.Parameters.ContainsKey("my_name"));
Assert.IsTrue(response.Result.Parameters.ContainsValue("Sam"));
Assert.IsNotNull(response.Result.Contexts);
Assert.IsTrue(response.Result.Contexts.Length > 0);
var context = response.Result.Contexts[0];
Assert.IsNotNull(context.Parameters);
Assert.IsTrue(context.Parameters.ContainsKey("my_name"));
Assert.IsTrue(context.Parameters.ContainsValue("Sam"));
}
[Test]
public void ContextsTest()
{
var dataService = CreateDataService();
var aiRequest = new AIRequest("weather");
dataService.ResetContexts();
var aiResponse = MakeRequest(dataService, aiRequest);
var action = aiResponse.Result.Action;
Assert.AreEqual("showWeather", action);
Assert.IsTrue(aiResponse.Result.Contexts.Any(c=>c.Name == "weather"));
}
[Test]
public void ResetContextsTest()
{
var dataService = CreateDataService();
dataService.ResetContexts();
{
var aiRequest = new AIRequest("what is your name");
var aiResponse = MakeRequest(dataService, aiRequest);
Assert.IsTrue(aiResponse.Result.Contexts.Any(c=>c.Name == "name_question"));
var resetSucceed = dataService.ResetContexts();
Assert.IsTrue(resetSucceed);
}
{
var aiRequest = new AIRequest("hello");
var aiResponse = MakeRequest(dataService, aiRequest);
Assert.IsFalse(aiResponse.Result.Contexts.Any(c=>c.Name == "name_question"));
}
}
[Test]
public void EntitiesTest()
{
var dataService = CreateDataService();
var aiRequest = new AIRequest("hi nori");
var myDwarfs = new Entity("dwarfs");
myDwarfs.AddEntry(new EntityEntry("Ori", new [] {"ori", "Nori"}));
myDwarfs.AddEntry(new EntityEntry("bifur", new [] {"Bofur","Bombur"}));
var extraEntities = new List<Entity> { myDwarfs };
aiRequest.Entities = extraEntities;
var aiResponse = MakeRequest(dataService, aiRequest);
Assert.IsTrue(!string.IsNullOrEmpty(aiResponse.Result.ResolvedQuery));
Assert.AreEqual("say_hi", aiResponse.Result.Action);
Assert.AreEqual("hi Bilbo, I am Ori", aiResponse.Result.Fulfillment.Speech);
}
[Test]
[ExpectedException(typeof(AIServiceException))]
public void WrongEntitiesTest()
{
var dataService = CreateDataService();
var aiRequest = new AIRequest("hi nori");
var myDwarfs = new Entity("not_dwarfs");
myDwarfs.AddEntry(new EntityEntry("Ori", new [] {"ori", "Nori"}));
myDwarfs.AddEntry(new EntityEntry("bifur", new [] {"Bofur","Bombur"}));
var extraEntities = new List<Entity> { myDwarfs };
aiRequest.Entities = extraEntities;
MakeRequest(dataService, aiRequest);
}
[Test]
public void ComplexParameterTest()
{
var config = new AIConfiguration(SUBSCRIPTION_KEY,
"23e7d37f6dd24e4eb7dbbd7491f832cf", // special agent with domains
SupportedLanguage.English);
var dataService = new AIDataService(config);
var aiRequest = new AIRequest("Turn off TV at 7pm");
var response = MakeRequest(dataService, aiRequest);
Assert.AreEqual("domains", response.Result.Source);
Assert.AreEqual("smarthome.appliances_off", response.Result.Action);
var actionCondition = response.Result.GetJsonParameter("action_condition");
var timeToken = actionCondition.SelectToken("time");
Assert.IsNotNull(timeToken);
}
[Test]
public void InputContextWithParametersTest()
{
var dataService = CreateDataService();
var aiRequest = new AIRequest("and for tomorrow");
var aiContext = new AIContext
{
Name = "weather",
Parameters = new Dictionary<string,string>
{
{ "location", "London"}
}
};
aiRequest.Contexts =
new List<AIContext>
{
aiContext
};
var response = MakeRequest(dataService, aiRequest);
Assert.AreEqual("Weather in London for tomorrow", response.Result.Fulfillment.Speech);
}
[Test]
public void ContextLifespanTest()
{
var dataService = CreateDataService();
var aiResponse = MakeRequest(dataService, new AIRequest("weather in london"));
Assert.AreEqual(2, aiResponse.Result.GetContext("shortContext").Lifespan.Value);
Assert.AreEqual(5, aiResponse.Result.GetContext("weather").Lifespan.Value);
Assert.AreEqual(10, aiResponse.Result.GetContext("longContext").Lifespan.Value);
for (int i = 0; i < 3; i++)
{
aiResponse = MakeRequest(dataService, new AIRequest("another request"));
}
Assert.IsNull(aiResponse.Result.GetContext("shortContext"));
Assert.IsNotNull(aiResponse.Result.GetContext("weather"));
Assert.IsNotNull(aiResponse.Result.GetContext("longContext"));
for (int i = 0; i < 3; i++)
{
aiResponse = MakeRequest(dataService, new AIRequest("another request"));
}
Assert.IsNull(aiResponse.Result.GetContext("shortContext"));
Assert.IsNull(aiResponse.Result.GetContext("weather"));
Assert.IsNotNull(aiResponse.Result.GetContext("longContext"));
}
[Test]
public void InputContextLifespanTest()
{
var dataService = CreateDataService();
var aiRequest = new AIRequest("and for tomorrow");
var aiContext = new AIContext
{
Name = "weather",
Parameters = new Dictionary<string, string>
{
{ "location", "London"}
},
Lifespan = 3
};
aiRequest.Contexts =
new List<AIContext>
{
aiContext
};
var response = MakeRequest(dataService, aiRequest);
Assert.IsNotNull(response.Result.GetContext("weather"));
for (int i = 0; i < 2; i++)
{
response = MakeRequest(dataService, new AIRequest("next request"));
}
Assert.IsNotNull(response.Result.GetContext("weather"));
response = MakeRequest(dataService, new AIRequest("next request"));
Assert.IsNull(response.Result.GetContext("weather"));
}
private AIResponse MakeRequest(AIDataService service, AIRequest request)
{
var aiResponse = service.Request(request);
Assert.IsNotNull(aiResponse);
Assert.IsFalse(aiResponse.IsError);
Assert.IsFalse(string.IsNullOrEmpty(aiResponse.Id));
Assert.IsNotNull(aiResponse.Result);
return aiResponse;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// This object is used to wrap a bunch of ConnectAsync operations
// on behalf of a single user call to ConnectAsync with a DnsEndPoint
internal abstract class MultipleConnectAsync
{
protected SocketAsyncEventArgs _userArgs;
protected SocketAsyncEventArgs _internalArgs;
protected DnsEndPoint _endPoint;
protected IPAddress[] _addressList;
protected int _nextAddress;
private enum State
{
NotStarted,
DnsQuery,
ConnectAttempt,
Completed,
Canceled,
}
private State _state;
private object _lockObject = new object();
// Called by Socket to kick off the ConnectAsync process. We'll complete the user's SAEA
// when it's done. Returns true if the operation will be asynchronous, false if it has failed synchronously
public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint)
{
lock (_lockObject)
{
if (endPoint.AddressFamily != AddressFamily.Unspecified &&
endPoint.AddressFamily != AddressFamily.InterNetwork &&
endPoint.AddressFamily != AddressFamily.InterNetworkV6)
{
NetEventSource.Fail(this, $"Unexpected endpoint address family: {endPoint.AddressFamily}");
}
_userArgs = args;
_endPoint = endPoint;
// If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
// fail synchronously from here. Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
if (_state == State.Canceled)
{
SyncFail(new SocketException((int)SocketError.OperationAborted));
return false;
}
if (_state != State.NotStarted)
{
NetEventSource.Fail(this, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
}
_state = State.DnsQuery;
IAsyncResult result = Dns.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null);
if (result.CompletedSynchronously)
{
return DoDnsCallback(result, true);
}
else
{
return true;
}
}
}
// Callback which fires when the Dns Resolve is complete
private void DnsCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
DoDnsCallback(result, false);
}
}
// Called when the DNS query completes (either synchronously or asynchronously). Checks for failure and
// starts the first connection attempt if it succeeded. Returns true if the operation will be asynchronous,
// false if it has failed synchronously.
private bool DoDnsCallback(IAsyncResult result, bool sync)
{
Exception exception = null;
lock (_lockObject)
{
// If the connection attempt was canceled during the dns query, the user's callback has already been
// called asynchronously and we simply need to return.
if (_state == State.Canceled)
{
return true;
}
if (_state != State.DnsQuery)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): Unexpected object state");
}
try
{
_addressList = Dns.EndGetHostAddresses(result);
if (_addressList == null)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!");
}
}
catch (Exception e)
{
_state = State.Completed;
exception = e;
}
// If the dns query succeeded, try to connect to the first address
if (exception == null)
{
_state = State.ConnectAttempt;
_internalArgs = new SocketAsyncEventArgs();
_internalArgs.Completed += InternalConnectCallback;
_internalArgs.CopyBufferFrom(_userArgs);
exception = AttemptConnection();
if (exception != null)
{
// There was a synchronous error while connecting
_state = State.Completed;
}
}
}
// Call this outside of the lock because it might call the user's callback.
if (exception != null)
{
return Fail(sync, exception);
}
else
{
return true;
}
}
// Callback which fires when an internal connection attempt completes.
// If it failed and there are more addresses to try, do it.
private void InternalConnectCallback(object sender, SocketAsyncEventArgs args)
{
Exception exception = null;
lock (_lockObject)
{
if (_state == State.Canceled)
{
// If Cancel was called before we got the lock, the Socket will be closed soon. We need to report
// OperationAborted (even though the connection actually completed), or the user will try to use a
// closed Socket.
exception = new SocketException((int)SocketError.OperationAborted);
}
else
{
Debug.Assert(_state == State.ConnectAttempt);
if (args.SocketError == SocketError.Success)
{
// The connection attempt succeeded; go to the completed state.
// The callback will be called outside the lock.
_state = State.Completed;
}
else if (args.SocketError == SocketError.OperationAborted)
{
// The socket was closed while the connect was in progress. This can happen if the user
// closes the socket, and is equivalent to a call to CancelConnectAsync
exception = new SocketException((int)SocketError.OperationAborted);
_state = State.Canceled;
}
else
{
// Keep track of this because it will be overwritten by AttemptConnection
SocketError currentFailure = args.SocketError;
Exception connectException = AttemptConnection();
if (connectException == null)
{
// don't call the callback, another connection attempt is successfully started
return;
}
else
{
SocketException socketException = connectException as SocketException;
if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
{
// If the error is NoData, that means there are no more IPAddresses to attempt
// a connection to. Return the last error from an actual connection instead.
exception = new SocketException((int)currentFailure);
}
else
{
exception = connectException;
}
_state = State.Completed;
}
}
}
}
if (exception == null)
{
Succeed();
}
else
{
AsyncFail(exception);
}
}
// Called to initiate a connection attempt to the next address in the list. Returns an exception
// if the attempt failed synchronously, or null if it was successfully initiated.
private Exception AttemptConnection()
{
try
{
Socket attemptSocket;
IPAddress attemptAddress = GetNextAddress(out attemptSocket);
if (attemptAddress == null)
{
return new SocketException((int)SocketError.NoData);
}
_internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port);
return AttemptConnection(attemptSocket, _internalArgs);
}
catch (Exception e)
{
if (e is ObjectDisposedException)
{
NetEventSource.Fail(this, "unexpected ObjectDisposedException");
}
return e;
}
}
private Exception AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args)
{
try
{
if (attemptSocket == null)
{
NetEventSource.Fail(null, "attemptSocket is null!");
}
bool pending = attemptSocket.ConnectAsync(args);
if (!pending)
{
InternalConnectCallback(null, args);
}
}
catch (ObjectDisposedException)
{
// This can happen if the user closes the socket, and is equivalent to a call
// to CancelConnectAsync
return new SocketException((int)SocketError.OperationAborted);
}
catch (Exception e)
{
return e;
}
return null;
}
protected abstract void OnSucceed();
private void Succeed()
{
OnSucceed();
_userArgs.FinishWrapperConnectSuccess(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
_internalArgs.Dispose();
}
protected abstract void OnFail(bool abortive);
private bool Fail(bool sync, Exception e)
{
if (sync)
{
SyncFail(e);
return false;
}
else
{
AsyncFail(e);
return true;
}
}
private void SyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
SocketException socketException = e as SocketException;
if (socketException != null)
{
_userArgs.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None);
}
else
{
ExceptionDispatchInfo.Throw(e);
}
}
private void AsyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
_userArgs.FinishConnectByNameAsyncFailure(e, 0, SocketFlags.None);
}
public void Cancel()
{
bool callOnFail = false;
lock (_lockObject)
{
switch (_state)
{
case State.NotStarted:
// Cancel was called before the Dns query was started. The dns query won't be started
// and the connection attempt will fail synchronously after the state change to DnsQuery.
// All we need to do here is close all the sockets.
callOnFail = true;
break;
case State.DnsQuery:
// Cancel was called after the Dns query was started, but before it finished. We can't
// actually cancel the Dns query, but we'll fake it by failing the connect attempt asynchronously
// from here, and silently dropping the connection attempt when the Dns query finishes.
Task.Factory.StartNew(
s => CallAsyncFail(s),
null,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
callOnFail = true;
break;
case State.ConnectAttempt:
// Cancel was called after the Dns query completed, but before we had a connection result to give
// to the user. Closing the sockets will cause any in-progress ConnectAsync call to fail immediately
// with OperationAborted, and will cause ObjectDisposedException from any new calls to ConnectAsync
// (which will be translated to OperationAborted by AttemptConnection).
callOnFail = true;
break;
case State.Completed:
// Cancel was called after we locked in a result to give to the user. Ignore it and give the user
// the real completion.
break;
default:
NetEventSource.Fail(this, "Unexpected object state");
break;
}
_state = State.Canceled;
}
// Call this outside the lock because Socket.Close may block
if (callOnFail)
{
OnFail(true);
}
}
// Call AsyncFail on a threadpool thread so it's asynchronous with respect to Cancel().
private void CallAsyncFail(object ignored)
{
AsyncFail(new SocketException((int)SocketError.OperationAborted));
}
protected abstract IPAddress GetNextAddress(out Socket attemptSocket);
}
// Used when the instance ConnectAsync method is called, or when the DnsEndPoint specified
// an AddressFamily. There's only one Socket, and we only try addresses that match its
// AddressFamily
internal sealed class SingleSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket;
private bool _userSocket;
public SingleSocketMultipleConnectAsync(Socket socket, bool userSocket)
{
_socket = socket;
_userSocket = userSocket;
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
_socket.ReplaceHandleIfNecessaryAfterFailedConnect();
IPAddress rval = null;
do
{
if (_nextAddress >= _addressList.Length)
{
attemptSocket = null;
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
}
while (!_socket.CanTryAddressFamily(rval.AddressFamily));
attemptSocket = _socket;
return rval;
}
protected override void OnFail(bool abortive)
{
// Close the socket if this is an abortive failure (CancelConnectAsync)
// or if we created it internally
if (abortive || !_userSocket)
{
_socket.Dispose();
}
}
// nothing to do on success
protected override void OnSucceed() { }
}
// This is used when the static ConnectAsync method is called. We don't know the address family
// ahead of time, so we create both IPv4 and IPv6 sockets.
internal sealed class DualSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket4;
private Socket _socket6;
public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protocolType)
{
if (Socket.OSSupportsIPv4)
{
_socket4 = new Socket(AddressFamily.InterNetwork, socketType, protocolType);
}
if (Socket.OSSupportsIPv6)
{
_socket6 = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType);
}
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
IPAddress rval = null;
attemptSocket = null;
while (attemptSocket == null)
{
if (_nextAddress >= _addressList.Length)
{
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
if (rval.AddressFamily == AddressFamily.InterNetworkV6)
{
attemptSocket = _socket6;
}
else if (rval.AddressFamily == AddressFamily.InterNetwork)
{
attemptSocket = _socket4;
}
}
attemptSocket?.ReplaceHandleIfNecessaryAfterFailedConnect();
return rval;
}
// on success, close the socket that wasn't used
protected override void OnSucceed()
{
if (_socket4 != null && !_socket4.Connected)
{
_socket4.Dispose();
}
if (_socket6 != null && !_socket6.Connected)
{
_socket6.Dispose();
}
}
// close both sockets whether its abortive or not - we always create them internally
protected override void OnFail(bool abortive)
{
_socket4?.Dispose();
_socket6?.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 java.lang;
using cnatural.helpers;
namespace cnatural.parser {
public class PreprocessorScanner : ScannerBase {
private bool lineStart;
private bool preprocessorLine;
public PreprocessorScanner(CodeErrorManager codeErrorManager, char[] text)
: this(codeErrorManager, text, 0, sizeof(text), 0, 0) {
}
public PreprocessorScanner(CodeErrorManager codeErrorManager, char[] text, int position, int length, int line, int column)
: super(codeErrorManager, text, position, length, line, column) {
this.lineStart = true;
}
public void scanMessage() {
while (true) {
switch (this.Next) {
case -1:
case '\r':
case '\u2028':
case '\u2029':
case '\n':
return;
}
advance();
}
}
public final PreprocessorLexicalUnit nextLexicalUnit(bool skippedSection) {
if (this.Next == -1) {
return PreprocessorLexicalUnit.EndOfStream;
}
while (true) {
switch (this.Next) {
case -1:
if (this.preprocessorLine) {
return PreprocessorLexicalUnit.EndOfStream;
}
return PreprocessorLexicalUnit.SourceCode;
case '\r':
this.Line++;
this.Column = -1;
if (advance() == '\n') {
this.Column = -1;
advance();
}
this.lineStart = true;
if (this.preprocessorLine) {
this.preprocessorLine = false;
return PreprocessorLexicalUnit.NewLine;
}
this.preprocessorLine = false;
return PreprocessorLexicalUnit.SourceCode;
case '\u2028':
case '\u2029':
case '\n':
this.Line++;
this.Column = -1;
advance();
this.lineStart = true;
if (this.preprocessorLine) {
this.preprocessorLine = false;
return PreprocessorLexicalUnit.NewLine;
}
this.preprocessorLine = false;
return PreprocessorLexicalUnit.SourceCode;
case ' ':
case '\t':
case '\v':
case '\f':
scanWhitespaces();
if (this.preprocessorLine) {
return PreprocessorLexicalUnit.WhiteSpace;
}
break;
case '@':
if (this.preprocessorLine) {
throw error(ParseErrorId.InvalidPreprocessorChar);
}
if (!skippedSection) {
if (advance() == '"') {
advance();
for (; ; ) {
switch (this.Next) {
case -1:
throw error(ParseErrorId.UnclosedVerbatimString);
case '\r':
this.Line++;
this.Column = -1;
if (advance() == '\n') {
this.Column = -1;
advance();
}
break;
case '\u2028':
case '\u2029':
case '\n':
this.Line++;
this.Column = -1;
advance();
break;
case '"':
switch (advance()) {
case '"':
advance();
break;
default:
return PreprocessorLexicalUnit.SourceCode;
}
break;
default:
advance();
break;
}
}
}
} else {
if (advance() == '"') {
for (; ; ) {
switch (advance()) {
case -1:
case '\u2028':
case '\u2029':
case '\r':
case '\n':
return PreprocessorLexicalUnit.SourceCode;
}
}
}
}
break;
case '/':
this.lineStart = false;
switch (advance()) {
case '/':
for (; ; ) {
switch (advance()) {
case -1:
case '\r':
case '\u2028':
case '\u2029':
case '\n':
if (this.preprocessorLine) {
return PreprocessorLexicalUnit.SingleLineComment;
} else {
return PreprocessorLexicalUnit.SourceCode;
}
}
}
case '*':
if (this.preprocessorLine) {
throw error(ParseErrorId.InvalidPreprocessorChar);
}
if (!skippedSection) {
advance();
for (; ; ) {
switch (this.Next) {
case -1:
throw error(ParseErrorId.UnclosedDelimitedComment);
case '\r':
this.Line++;
this.Column = -1;
if (advance() == '\n') {
this.Column = -1;
advance();
}
break;
case '\u2028':
case '\u2029':
case '\n':
this.Line++;
this.Column = -1;
advance();
break;
case '*':
switch (advance()) {
case -1:
throw error(ParseErrorId.UnclosedDelimitedComment);
case '/':
advance();
return PreprocessorLexicalUnit.SourceCode;
}
break;
default:
advance();
break;
}
}
} else {
for (; ; ) {
switch (advance()) {
case -1:
case '\u2028':
case '\u2029':
case '\r':
case '\n':
return PreprocessorLexicalUnit.SourceCode;
}
}
}
default:
if (this.preprocessorLine) {
throw error(ParseErrorId.InvalidPreprocessorChar);
}
break;
}
break;
case '|':
if (this.preprocessorLine) {
if (advance() == '|') {
advance();
return PreprocessorLexicalUnit.Or;
} else {
throw error(ParseErrorId.InvalidPreprocessorChar);
}
} else {
this.lineStart = false;
advance();
}
break;
case '&':
if (this.preprocessorLine) {
if (advance() == '&') {
advance();
return PreprocessorLexicalUnit.And;
} else {
throw error(ParseErrorId.InvalidPreprocessorChar);
}
} else {
this.lineStart = false;
advance();
}
break;
case '=':
if (this.preprocessorLine) {
if (advance() == '=') {
advance();
return PreprocessorLexicalUnit.Equal;
} else {
throw error(ParseErrorId.InvalidPreprocessorChar);
}
} else {
this.lineStart = false;
advance();
}
break;
case '!':
if (this.preprocessorLine) {
if (advance() == '=') {
advance();
return PreprocessorLexicalUnit.NotEqual;
} else {
return PreprocessorLexicalUnit.Not;
}
} else {
this.lineStart = false;
advance();
}
break;
case 'd':
if (this.preprocessorLine) {
return scanKeyword("define", PreprocessorLexicalUnit.Define);
} else {
this.lineStart = false;
advance();
}
break;
case 'i':
if (this.preprocessorLine) {
return scanKeyword("if", PreprocessorLexicalUnit.If);
} else {
this.lineStart = false;
advance();
}
break;
case 'p':
if (this.preprocessorLine) {
return scanKeyword("pragma", PreprocessorLexicalUnit.Pragma);
} else {
this.lineStart = false;
advance();
}
break;
case 'u':
if (this.preprocessorLine) {
return scanKeyword("undef", PreprocessorLexicalUnit.Undef);
} else {
this.lineStart = false;
advance();
}
break;
case 'l':
if (this.preprocessorLine) {
return scanKeyword("line", PreprocessorLexicalUnit.Line);
} else {
this.lineStart = false;
advance();
}
break;
case 'w':
if (this.preprocessorLine) {
return scanKeyword("warning", PreprocessorLexicalUnit.Warning);
} else {
this.lineStart = false;
advance();
}
break;
case 'r':
if (this.preprocessorLine) {
return scanKeyword("region", PreprocessorLexicalUnit.Region);
} else {
this.lineStart = false;
advance();
}
break;
case 'e':
if (this.preprocessorLine) {
switch (advance()) {
case 'l':
switch (advance()) {
case 'i':
return scanKeyword("if", PreprocessorLexicalUnit.Elif);
case 's':
return scanKeyword("se", PreprocessorLexicalUnit.Else);
default:
if (ParserHelper.isIdentifierPartChar(this.Next)) {
scanIdentifierPart();
}
return PreprocessorLexicalUnit.Symbol;
}
case 'n':
switch (advance()) {
case 'd':
switch (advance()) {
case 'i':
return scanKeyword("if", PreprocessorLexicalUnit.Endif);
case 'r':
return scanKeyword("region", PreprocessorLexicalUnit.Endregion);
default:
if (ParserHelper.isIdentifierPartChar(this.Next)) {
scanIdentifierPart();
}
return PreprocessorLexicalUnit.Symbol;
}
default:
if (ParserHelper.isIdentifierPartChar(this.Next)) {
scanIdentifierPart();
}
return PreprocessorLexicalUnit.Symbol;
}
case 'r':
return scanKeyword("rror", PreprocessorLexicalUnit.Error);
default:
if (ParserHelper.isIdentifierPartChar(this.Next)) {
scanIdentifierPart();
}
return PreprocessorLexicalUnit.Symbol;
}
} else {
this.lineStart = false;
advance();
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (this.preprocessorLine) {
for (; ; ) {
switch (advance()) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
break;
default:
return PreprocessorLexicalUnit.DecimalDigits;
}
}
} else {
this.lineStart = false;
advance();
}
break;
case '\'':
switch (advance()) {
case -1:
case '\r':
case '\u2028':
case '\u2029':
case '\n':
case '\'':
return PreprocessorLexicalUnit.SourceCode;
case '\\':
advance();
bool done = false;
do {
switch (advance()) {
case -1:
case '\r':
case '\u2028':
case '\u2029':
case '\n':
case '\'':
done = true;
break;
}
} while (!done);
break;
default:
advance();
advance();
break;
}
break;
case '"':
if (this.preprocessorLine) {
for (; ; ) {
switch (advance()) {
case -1:
case '\r':
case '\u2028':
case '\u2029':
case '\n':
throw error(ParseErrorId.UnclosedFilename);
case '"':
advance();
return PreprocessorLexicalUnit.Filename;
}
}
} else {
this.lineStart = false;
for (; ; ) {
switch (advance()) {
case -1:
case '\r':
case '\u2028':
case '\u2029':
case '\n':
case '"':
return PreprocessorLexicalUnit.SourceCode;
case '\\':
advance();
bool done = false;
do {
switch (advance()) {
case -1:
case '\r':
case '\u2028':
case '\u2029':
case '\n':
case '\"':
done = true;
break;
}
} while (!done);
break;
}
}
}
case '(':
if (this.preprocessorLine) {
advance();
return PreprocessorLexicalUnit.LeftParenthesis;
} else {
this.lineStart = false;
advance();
}
break;
case ')':
if (this.preprocessorLine) {
advance();
return PreprocessorLexicalUnit.RightParenthesis;
} else {
this.lineStart = false;
advance();
}
break;
case ',':
if (this.preprocessorLine) {
advance();
return PreprocessorLexicalUnit.Comma;
} else {
this.lineStart = false;
advance();
}
break;
case '_':
if (this.preprocessorLine) {
scanIdentifierPart();
return PreprocessorLexicalUnit.Symbol;
} else {
this.lineStart = false;
advance();
}
break;
case '\\':
if (this.preprocessorLine) {
int unicode = scanUnicodeEscapeSequence();
if (ParserHelper.isIdentifierStartChar(unicode)) {
scanIdentifierPart();
return PreprocessorLexicalUnit.Symbol;
} else {
throw error(ParseErrorId.InvalidPreprocessorChar);
}
} else {
this.lineStart = false;
advance();
}
break;
default:
if (this.preprocessorLine) {
if (ParserHelper.isIdentifierStartChar(this.Next)) {
scanIdentifierPart();
return PreprocessorLexicalUnit.Symbol;
}
}
this.lineStart = false;
advance();
break;
case '#':
if (!lineStart) {
throw error(ParseErrorId.MisplacedNumberSign);
}
this.lineStart = false;
this.preprocessorLine = true;
advance();
return PreprocessorLexicalUnit.NumberSign;
}
}
}
private PreprocessorLexicalUnit scanKeyword(String suffix, PreprocessorLexicalUnit keyword) {
bool isKeyword = true;
for (int i = 0; i < suffix.length(); i++) {
char c = suffix[i];
if (this.Next == -1 || (char)this.Next != c) {
isKeyword = false;
break;
}
advance();
}
if (this.Next != -1 && ParserHelper.isIdentifierPartChar(this.Next)) {
scanIdentifierPart();
return PreprocessorLexicalUnit.Symbol;
}
return (isKeyword) ? keyword : PreprocessorLexicalUnit.Symbol;
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Contoso.Provisioning.Cloud.SyncWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/*
* 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 System.Threading;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.ClientStack.LindenUDP;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Hypergrid;
using OpenMetaverse;
using OpenMetaverse.Packets;
using log4net;
using Nini.Config;
using Mono.Addins;
using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags;
namespace OpenSim.Region.CoreModules.Framework.UserManagement
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserManagementModule")]
public class UserManagementModule : ISharedRegionModule, IUserManagement, IPeople
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled;
protected List<Scene> m_Scenes = new List<Scene>();
protected IServiceThrottleModule m_ServiceThrottle;
// The cache
protected Dictionary<UUID, UserData> m_UserCache = new Dictionary<UUID, UserData>();
protected bool m_DisplayChangingHomeURI = false;
#region ISharedRegionModule
public virtual void Initialise(IConfigSource config)
{
string umanmod = config.Configs["Modules"].GetString("UserManagementModule", Name);
if (umanmod == Name)
{
m_Enabled = true;
Init();
m_log.DebugFormat("[USER MANAGEMENT MODULE]: {0} is enabled", Name);
}
if(!m_Enabled)
{
return;
}
IConfig userManagementConfig = config.Configs["UserManagement"];
if (userManagementConfig == null)
return;
m_DisplayChangingHomeURI = userManagementConfig.GetBoolean("DisplayChangingHomeURI", false);
}
public virtual bool IsSharedModule
{
get { return true; }
}
public virtual string Name
{
get { return "BasicUserManagementModule"; }
}
public virtual Type ReplaceableInterface
{
get { return null; }
}
public virtual void AddRegion(Scene scene)
{
if (m_Enabled)
{
lock (m_Scenes)
{
m_Scenes.Add(scene);
}
scene.RegisterModuleInterface<IUserManagement>(this);
scene.RegisterModuleInterface<IPeople>(this);
scene.EventManager.OnNewClient += new EventManager.OnNewClientDelegate(EventManager_OnNewClient);
scene.EventManager.OnPrimsLoaded += new EventManager.PrimsLoaded(EventManager_OnPrimsLoaded);
}
}
public virtual void RemoveRegion(Scene scene)
{
if (m_Enabled)
{
scene.UnregisterModuleInterface<IUserManagement>(this);
lock (m_Scenes)
{
m_Scenes.Remove(scene);
}
}
}
public virtual void RegionLoaded(Scene s)
{
if (m_Enabled && m_ServiceThrottle == null)
m_ServiceThrottle = s.RequestModuleInterface<IServiceThrottleModule>();
}
public virtual void PostInitialise()
{
}
public virtual void Close()
{
lock (m_Scenes)
{
m_Scenes.Clear();
}
lock (m_UserCache)
m_UserCache.Clear();
}
#endregion ISharedRegionModule
#region Event Handlers
protected virtual void EventManager_OnPrimsLoaded(Scene s)
{
// let's sniff all the user names referenced by objects in the scene
m_log.DebugFormat("[USER MANAGEMENT MODULE]: Caching creators' data from {0} ({1} objects)...", s.RegionInfo.RegionName, s.GetEntities().Length);
s.ForEachSOG(delegate(SceneObjectGroup sog) { CacheCreators(sog); });
}
protected virtual void EventManager_OnNewClient(IClientAPI client)
{
client.OnConnectionClosed += new Action<IClientAPI>(HandleConnectionClosed);
client.OnNameFromUUIDRequest += new UUIDNameRequest(HandleUUIDNameRequest);
client.OnAvatarPickerRequest += new AvatarPickerRequest(HandleAvatarPickerRequest);
}
protected virtual void HandleConnectionClosed(IClientAPI client)
{
client.OnNameFromUUIDRequest -= new UUIDNameRequest(HandleUUIDNameRequest);
client.OnAvatarPickerRequest -= new AvatarPickerRequest(HandleAvatarPickerRequest);
client.OnConnectionClosed -= new Action<IClientAPI>(HandleConnectionClosed);
}
protected virtual void HandleUUIDNameRequest(UUID uuid, IClientAPI client)
{
// m_log.DebugFormat(
// "[USER MANAGEMENT MODULE]: Handling request for name binding of UUID {0} from {1}",
// uuid, remote_client.Name);
if(m_Scenes.Count <= 0)
return;
if (m_Scenes[0].LibraryService != null && (m_Scenes[0].LibraryService.LibraryRootFolder.Owner == uuid))
{
client.SendNameReply(uuid, "Mr", "OpenSim");
}
else
{
UserData user;
/* bypass that continuation here when entry is already available */
lock (m_UserCache)
{
if (m_UserCache.TryGetValue(uuid, out user))
{
if (!user.IsUnknownUser && user.HasGridUserTried)
{
client.SendNameReply(uuid, user.FirstName, user.LastName);
return;
}
}
}
// Not found in cache, queue continuation
m_ServiceThrottle.Enqueue("uuidname", uuid.ToString(), delegate
{
//m_log.DebugFormat("[YYY]: Name request {0}", uuid);
// As least upto September 2013, clients permanently cache UUID -> Name bindings. Some clients
// appear to clear this when the user asks it to clear the cache, but others may not.
//
// So to avoid clients
// (particularly Hypergrid clients) permanently binding "Unknown User" to a given UUID, we will
// instead drop the request entirely.
if(!client.IsActive)
return;
if (GetUser(uuid, out user))
{
if(client.IsActive)
client.SendNameReply(uuid, user.FirstName, user.LastName);
}
// else
// m_log.DebugFormat(
// "[USER MANAGEMENT MODULE]: No bound name for {0} found, ignoring request from {1}",
// uuid, client.Name);
});
}
}
public virtual void HandleAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query)
{
//EventManager.TriggerAvatarPickerRequest();
m_log.DebugFormat("[USER MANAGEMENT MODULE]: HandleAvatarPickerRequest for {0}", query);
List<UserData> users = GetUserData(query, 500, 1);
AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket)PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply);
// TODO: don't create new blocks if recycling an old packet
AvatarPickerReplyPacket.DataBlock[] searchData =
new AvatarPickerReplyPacket.DataBlock[users.Count];
AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock();
agentData.AgentID = avatarID;
agentData.QueryID = RequestID;
replyPacket.AgentData = agentData;
//byte[] bytes = new byte[AvatarResponses.Count*32];
int i = 0;
foreach (UserData item in users)
{
UUID translatedIDtem = item.Id;
searchData[i] = new AvatarPickerReplyPacket.DataBlock();
searchData[i].AvatarID = translatedIDtem;
searchData[i].FirstName = Utils.StringToBytes((string)item.FirstName);
searchData[i].LastName = Utils.StringToBytes((string)item.LastName);
i++;
}
if (users.Count == 0)
{
searchData = new AvatarPickerReplyPacket.DataBlock[0];
}
replyPacket.Data = searchData;
AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs();
agent_data.AgentID = replyPacket.AgentData.AgentID;
agent_data.QueryID = replyPacket.AgentData.QueryID;
List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>();
for (i = 0; i < replyPacket.Data.Length; i++)
{
AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs();
data_arg.AvatarID = replyPacket.Data[i].AvatarID;
data_arg.FirstName = replyPacket.Data[i].FirstName;
data_arg.LastName = replyPacket.Data[i].LastName;
data_args.Add(data_arg);
}
client.SendAvatarPickerReply(agent_data, data_args);
}
protected virtual void AddAdditionalUsers(string query, List<UserData> users)
{
}
#endregion Event Handlers
#region IPeople
public virtual List<UserData> GetUserData(string query, int page_size, int page_number)
{
if(m_Scenes.Count <= 0)
return new List<UserData>();;
// search the user accounts service
List<UserAccount> accs = m_Scenes[0].UserAccountService.GetUserAccounts(m_Scenes[0].RegionInfo.ScopeID, query);
List<UserData> users = new List<UserData>();
if (accs != null)
{
foreach (UserAccount acc in accs)
{
UserData ud = new UserData();
ud.FirstName = acc.FirstName;
ud.LastName = acc.LastName;
ud.Id = acc.PrincipalID;
ud.HasGridUserTried = true;
ud.IsUnknownUser = false;
users.Add(ud);
}
}
// search the local cache
foreach (UserData data in m_UserCache.Values)
{
if (data.Id != UUID.Zero && !data.IsUnknownUser &&
users.Find(delegate(UserData d) { return d.Id == data.Id; }) == null &&
(data.FirstName.ToLower().StartsWith(query.ToLower()) || data.LastName.ToLower().StartsWith(query.ToLower())))
users.Add(data);
}
AddAdditionalUsers(query, users);
return users;
}
#endregion IPeople
protected virtual void CacheCreators(SceneObjectGroup sog)
{
//m_log.DebugFormat("[USER MANAGEMENT MODULE]: processing {0} {1}; {2}", sog.RootPart.Name, sog.RootPart.CreatorData, sog.RootPart.CreatorIdentification);
AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData);
foreach (SceneObjectPart sop in sog.Parts)
{
AddUser(sop.CreatorID, sop.CreatorData);
foreach (TaskInventoryItem item in sop.TaskInventory.Values)
AddUser(item.CreatorID, item.CreatorData);
}
}
/// <summary>
///
/// </summary>
/// <param name="uuid"></param>
/// <param name="names">Caller please provide a properly instantiated array for names, string[2]</param>
/// <returns></returns>
protected virtual bool TryGetUserNames(UUID uuid, string[] names)
{
if (names == null)
names = new string[2];
if (TryGetUserNamesFromCache(uuid, names))
return true;
if (TryGetUserNamesFromServices(uuid, names))
return true;
return false;
}
protected virtual bool TryGetUserNamesFromCache(UUID uuid, string[] names)
{
lock (m_UserCache)
{
if (m_UserCache.ContainsKey(uuid))
{
names[0] = m_UserCache[uuid].FirstName;
names[1] = m_UserCache[uuid].LastName;
return true;
}
}
return false;
}
/// <summary>
/// Try to get the names bound to the given uuid, from the services.
/// </summary>
/// <returns>True if the name was found, false if not.</returns>
/// <param name='uuid'></param>
/// <param name='names'>The array of names if found. If not found, then names[0] = "Unknown" and names[1] = "User"</param>
protected virtual bool TryGetUserNamesFromServices(UUID uuid, string[] names)
{
if(m_Scenes.Count <= 0)
return false;
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, uuid);
if (account != null)
{
names[0] = account.FirstName;
names[1] = account.LastName;
UserData user = new UserData();
user.FirstName = account.FirstName;
user.LastName = account.LastName;
lock (m_UserCache)
m_UserCache[uuid] = user;
return true;
}
else
{
// Let's try the GridUser service
GridUserInfo uInfo = m_Scenes[0].GridUserService.GetGridUserInfo(uuid.ToString());
if (uInfo != null)
{
string url, first, last, tmp;
UUID u;
if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out u, out url, out first, out last, out tmp))
{
AddUser(uuid, first, last, url);
if (m_UserCache.ContainsKey(uuid))
{
names[0] = m_UserCache[uuid].FirstName;
names[1] = m_UserCache[uuid].LastName;
return true;
}
}
else
m_log.DebugFormat("[USER MANAGEMENT MODULE]: Unable to parse UUI {0}", uInfo.UserID);
}
// else
// {
// m_log.DebugFormat("[USER MANAGEMENT MODULE]: No grid user found for {0}", uuid);
// }
names[0] = "Unknown";
names[1] = "UserUMMTGUN9";
return false;
}
}
#region IUserManagement
public virtual UUID GetUserIdByName(string name)
{
string[] parts = name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
throw new Exception("Name must have 2 components");
return GetUserIdByName(parts[0], parts[1]);
}
public virtual UUID GetUserIdByName(string firstName, string lastName)
{
if(m_Scenes.Count <= 0)
return UUID.Zero;
// TODO: Optimize for reverse lookup if this gets used by non-console commands.
lock (m_UserCache)
{
foreach (UserData user in m_UserCache.Values)
{
if (user.FirstName == firstName && user.LastName == lastName)
return user.Id;
}
}
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
if (account != null)
return account.PrincipalID;
return UUID.Zero;
}
public virtual string GetUserName(UUID uuid)
{
UserData user;
GetUser(uuid, out user);
return user.FirstName + " " + user.LastName;
}
public virtual Dictionary<UUID,string> GetUsersNames(string[] ids)
{
Dictionary<UUID,string> ret = new Dictionary<UUID,string>();
if(m_Scenes.Count <= 0)
return ret;
List<string> missing = new List<string>();
Dictionary<UUID,string> untried = new Dictionary<UUID, string>();
// look in cache
UserData userdata = new UserData();
UUID uuid = UUID.Zero;
foreach(string id in ids)
{
if(UUID.TryParse(id, out uuid))
{
lock (m_UserCache)
{
if (m_UserCache.TryGetValue(uuid, out userdata) &&
userdata.FirstName != "Unknown" && userdata.FirstName != string.Empty)
{
string name = userdata.FirstName + " " + userdata.LastName;
if(userdata.HasGridUserTried)
ret[uuid] = name;
else
{
untried[uuid] = name;
missing.Add(id);
}
}
else
missing.Add(id);
}
}
}
if(missing.Count == 0)
return ret;
// try user account service
List<UserAccount> accounts = m_Scenes[0].UserAccountService.GetUserAccounts(
m_Scenes[0].RegionInfo.ScopeID, missing);
if(accounts.Count != 0)
{
foreach(UserAccount uac in accounts)
{
if(uac != null)
{
string name = uac.FirstName + " " + uac.LastName;
ret[uac.PrincipalID] = name;
missing.Remove(uac.PrincipalID.ToString()); // slowww
untried.Remove(uac.PrincipalID);
userdata = new UserData();
userdata.Id = uac.PrincipalID;
userdata.FirstName = uac.FirstName;
userdata.LastName = uac.LastName;
userdata.HomeURL = string.Empty;
userdata.IsUnknownUser = false;
userdata.HasGridUserTried = true;
lock (m_UserCache)
m_UserCache[uac.PrincipalID] = userdata;
}
}
}
if (missing.Count == 0 || m_Scenes[0].GridUserService == null)
return ret;
// try grid user service
GridUserInfo[] pinfos = m_Scenes[0].GridUserService.GetGridUserInfo(missing.ToArray());
if(pinfos.Length > 0)
{
foreach(GridUserInfo uInfo in pinfos)
{
if (uInfo != null)
{
string url, first, last, tmp;
if(uInfo.UserID.Length <= 36)
continue;
if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out uuid, out url, out first, out last, out tmp))
{
if (url != string.Empty)
{
try
{
userdata = new UserData();
userdata.FirstName = first.Replace(" ", ".") + "." + last.Replace(" ", ".");
userdata.LastName = "@" + new Uri(url).Authority;
userdata.Id = uuid;
userdata.HomeURL = url;
userdata.IsUnknownUser = false;
userdata.HasGridUserTried = true;
lock (m_UserCache)
m_UserCache[uuid] = userdata;
string name = userdata.FirstName + " " + userdata.LastName;
ret[uuid] = name;
missing.Remove(uuid.ToString());
untried.Remove(uuid);
}
catch
{
}
}
}
}
}
}
// add the untried in cache that still failed
if(untried.Count > 0)
{
foreach(KeyValuePair<UUID, string> kvp in untried)
{
ret[kvp.Key] = kvp.Value;
missing.Remove((kvp.Key).ToString());
}
}
// add the UMMthings ( not sure we should)
if(missing.Count > 0)
{
foreach(string id in missing)
{
if(UUID.TryParse(id, out uuid) && uuid != UUID.Zero)
{
if (m_Scenes[0].LibraryService != null &&
(m_Scenes[0].LibraryService.LibraryRootFolder.Owner == uuid))
ret[uuid] = "Mr OpenSim";
else
ret[uuid] = "Unknown UserUMMAU43";
}
}
}
return ret;
}
public virtual string GetUserHomeURL(UUID userID)
{
UserData user;
if(GetUser(userID, out user))
{
return user.HomeURL;
}
return string.Empty;
}
public virtual string GetUserServerURL(UUID userID, string serverType)
{
UserData userdata;
if(!GetUser(userID, out userdata))
{
return string.Empty;
}
if (userdata.ServerURLs != null && userdata.ServerURLs.ContainsKey(serverType) && userdata.ServerURLs[serverType] != null)
{
return userdata.ServerURLs[serverType].ToString();
}
if (!string.IsNullOrEmpty(userdata.HomeURL))
{
// m_log.DebugFormat("[USER MANAGEMENT MODULE]: Requested url type {0} for {1}", serverType, userID);
UserAgentServiceConnector uConn = new UserAgentServiceConnector(userdata.HomeURL);
try
{
userdata.ServerURLs = uConn.GetServerURLs(userID);
}
catch(System.Net.WebException e)
{
m_log.DebugFormat("[USER MANAGEMENT MODULE]: GetServerURLs call failed {0}", e.Message);
userdata.ServerURLs = new Dictionary<string, object>();
}
catch (Exception e)
{
m_log.Debug("[USER MANAGEMENT MODULE]: GetServerURLs call failed ", e);
userdata.ServerURLs = new Dictionary<string, object>();
}
if (userdata.ServerURLs != null && userdata.ServerURLs.ContainsKey(serverType) && userdata.ServerURLs[serverType] != null)
return userdata.ServerURLs[serverType].ToString();
}
return string.Empty;
}
public virtual string GetUserUUI(UUID userID)
{
string uui;
GetUserUUI(userID, out uui);
return uui;
}
public virtual bool GetUserUUI(UUID userID, out string uui)
{
UserData ud;
bool result = GetUser(userID, out ud);
if (ud != null)
{
string homeURL = ud.HomeURL;
string first = ud.FirstName, last = ud.LastName;
if (ud.LastName.StartsWith("@"))
{
string[] parts = ud.FirstName.Split('.');
if (parts.Length >= 2)
{
first = parts[0];
last = parts[1];
}
uui = userID + ";" + homeURL + ";" + first + " " + last;
return result;
}
}
uui = userID.ToString();
return result;
}
#region Cache Management
public virtual bool GetUser(UUID uuid, out UserData userdata)
{
if(m_Scenes.Count <= 0)
{
userdata = new UserData();
return false;
}
lock (m_UserCache)
{
if (m_UserCache.TryGetValue(uuid, out userdata))
{
if (userdata.HasGridUserTried)
{
return true;
}
}
else
{
userdata = new UserData();
userdata.Id = uuid;
userdata.FirstName = "Unknown";
userdata.LastName = "UserUMMAU42";
userdata.HomeURL = string.Empty;
userdata.IsUnknownUser = true;
userdata.HasGridUserTried = false;
}
}
/* BEGIN: do not wrap this code in any lock here
* There are HTTP calls in here.
*/
if (!userdata.HasGridUserTried)
{
/* rewrite here */
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid);
if (account != null)
{
userdata.FirstName = account.FirstName;
userdata.LastName = account.LastName;
userdata.HomeURL = string.Empty;
userdata.IsUnknownUser = false;
userdata.HasGridUserTried = true;
}
}
if (!userdata.HasGridUserTried)
{
GridUserInfo uInfo = null;
if (null != m_Scenes[0].GridUserService)
{
uInfo = m_Scenes[0].GridUserService.GetGridUserInfo(uuid.ToString());
}
if (uInfo != null)
{
string url, first, last, tmp;
UUID u;
if(uInfo.UserID.Length <= 36)
{
/* not a UUI */
}
else if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out u, out url, out first, out last, out tmp))
{
if (url != string.Empty)
{
userdata.FirstName = first.Replace(" ", ".") + "." + last.Replace(" ", ".");
userdata.HomeURL = url;
try
{
userdata.LastName = "@" + new Uri(url).Authority;
userdata.IsUnknownUser = false;
}
catch
{
userdata.LastName = "@unknown";
}
userdata.HasGridUserTried = true;
}
}
else
m_log.DebugFormat("[USER MANAGEMENT MODULE]: Unable to parse UUI {0}", uInfo.UserID);
}
}
/* END: do not wrap this code in any lock here */
lock (m_UserCache)
{
m_UserCache[uuid] = userdata;
}
return !userdata.IsUnknownUser;
}
public virtual void AddUser(UUID uuid, string first, string last, bool isNPC = false)
{
lock(m_UserCache)
{
if(!m_UserCache.ContainsKey(uuid))
{
UserData user = new UserData();
user.Id = uuid;
user.FirstName = first;
user.LastName = last;
user.IsUnknownUser = false;
user.HasGridUserTried = isNPC;
m_UserCache.Add(uuid, user);
}
}
}
public virtual void AddUser(UUID uuid, string first, string last, string homeURL)
{
//m_log.DebugFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, first {1}, last {2}, url {3}", uuid, first, last, homeURL);
UserData oldUser;
lock (m_UserCache)
{
if (m_UserCache.TryGetValue(uuid, out oldUser))
{
if (!oldUser.IsUnknownUser)
{
if (homeURL != oldUser.HomeURL && m_DisplayChangingHomeURI)
{
m_log.DebugFormat("[USER MANAGEMENT MODULE]: Different HomeURI for {0} {1} ({2}): {3} and {4}",
first, last, uuid.ToString(), homeURL, oldUser.HomeURL);
}
/* no update needed */
return;
}
}
else if(!m_UserCache.ContainsKey(uuid))
{
oldUser = new UserData();
oldUser.HasGridUserTried = false;
oldUser.IsUnknownUser = false;
if (homeURL != string.Empty)
{
oldUser.FirstName = first.Replace(" ", ".") + "." + last.Replace(" ", ".");
try
{
oldUser.LastName = "@" + new Uri(homeURL).Authority;
oldUser.IsUnknownUser = false;
}
catch
{
oldUser.LastName = "@unknown";
}
}
else
{
oldUser.FirstName = first;
oldUser.LastName = last;
}
oldUser.HomeURL = homeURL;
oldUser.Id = uuid;
m_UserCache.Add(uuid, oldUser);
}
}
}
public virtual void AddUser(UUID id, string creatorData)
{
// m_log.InfoFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, creatorData {1}", id, creatorData);
if(string.IsNullOrEmpty(creatorData))
{
AddUser(id, string.Empty, string.Empty, string.Empty);
}
else
{
string homeURL;
string firstname = string.Empty;
string lastname = string.Empty;
//creatorData = <endpoint>;<name>
string[] parts = creatorData.Split(';');
if(parts.Length > 1)
{
string[] nameparts = parts[1].Split(' ');
firstname = nameparts[0];
for(int xi = 1; xi < nameparts.Length; ++xi)
{
if(xi != 1)
{
lastname += " ";
}
lastname += nameparts[xi];
}
}
else
{
firstname = "Unknown";
lastname = "UserUMMAU5";
}
if (parts.Length >= 1)
{
homeURL = parts[0];
if(Uri.IsWellFormedUriString(homeURL, UriKind.Absolute))
{
AddUser(id, firstname, lastname, homeURL);
}
else
{
m_log.DebugFormat("[SCENE]: Unable to parse Uri {0} for CreatorID {1}", parts[0], creatorData);
lock (m_UserCache)
{
if(!m_UserCache.ContainsKey(id))
{
UserData newUser = new UserData();
newUser.Id = id;
newUser.FirstName = firstname + "." + lastname.Replace(' ', '.');
newUser.LastName = "@unknown";
newUser.HomeURL = string.Empty;
newUser.HasGridUserTried = false;
newUser.IsUnknownUser = true; /* we mark those users as Unknown user so a re-retrieve may be activated */
m_UserCache.Add(id, newUser);
}
}
}
}
else
{
lock(m_UserCache)
{
if(!m_UserCache.ContainsKey(id))
{
UserData newUser = new UserData();
newUser.Id = id;
newUser.FirstName = "Unknown";
newUser.LastName = "UserUMMAU4";
newUser.HomeURL = string.Empty;
newUser.IsUnknownUser = true;
newUser.HasGridUserTried = false;
m_UserCache.Add(id, newUser);
}
}
}
}
}
#endregion
public virtual bool IsLocalGridUser(UUID uuid)
{
lock (m_Scenes)
{
if (m_Scenes.Count == 0)
return true;
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid);
if (account == null || (account != null && !account.LocalToGrid))
return false;
}
return true;
}
#endregion IUserManagement
protected virtual void Init()
{
AddUser(UUID.Zero, "Unknown", "User");
RegisterConsoleCmds();
}
protected virtual void RegisterConsoleCmds()
{
MainConsole.Instance.Commands.AddCommand("Users", true,
"show name",
"show name <uuid>",
"Show the bindings between a single user UUID and a user name",
String.Empty,
HandleShowUser);
MainConsole.Instance.Commands.AddCommand("Users", true,
"show names",
"show names",
"Show the bindings between user UUIDs and user names",
String.Empty,
HandleShowUsers);
MainConsole.Instance.Commands.AddCommand("Users", true,
"reset user cache",
"reset user cache",
"reset user cache to allow changed settings to be applied",
String.Empty,
HandleResetUserCache);
}
protected virtual void HandleResetUserCache(string module, string[] cmd)
{
lock(m_UserCache)
{
m_UserCache.Clear();
}
}
protected virtual void HandleShowUser(string module, string[] cmd)
{
if (cmd.Length < 3)
{
MainConsole.Instance.OutputFormat("Usage: show name <uuid>");
return;
}
UUID userId;
if (!ConsoleUtil.TryParseConsoleUuid(MainConsole.Instance, cmd[2], out userId))
return;
UserData ud;
if(!GetUser(userId, out ud))
{
MainConsole.Instance.OutputFormat("No name known for user with id {0}", userId);
return;
}
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("UUID", 36);
cdt.AddColumn("Name", 30);
cdt.AddColumn("HomeURL", 40);
cdt.AddRow(userId, string.Format("{0} {1}", ud.FirstName, ud.LastName), ud.HomeURL);
MainConsole.Instance.Output(cdt.ToString());
}
protected virtual void HandleShowUsers(string module, string[] cmd)
{
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("UUID", 36);
cdt.AddColumn("Name", 30);
cdt.AddColumn("HomeURL", 40);
cdt.AddColumn("Checked", 10);
Dictionary<UUID, UserData> copyDict;
lock(m_UserCache)
{
copyDict = new Dictionary<UUID, UserData>(m_UserCache);
}
foreach(KeyValuePair<UUID, UserData> kvp in copyDict)
{
cdt.AddRow(kvp.Key, string.Format("{0} {1}", kvp.Value.FirstName, kvp.Value.LastName), kvp.Value.HomeURL, kvp.Value.HasGridUserTried ? "yes" : "no");
}
MainConsole.Instance.Output(cdt.ToString());
}
}
}
| |
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Avalonia.Animation;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Utils;
using Avalonia.Data;
namespace Avalonia.Controls.Presenters
{
/// <summary>
/// Displays pages inside an <see cref="ItemsControl"/>.
/// </summary>
public class CarouselPresenter : ItemsPresenterBase
{
/// <summary>
/// Defines the <see cref="IsVirtualized"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsVirtualizedProperty =
Carousel.IsVirtualizedProperty.AddOwner<CarouselPresenter>();
/// <summary>
/// Defines the <see cref="SelectedIndex"/> property.
/// </summary>
public static readonly DirectProperty<CarouselPresenter, int> SelectedIndexProperty =
SelectingItemsControl.SelectedIndexProperty.AddOwner<CarouselPresenter>(
o => o.SelectedIndex,
(o, v) => o.SelectedIndex = v);
/// <summary>
/// Defines the <see cref="PageTransition"/> property.
/// </summary>
public static readonly StyledProperty<IPageTransition> PageTransitionProperty =
Carousel.PageTransitionProperty.AddOwner<CarouselPresenter>();
private int _selectedIndex = -1;
private Task _currentTransition;
private int _queuedTransitionIndex = -1;
/// <summary>
/// Initializes static members of the <see cref="CarouselPresenter"/> class.
/// </summary>
static CarouselPresenter()
{
IsVirtualizedProperty.Changed.AddClassHandler<CarouselPresenter>((x, e) => x.IsVirtualizedChanged(e));
SelectedIndexProperty.Changed.AddClassHandler<CarouselPresenter>((x, e) => x.SelectedIndexChanged(e));
}
/// <summary>
/// Gets or sets a value indicating whether the items in the carousel are virtualized.
/// </summary>
/// <remarks>
/// When the carousel is virtualized, only the active page is held in memory.
/// </remarks>
public bool IsVirtualized
{
get { return GetValue(IsVirtualizedProperty); }
set { SetValue(IsVirtualizedProperty, value); }
}
/// <summary>
/// Gets or sets the index of the selected page.
/// </summary>
public int SelectedIndex
{
get
{
return _selectedIndex;
}
set
{
var old = SelectedIndex;
var effective = (value >= 0 && value < Items?.Cast<object>().Count()) ? value : -1;
if (old != effective)
{
_selectedIndex = effective;
RaisePropertyChanged(SelectedIndexProperty, old, effective, BindingPriority.LocalValue);
}
}
}
/// <summary>
/// Gets or sets a transition to use when switching pages.
/// </summary>
public IPageTransition PageTransition
{
get { return GetValue(PageTransitionProperty); }
set { SetValue(PageTransitionProperty, value); }
}
/// <inheritdoc/>
protected override void ItemsChanged(NotifyCollectionChangedEventArgs e)
{
if (!IsVirtualized)
{
base.ItemsChanged(e);
if (Items == null || SelectedIndex >= Items.Count())
{
SelectedIndex = Items.Count() - 1;
}
foreach (var c in ItemContainerGenerator.Containers)
{
c.ContainerControl.IsVisible = c.Index == SelectedIndex;
}
}
else if (SelectedIndex != -1 && Panel != null)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
if (e.NewStartingIndex > SelectedIndex)
{
return;
}
break;
case NotifyCollectionChangedAction.Remove:
if (e.OldStartingIndex > SelectedIndex)
{
return;
}
break;
case NotifyCollectionChangedAction.Replace:
if (e.OldStartingIndex > SelectedIndex ||
e.OldStartingIndex + e.OldItems.Count - 1 < SelectedIndex)
{
return;
}
break;
case NotifyCollectionChangedAction.Move:
if (e.OldStartingIndex > SelectedIndex &&
e.NewStartingIndex > SelectedIndex)
{
return;
}
break;
}
if (Items == null || SelectedIndex >= Items.Count())
{
SelectedIndex = Items.Count() - 1;
}
Panel.Children.Clear();
ItemContainerGenerator.Clear();
if (SelectedIndex != -1)
{
GetOrCreateContainer(SelectedIndex);
}
}
}
protected override void PanelCreated(IPanel panel)
{
ItemsChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
/// <summary>
/// Moves to the selected page, animating if a <see cref="PageTransition"/> is set.
/// </summary>
/// <param name="fromIndex">The index of the old page.</param>
/// <param name="toIndex">The index of the new page.</param>
/// <returns>A task tracking the animation.</returns>
private async Task MoveToPage(int fromIndex, int toIndex)
{
if (fromIndex != toIndex)
{
var generator = ItemContainerGenerator;
IControl from = null;
IControl to = null;
if (fromIndex != -1)
{
from = ItemContainerGenerator.ContainerFromIndex(fromIndex);
}
if (toIndex != -1)
{
to = GetOrCreateContainer(toIndex);
}
if (PageTransition != null && (from != null || to != null))
{
await PageTransition.Start((Visual)from, (Visual)to, fromIndex < toIndex, default);
}
else if (to != null)
{
to.IsVisible = true;
}
if (from != null)
{
if (IsVirtualized)
{
Panel.Children.Remove(from);
generator.Dematerialize(fromIndex, 1);
}
else
{
from.IsVisible = false;
}
}
}
}
private IControl GetOrCreateContainer(int index)
{
var container = ItemContainerGenerator.ContainerFromIndex(index);
if (container == null && IsVirtualized)
{
var item = Items.Cast<object>().ElementAt(index);
var materialized = ItemContainerGenerator.Materialize(index, item);
Panel.Children.Add(materialized.ContainerControl);
container = materialized.ContainerControl;
}
return container;
}
/// <summary>
/// Called when the <see cref="IsVirtualized"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private void IsVirtualizedChanged(AvaloniaPropertyChangedEventArgs e)
{
if (Panel != null)
{
ItemsChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
/// <summary>
/// Called when the <see cref="SelectedIndex"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private async void SelectedIndexChanged(AvaloniaPropertyChangedEventArgs e)
{
if (Panel != null)
{
if (_currentTransition == null)
{
int fromIndex = (int)e.OldValue;
int toIndex = (int)e.NewValue;
for (;;)
{
_currentTransition = MoveToPage(fromIndex, toIndex);
await _currentTransition;
if (_queuedTransitionIndex != -1)
{
fromIndex = toIndex;
toIndex = _queuedTransitionIndex;
_queuedTransitionIndex = -1;
}
else
{
_currentTransition = null;
break;
}
}
}
else
{
_queuedTransitionIndex = (int)e.NewValue;
}
}
}
}
}
| |
//
// Entity.cs
//
// Author:
// Rik <>
//
// Copyright (c) 2014 Rik
//
// 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 UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public abstract class Entity : FContainer
{
Vector2 oldPosition;
public Vector2 velocity;
Vector2 lastMovement;
public float impactRotation;
Vector2 position;
Vector2 maxSpeed;
Vector2 size;
int facing;
float gravity;
float movementSpeed = 80f;
float runningSpeed = 120f;
float normalSpeed = 80f;
float floorFriction;
float airFriction;
float jumpImpulse;
//the smaller this value, the bigger the rectBounds will check
public int detectionAccuracy = 6;
public Rectangle boundingBox, impactBoundingBox, offsetOnePixel;
bool active, remove;
bool isJumping, wasJumping;
FSprite sprite;
int healthPoints, totalPoints;
int scorePoints;
bool needsReset;
bool isPaused;
public Vector2 Velocity { get { return velocity; } set { velocity = value; } }
public Vector2 Position { get { return position; } set { position = value; } }
public Vector2 OldPosition { get { return oldPosition; } set { oldPosition = value; } }
public Vector2 MaxSpeed { get { return maxSpeed; } set { maxSpeed = value; } }
public Vector2 Size { get { return size; } set { size = value; } }
public Vector2 LastMovement { get { return lastMovement; } set { lastMovement = value; } }
public float Gravity { get { return gravity; } set { gravity = value; } }
public float JumpImpulse { get { return jumpImpulse; } set { jumpImpulse = value; } }
public float MovementSpeed { get { return movementSpeed; } set { movementSpeed = value; } }
public float NormalSpeed { get { return normalSpeed; } set { normalSpeed = value; } }
public float RunningSpeed { get { return runningSpeed; } set { runningSpeed = value; } }
public float AirFriction { get { return airFriction; } set { airFriction = value; } }
public float FloorFriction { get { return floorFriction; } set { floorFriction = value; } }
public int DetectionAccuracy { get { return detectionAccuracy; } set { detectionAccuracy = value; } }
public int Facing { get { return facing; } set { facing = value; } }
public bool IsJumping { get { return isJumping; } set { isJumping = value; } }
public bool WasJumping { get { return wasJumping; } set { wasJumping = value; } }
public bool isActive { get { return active; } set { active = value; } }
public bool Remove { get { return remove; } set { remove = value; } }
public bool canJump { get; set; }
public bool useGravity { get; set; }
public bool noClip { get; set; }
public FSprite Texture { get { return sprite; } set { sprite = value; } }
public int HealthPoints { get { return healthPoints; } set { healthPoints = value; } }
public int TotalPoints { get { return totalPoints; } set { totalPoints = value; } }
public int ScorePoints { get { return scorePoints; } set { scorePoints = value; } }
public bool NeedsReset { get { return needsReset; } set { needsReset = value; } }
public bool IsPaused { get { return isPaused; } set { isPaused = value; } }
public bool DeadLogic { get { return deadLogic; } set { deadLogic = value; } }
public bool running;
float currentTime;
bool deadLogic;
public float timeToWait;
public Entity()
{
}
public enum EntityState
{
onJump,
onDoubleJump,
onGround,
onAir
}
public virtual void Init() { }
public virtual void CheckAndUpdateMovement()
{
}
public void MoveAsFarAsPossible()
{
oldPosition = position;
UpdatePosition();
position = TileMap.CurrentMap.WhereCanIGetTo(oldPosition, position, getAABBBoundingBox());
}
public void UpdatePosition()
{
position += velocity;
}
public virtual void applyGravity()
{
if (!useGravity)
return;
velocity -= Vector2.up * gravity * Time.deltaTime;
}
public virtual void applyFriction()
{
// applies friction based on the last type of tile detected?. Of if the entity is not grounded.
if (Ground())
{
velocity.x -= velocity.x * FloorFriction;
}
else
{
velocity.x -= velocity.x * AirFriction;
}
}
public virtual void Update()
{
CheckAndUpdateMovement();
applyGravity();
applyFriction();
MoveAsFarAsPossible();
StopMovingIfBlocked();
SetPosition(position);
currentTime = timeToWait - Time.time;
if (currentTime > 0)
return;
RemoveHitEffect();
}
public virtual void WorldWrap()
{
var wrap = TileMap.CurrentMap.WordWrap(getAABBBoundingBox());
if (wrap != Vector2.zero)
{
if (wrap.x != 0)
Position = new Vector2(wrap.x, Position.y);
if (wrap.y != 0)
Position = new Vector2(Position.x, wrap.y);
}
}
public virtual void StopMovingIfBlocked()
{
lastMovement = position - oldPosition;
if (lastMovement.x == 0) { velocity.x = 0; }
if (lastMovement.y == 0) { velocity.y = 0; }
}
public void Destroy()
{
Remove = true;
RemoveFromContainer();
}
public Rectangle getAABBBoundingBox()
{
boundingBox.setValues(position.x, position.y, size.x, size.y);
return boundingBox;
}
// returns entitys actual position in tiles.
public Vector2 PositionOnTileMap()
{
return new Vector2(TileMap.CurrentMap.pixelsToTiles(Position.x), TileMap.CurrentMap.pixelsToTiles(Position.y));
}
//https://docs.unity3d.com/Documentation/ScriptReference/Rectangle.html
public bool Ground()
{
offsetOnePixel = getAABBBoundingBox();
offsetOnePixel.y -= offsetOnePixel.h/detectionAccuracy;
offsetOnePixel.w *= 0.8f;
bool val = !TileMap.CurrentMap.HasRoomForRectangle(offsetOnePixel);
return val;
}
public bool Ceiling()
{
offsetOnePixel = getAABBBoundingBox();
offsetOnePixel.y += offsetOnePixel.h / detectionAccuracy;
offsetOnePixel.w *= 0.8f;
return !TileMap.CurrentMap.HasRoomForRectangle(offsetOnePixel);
}
public bool LeftWall()
{
offsetOnePixel = getAABBBoundingBox();
offsetOnePixel.x -= offsetOnePixel.w / detectionAccuracy;
offsetOnePixel.y += offsetOnePixel.h / detectionAccuracy;
offsetOnePixel.h *= 0.8f;
return !TileMap.CurrentMap.HasRoomForRectangle(offsetOnePixel);
}
public bool RightWall()
{
offsetOnePixel = getAABBBoundingBox();
offsetOnePixel.x +=offsetOnePixel.w / detectionAccuracy;
offsetOnePixel.y += offsetOnePixel.h / detectionAccuracy;
offsetOnePixel.h *= 0.8f;
return !TileMap.CurrentMap.HasRoomForRectangle(offsetOnePixel);
}
public void SubstractLife(int value) {
}
public virtual void DoHitEffect() {
}
public virtual void RemoveHitEffect() {
}
public void WaitSeconds(float ammount)
{
timeToWait = Time.time + ammount;
}
// this code is by mylesmar10
public void drawHitBox(Rectangle Rectangle, Color color)
{
Vector3 tL = new Vector3(0f, 0f, 0f);
Vector3 tR = new Vector3(0f, 0f, 0f);
Vector3 bL = new Vector3(0f, 0f, 0f);
Vector3 bR = new Vector3(0f, 0f, 0f);
tL.x = Rectangle.x;
tL.y = Rectangle.y;
tR.x = Rectangle.x + Rectangle.w;
tR.y = Rectangle.y;
bL.x = Rectangle.x;
bL.y = Rectangle.y + Rectangle.h;
bR.x = Rectangle.x + Rectangle.w;
bR.y = Rectangle.y + Rectangle.h;
Debug.DrawLine(tL, tR, color);
Debug.DrawLine(tR, bR, color);
Debug.DrawLine(bR, bL, color);
Debug.DrawLine(bL, tL, color);
}
}
| |
// 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.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ScenarioTests.Common;
using Xunit;
public static class ServiceContractTests
{
[Fact]
[OuterLoop]
public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_Buffered()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.TransferMode = TransferMode.Buffered;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStream(stream);
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_StreamedRequest()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.TransferMode = TransferMode.StreamedRequest;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var result = serviceProxy.GetStringFromStream(stream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_StreamedResponse()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.TransferMode = TransferMode.StreamedResponse;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
var returnStream = serviceProxy.GetStreamFromString(testString);
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.TransferMode = TransferMode.Streamed;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStream(stream);
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_Async()
{
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.TransferMode = TransferMode.Streamed;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStreamAsync(stream).Result;
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_WithSingleThreadedSyncContext timed-out.");
}
[Fact]
[OuterLoop]
public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_Async_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_Async(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_Async_WithSingleThreadedSyncContext timed-out.");
}
[Fact]
[OuterLoop]
public static void BasicHttp_Streamed_Async_Delayed_And_Aborted_Request_Throws_TimeoutException()
{
// This test is a regression test that verifies an issue discovered where exceeding the timeout
// and aborting the channel before the client's Task completed led to incorrect error handling.
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
int sendTimeoutMs = 3000;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.TransferMode = TransferMode.Streamed;
binding.SendTimeout = TimeSpan.FromMilliseconds(sendTimeoutMs);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
// Create a read stream that will both timeout and then abort the proxy channel when the
// async read is called. We also intercept the synchronous read because that path can also
// be executed during an async read.
stream = new TestMockStream()
{
CopyToAsyncFunc = (Stream destination, int bufferSize, CancellationToken ct) =>
{
// Abort to force the internal HttpClientChannelAsyncRequest.Cleanup()
// to clear its data structures before the client's Task completes.
Task.Delay(sendTimeoutMs * 2).Wait();
((ICommunicationObject)serviceProxy).Abort();
return null;
},
ReadFunc = (byte[] buffer, int offset, int count) =>
{
// Abort to force the internal HttpClientChannelAsyncRequest.Cleanup()
// to clear its data structures before the client's Task completes.
Task.Delay(sendTimeoutMs * 2).Wait();
((ICommunicationObject)serviceProxy).Abort();
return -1;
}
};
// *** EXECUTE *** \\
Assert.Throws<TimeoutException>(() =>
{
var unused = serviceProxy.EchoStreamAsync(stream).GetAwaiter().GetResult();
});
// *** VALIDATE *** \\
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_Streamed_Async_Delayed_Request_Throws_TimeoutException()
{
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
int sendTimeoutMs = 3000;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.TransferMode = TransferMode.Streamed;
binding.SendTimeout = TimeSpan.FromMilliseconds(sendTimeoutMs);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
// Create a read stream that deliberately times out during the async read during the request.
// We also intercept the synchronous read because that path can also be executed during
// an async read.
stream = new TestMockStream()
{
CopyToAsyncFunc = (Stream destination, int bufferSize, CancellationToken ct) =>
{
Task.Delay(sendTimeoutMs * 2).Wait();
return null;
},
ReadFunc = (byte[] buffer, int offset, int count) =>
{
Task.Delay(sendTimeoutMs * 2).Wait();
return -1;
}
};
// *** EXECUTE *** \\
Assert.Throws<TimeoutException>(() =>
{
var unused = serviceProxy.EchoStreamAsync(stream).GetAwaiter().GetResult();
});
// *** VALIDATE *** \\
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void NetTcp_NoSecurity_Buffered_RoundTrips_String()
{
string testString = "Hello";
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.None);
binding.TransferMode = TransferMode.Buffered;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStream(stream);
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void NetTcp_NoSecurity_StreamedRequest_RoundTrips_String()
{
string testString = "Hello";
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = binding = new NetTcpBinding(SecurityMode.None);
binding.TransferMode = TransferMode.StreamedRequest;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var result = serviceProxy.GetStringFromStream(stream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void NetTcp_NoSecurity_StreamedResponse_RoundTrips_String()
{
string testString = "Hello";
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.None);
binding.TransferMode = TransferMode.StreamedResponse;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
var returnStream = serviceProxy.GetStreamFromString(testString);
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void NetTcp_NoSecurity_Streamed_RoundTrips_String()
{
string testString = "Hello";
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.None);
binding.TransferMode = TransferMode.Streamed;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStream(stream);
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void NetTcp_NoSecurity_Streamed_Async_RoundTrips_String()
{
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.None);
binding.TransferMode = TransferMode.Streamed;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStreamAsync(stream).Result;
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void NetTcp_NoSecurity_StreamedRequest_Async_RoundTrips_String()
{
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.None);
binding.TransferMode = TransferMode.StreamedRequest;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStreamAsync(stream).Result;
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void NetTcp_NoSecurity_StreamedResponse_Async_RoundTrips_String()
{
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.None);
binding.TransferMode = TransferMode.StreamedResponse;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStreamAsync(stream).Result;
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void NetTcp_NoSecurity_Streamed_RoundTrips_String_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.NetTcp_NoSecurity_Streamed_RoundTrips_String(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: NetTcp_NoSecurity_String_Streamed_RoundTrips_WithSingleThreadedSyncContext timed-out.");
}
[Fact]
[OuterLoop]
public static void NetTcp_NoSecurity_Streamed_Async_RoundTrips_String_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.NetTcp_NoSecurity_Streamed_Async_RoundTrips_String(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: NetTcp_NoSecurity_Streamed_Async_RoundTrips_String_WithSingleThreadedSyncContext timed-out.");
}
[Fact]
[OuterLoop]
public static void ServiceContract_Call_Operation_With_MessageParameterAttribute()
{
// This test verifies the scenario where MessageParameter attribute is used in the contract
StringBuilder errorBuilder = new StringBuilder();
ChannelFactory<IWcfServiceGenerated> factory = null;
IWcfServiceGenerated serviceProxy = null;
try
{
// *** SETUP *** \\
CustomBinding customBinding = new CustomBinding();
customBinding.Elements.Add(new TextMessageEncodingBindingElement());
customBinding.Elements.Add(new HttpTransportBindingElement());
// Note the service interface used. It was manually generated with svcutil.
factory = new ChannelFactory<IWcfServiceGenerated>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string echoString = "you";
string result = serviceProxy.EchoMessageParameter(echoString);
// *** VALIDATE *** \\
Assert.True(string.Equals(result, "Hello " + echoString), String.Format("Expected response from Service: {0} Actual was: {1}", "Hello " + echoString, result));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// End operation includes keyword "out" on an Int as an arg.
[Fact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncEndOperation_IntOutArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractIntOutService> factory = null;
IServiceContractIntOutService serviceProxy = null;
int number = 0;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractIntOutService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncIntOut_Address));
serviceProxy = factory.CreateChannel();
ManualResetEvent waitEvent = new ManualResetEvent(false);
// *** EXECUTE *** \\
// This delegate will execute when the call has completed, which is how we get the result of the call.
AsyncCallback callback = (iar) =>
{
serviceProxy.EndRequest(out number, iar);
waitEvent.Set();
};
IAsyncResult ar = serviceProxy.BeginRequest(message, callback, null);
// *** VALIDATE *** \\
Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called.");
Assert.True((number == message.Count<char>()), String.Format("The local int variable was not correctly set, expected {0} but got {1}", message.Count<char>(), number));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// End operation includes keyword "out" on a unique type as an arg.
// The unique type used must not appear anywhere else in any contracts in order
// test the static analysis logic of the Net Native toolchain.
[Fact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncEndOperation_UniqueTypeOutArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractUniqueTypeOutService> factory = null;
IServiceContractUniqueTypeOutService serviceProxy = null;
UniqueType uniqueType = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractUniqueTypeOutService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncUniqueTypeOut_Address));
serviceProxy = factory.CreateChannel();
ManualResetEvent waitEvent = new ManualResetEvent(false);
// *** EXECUTE *** \\
// This delegate will execute when the call has completed, which is how we get the result of the call.
AsyncCallback callback = (iar) =>
{
serviceProxy.EndRequest(out uniqueType, iar);
waitEvent.Set();
};
IAsyncResult ar = serviceProxy.BeginRequest(message, callback, null);
// *** VALIDATE *** \\
Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called.");
Assert.True((uniqueType.stringValue == message),
String.Format("The 'stringValue' field in the instance of 'UniqueType' was not as expected. expected {0} but got {1}", message, uniqueType.stringValue));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// End & Begin operations include keyword "ref" on an Int as an arg.
[Fact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncEndOperation_IntRefArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractIntRefService> factory = null;
IServiceContractIntRefService serviceProxy = null;
int number = 0;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractIntRefService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncIntRef_Address));
serviceProxy = factory.CreateChannel();
ManualResetEvent waitEvent = new ManualResetEvent(false);
// *** EXECUTE *** \\
// This delegate will execute when the call has completed, which is how we get the result of the call.
AsyncCallback callback = (iar) =>
{
serviceProxy.EndRequest(ref number, iar);
waitEvent.Set();
};
IAsyncResult ar = serviceProxy.BeginRequest(message, ref number, callback, null);
// *** VALIDATE *** \\
Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called.");
Assert.True((number == message.Count<char>()),
String.Format("The value of the integer sent by reference was not the expected value. expected {0} but got {1}", message.Count<char>(), number));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// End & Begin operations include keyword "ref" on a unique type as an arg.
// The unique type used must not appear anywhere else in any contracts in order
// test the static analysis logic of the Net Native toolchain.
[Fact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncEndOperation_UniqueTypeRefArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractUniqueTypeRefService> factory = null;
IServiceContractUniqueTypeRefService serviceProxy = null;
UniqueType uniqueType = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractUniqueTypeRefService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncUniqueTypeRef_Address));
serviceProxy = factory.CreateChannel();
ManualResetEvent waitEvent = new ManualResetEvent(false);
// *** EXECUTE *** \\
// This delegate will execute when the call has completed, which is how we get the result of the call.
AsyncCallback callback = (iar) =>
{
serviceProxy.EndRequest(ref uniqueType, iar);
waitEvent.Set();
};
IAsyncResult ar = serviceProxy.BeginRequest(message, ref uniqueType, callback, null);
// *** VALIDATE *** \\
Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called.");
Assert.True((uniqueType.stringValue == message),
String.Format("The 'stringValue' field in the instance of 'UniqueType' was not as expected. expected {0} but got {1}", message, uniqueType.stringValue));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// Synchronous operation using the keyword "out" on a unique type as an arg.
// The unique type used must not appear anywhere else in any contracts in order
// test the static analysis logic of the Net Native toolchain.
[Fact]
[OuterLoop]
public static void ServiceContract_TypedProxy_SyncOperation_UniqueTypeOutArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractUniqueTypeOutSyncService> factory = null;
IServiceContractUniqueTypeOutSyncService serviceProxy = null;
UniqueType uniqueType = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractUniqueTypeOutSyncService>(binding, new EndpointAddress(Endpoints.ServiceContractSyncUniqueTypeOut_Address));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
serviceProxy.Request(message, out uniqueType);
// *** VALIDATE *** \\
Assert.True((uniqueType.stringValue == message),
String.Format("The value of the 'stringValue' field in the UniqueType instance was not as expected. expected {0} but got {1}", message, uniqueType.stringValue));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// Synchronous operation using the keyword "ref" on a unique type as an arg.
// The unique type used must not appear anywhere else in any contracts in order
// test the static analysis logic of the Net Native toolchain.
[Fact]
[OuterLoop]
public static void ServiceContract_TypedProxy_SyncOperation_UniqueTypeRefArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractUniqueTypeRefSyncService> factory = null;
IServiceContractUniqueTypeRefSyncService serviceProxy = null;
UniqueType uniqueType = new UniqueType();
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractUniqueTypeRefSyncService>(binding, new EndpointAddress(Endpoints.ServiceContractSyncUniqueTypeRef_Address));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
serviceProxy.Request(message, ref uniqueType);
// *** VALIDATE *** \\
Assert.True((uniqueType.stringValue == message),
String.Format("The value of the 'stringValue' field in the UniqueType instance was not as expected. expected {0} but got {1}", message, uniqueType.stringValue));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_Async_Open_ChannelFactory()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
string result = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.OpenTimeout = ScenarioTestHelpers.TestTimeout;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
// *** EXECUTE *** \\
Task t = Task.Factory.FromAsync(factory.BeginOpen, factory.EndOpen, TaskCreationOptions.None);
// *** VALIDATE *** \\
t.GetAwaiter().GetResult();
Assert.True(factory.State == CommunicationState.Opened,
String.Format("Expected factory state 'Opened', actual was '{0}'", factory.State));
serviceProxy = factory.CreateChannel();
result = serviceProxy.Echo(testString); // verifies factory did open correctly
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_Async_Open_ChannelFactory_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_Async_Open_ChannelFactory(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: BasicHttp_Async_Open_ChannelFactory_WithSingleThreadedSyncContext timed-out.");
}
[Fact]
[OuterLoop]
public static void BasicHttp_Async_Open_Proxy()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
string result = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
ICommunicationObject proxyAsCommunicationObject = (ICommunicationObject)serviceProxy;
Task t = Task.Factory.FromAsync(proxyAsCommunicationObject.BeginOpen, proxyAsCommunicationObject.EndOpen, TaskCreationOptions.None);
// *** VALIDATE *** \\
t.GetAwaiter().GetResult();
Assert.True(proxyAsCommunicationObject.State == CommunicationState.Opened,
String.Format("Expected proxy state 'Opened', actual was '{0}'", proxyAsCommunicationObject.State));
result = serviceProxy.Echo(testString); // verifies proxy did open correctly
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_Async_Open_Proxy_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_Async_Open_Proxy(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: BasicHttp_Async_Open_Proxy_WithSingleThreadedSyncContext timed-out.");
}
[Fact]
[OuterLoop]
public static void BasicHttp_Async_Close_ChannelFactory()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
string result = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.CloseTimeout = ScenarioTestHelpers.TestTimeout;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
result = serviceProxy.Echo(testString); // force proxy and factory to open as part of setup
((ICommunicationObject)serviceProxy).Close(); // force proxy closed before close factory
// *** EXECUTE *** \\
Task t = Task.Factory.FromAsync(factory.BeginClose, factory.EndClose, TaskCreationOptions.None);
// *** VALIDATE *** \\
t.GetAwaiter().GetResult();
Assert.True(factory.State == CommunicationState.Closed,
String.Format("Expected factory state 'Closed', actual was '{0}'", factory.State));
// *** CLEANUP *** \\
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_Async_Close_ChannelFactory_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_Async_Close_ChannelFactory(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: BasicHttp_Async_Close_ChannelFactory_WithSingleThreadedSyncContext timed-out.");
}
[Fact]
[OuterLoop]
public static void BasicHttp_Async_Close_Proxy()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
serviceProxy.Echo(testString); // force sync open as part of setup
// *** EXECUTE *** \\
ICommunicationObject proxyAsCommunicationObject = (ICommunicationObject)serviceProxy;
Task t = Task.Factory.FromAsync(proxyAsCommunicationObject.BeginClose, proxyAsCommunicationObject.EndClose, TaskCreationOptions.None);
// *** VALIDATE *** \\
t.GetAwaiter().GetResult();
Assert.True(proxyAsCommunicationObject.State == CommunicationState.Closed,
String.Format("Expected proxy state 'Closed', actual was '{0}'", proxyAsCommunicationObject.State));
// *** CLEANUP *** \\
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[OuterLoop]
public static void BasicHttp_Async_Close_Proxy_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_Async_Close_Proxy(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: BasicHttp_Async_Close_Proxy_WithSingleThreadedSyncContext timed-out.");
}
private static void PrintInnerExceptionsHresult(Exception e, StringBuilder errorBuilder)
{
if (e.InnerException != null)
{
errorBuilder.AppendLine(string.Format("\r\n InnerException type: '{0}', Hresult:'{1}'", e.InnerException, e.InnerException.HResult));
PrintInnerExceptionsHresult(e.InnerException, errorBuilder);
}
}
private static string StreamToString(Stream stream)
{
var reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd();
}
private static Stream StringToStream(string str)
{
var ms = new MemoryStream();
var sw = new StreamWriter(ms, Encoding.UTF8);
sw.Write(str);
sw.Flush();
ms.Position = 0;
return ms;
}
}
| |
using UnityEngine;
using System.Collections;
namespace tk2dRuntime.TileMap
{
[System.Serializable]
public class LayerSprites
{
public int[] spriteIds;
public LayerSprites()
{
spriteIds = new int[0];
}
}
[System.Serializable]
public class SpriteChunk
{
bool dirty;
public int[] spriteIds;
public GameObject gameObject;
public Mesh mesh;
public MeshCollider meshCollider;
public Mesh colliderMesh;
public SpriteChunk() { spriteIds = new int[0]; }
public bool Dirty
{
get { return dirty; }
set { dirty = value; }
}
public bool IsEmpty
{
get { return spriteIds.Length == 0; }
}
public bool HasGameData
{
get { return gameObject != null || mesh != null || meshCollider != null || colliderMesh != null; }
}
public void DestroyGameData(tk2dTileMap tileMap)
{
if (mesh != null) tileMap.DestroyMesh(mesh);
if (gameObject != null) GameObject.DestroyImmediate(gameObject);
gameObject = null;
mesh = null;
DestroyColliderData(tileMap);
}
public void DestroyColliderData(tk2dTileMap tileMap)
{
if (colliderMesh != null)
tileMap.DestroyMesh(colliderMesh);
if (meshCollider != null && meshCollider.sharedMesh != null && meshCollider.sharedMesh != colliderMesh)
tileMap.DestroyMesh(meshCollider.sharedMesh);
if (meshCollider != null) GameObject.DestroyImmediate(meshCollider);
meshCollider = null;
colliderMesh = null;
}
}
[System.Serializable]
public class SpriteChannel
{
public SpriteChunk[] chunks;
public SpriteChannel() { chunks = new SpriteChunk[0]; }
}
[System.Serializable]
public class ColorChunk
{
public bool Dirty { get; set; }
public bool Empty { get { return colors.Length == 0; } }
public Color32[] colors;
public ColorChunk() { colors = new Color32[0]; }
}
[System.Serializable]
public class ColorChannel
{
public ColorChannel(int width, int height, int divX, int divY)
{
Init(width, height, divX, divY);
}
public Color clearColor = Color.white;
public ColorChunk[] chunks;
public ColorChannel() { chunks = new ColorChunk[0]; }
public void Init(int width, int height, int divX, int divY)
{
numColumns = (width + divX - 1) / divX;
numRows = (height + divY - 1) / divY;
chunks = new ColorChunk[0];
this.divX = divX;
this.divY = divY;
}
public ColorChunk FindChunkAndCoordinate(int x, int y, out int offset)
{
int cellX = Mathf.Max(x - 1, 0) / divX;
int cellY = Mathf.Max(y - 1, 0) / divY;
int idx = cellY * numColumns + cellX;
var chunk = chunks[idx];
int localX = x - cellX * divX;
int localY = y - cellY * divY;
offset = localY * (divX + 1) + localX;
return chunk;
}
public Color GetColor(int x, int y)
{
if (IsEmpty)
return clearColor;
int offset;
var chunk = FindChunkAndCoordinate(x, y, out offset);
if (chunk.colors.Length == 0)
return clearColor;
else
return chunk.colors[offset];
}
// create chunk if it doesn't already exist
void InitChunk(ColorChunk chunk)
{
if (chunk.colors.Length == 0)
{
chunk.colors = new Color32[(divX + 1) * (divY + 1)];
for (int i = 0; i < chunk.colors.Length; ++i)
chunk.colors[i] = clearColor;
}
}
public void SetColor(int x, int y, Color color)
{
if (IsEmpty)
Create();
int cellLocalWidth = divX + 1;
// at edges, set to all overlapping coordinates
int cellX = Mathf.Max(x - 1, 0) / divX;
int cellY = Mathf.Max(y - 1, 0) / divY;
var chunk = GetChunk(cellX, cellY, true);
int localX = x - cellX * divX;
int localY = y - cellY * divY;
chunk.colors[localY * cellLocalWidth + localX] = color;
chunk.Dirty = true;
// May need to set it to adjancent cells too
bool needX = false, needY = false;
if (x != 0 && (x % divX) == 0 && (cellX + 1) < numColumns)
needX = true;
if (y != 0 && (y % divY) == 0 && (cellY + 1) < numRows)
needY = true;
if (needX)
{
int cx = cellX + 1;
chunk = GetChunk(cx, cellY, true);
localX = x - cx * divX;
localY = y - cellY * divY;
chunk.colors[localY * cellLocalWidth + localX] = color;
}
if (needY)
{
int cy = cellY + 1;
chunk = GetChunk(cellX, cy, true);
localX = x - cellX * divX;
localY = y - cy * divY;
chunk.colors[localY * cellLocalWidth + localX] = color;
}
if (needX && needY)
{
int cx = cellX + 1;
int cy = cellY + 1;
chunk = GetChunk(cx, cy, true);
localX = x - cx * divX;
localY = y - cy * divY;
chunk.colors[localY * cellLocalWidth + localX] = color;
}
}
public ColorChunk GetChunk(int x, int y)
{
if (chunks == null || chunks.Length == 0)
return null;
return chunks[y * numColumns + x];
}
public ColorChunk GetChunk(int x, int y, bool init)
{
if (chunks == null || chunks.Length == 0)
return null;
var chunk = chunks[y * numColumns + x];
InitChunk(chunk);
return chunk;
}
public void ClearChunk(ColorChunk chunk)
{
for (int i = 0; i < chunk.colors.Length; ++i)
chunk.colors[i] = clearColor;
}
public void ClearDirtyFlag()
{
foreach (var chunk in chunks)
chunk.Dirty = false;
}
public void Clear(Color color)
{
clearColor = color;
foreach (var chunk in chunks)
ClearChunk(chunk);
Optimize();
}
public void Delete()
{
chunks = new ColorChunk[0];
}
public void Create()
{
chunks = new ColorChunk[numColumns * numRows];
for (int i = 0; i < chunks.Length; ++i)
chunks[i] = new ColorChunk();
}
void Optimize(ColorChunk chunk)
{
bool empty = true;
Color32 clearColor32 = this.clearColor;
foreach (var c in chunk.colors)
{
if (c.r != clearColor32.r ||
c.g != clearColor32.g ||
c.b != clearColor32.b ||
c.a != clearColor32.a)
{
empty = false;
break;
}
}
if (empty)
chunk.colors = new Color32[0];
}
public void Optimize()
{
foreach (var chunk in chunks)
Optimize(chunk);
}
public bool IsEmpty { get { return chunks.Length == 0; } }
public int NumActiveChunks
{
get
{
int numActiveChunks = 0;
foreach (var chunk in chunks)
if (chunk != null && chunk.colors != null && chunk.colors.Length > 0)
numActiveChunks++;
return numActiveChunks;
}
}
public int numColumns, numRows;
public int divX, divY;
}
[System.Serializable]
public class Layer
{
public int hash;
public SpriteChannel spriteChannel;
public Layer(int hash, int width, int height, int divX, int divY)
{
spriteChannel = new SpriteChannel();
Init(hash, width, height, divX, divY);
}
public void Init(int hash, int width, int height, int divX, int divY)
{
this.divX = divX;
this.divY = divY;
this.hash = hash;
this.numColumns = (width + divX - 1) / divX;
this.numRows = (height + divY - 1) / divY;
this.width = width;
this.height = height;
spriteChannel.chunks = new SpriteChunk[numColumns * numRows];
for (int i = 0; i < numColumns * numRows; ++i)
spriteChannel.chunks[i] = new SpriteChunk();
}
public bool IsEmpty { get { return spriteChannel.chunks.Length == 0; } }
public void Create()
{
spriteChannel.chunks = new SpriteChunk[numColumns * numRows];
}
public int[] GetChunkData(int x, int y)
{
return GetChunk(x, y).spriteIds;
}
public SpriteChunk GetChunk(int x, int y)
{
return spriteChannel.chunks[y * numColumns + x];
}
SpriteChunk FindChunkAndCoordinate(int x, int y, out int offset)
{
int cellX = x / divX;
int cellY = y / divY;
var chunk = spriteChannel.chunks[cellY * numColumns + cellX];
int localX = x - cellX * divX;
int localY = y - cellY * divY;
offset = localY * divX + localX;
return chunk;
}
public void SetTile(int x, int y, int spriteId)
{
int offset;
var chunk = FindChunkAndCoordinate(x, y, out offset);
CreateChunk(chunk);
chunk.spriteIds[offset] = spriteId;
chunk.Dirty = true;
}
public int GetTile(int x, int y)
{
int offset;
var chunk = FindChunkAndCoordinate(x, y, out offset);
if (chunk.spriteIds == null || chunk.spriteIds.Length == 0)
return -1;
return chunk.spriteIds[offset];
}
void CreateChunk(SpriteChunk chunk)
{
if (chunk.spriteIds == null || chunk.spriteIds.Length == 0)
{
chunk.spriteIds = new int[divX * divY];
for (int i = 0; i < divX * divY; ++i)
chunk.spriteIds[i] = -1;
}
}
void Optimize(SpriteChunk chunk)
{
bool empty = true;
foreach (var v in chunk.spriteIds)
{
if (v != -1)
{
empty = false;
break;
}
}
if (empty)
chunk.spriteIds = new int[0];
}
public void Optimize()
{
foreach (var chunk in spriteChannel.chunks)
Optimize(chunk);
}
public void OptimizeIncremental()
{
foreach (var chunk in spriteChannel.chunks)
{
if (chunk.Dirty)
Optimize(chunk);
}
}
public void ClearDirtyFlag()
{
foreach (var chunk in spriteChannel.chunks)
chunk.Dirty = false;
}
public int NumActiveChunks
{
get
{
int numActiveChunks = 0;
foreach (var chunk in spriteChannel.chunks)
if (!chunk.IsEmpty)
numActiveChunks++;
return numActiveChunks;
}
}
public int width, height;
public int numColumns, numRows;
public int divX, divY;
public GameObject gameObject;
}
}
| |
using System;
using System.Web.Security;
namespace SmallSharpTools.YahooPack.Web.Security
{
public class YahooMembershipProvider : MembershipProvider
{
///<summary>
///Adds a new membership user to the data source.
///</summary>
///
///<returns>
///A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user.
///</returns>
///
///<param name="isApproved">Whether or not the new user is approved to be validated.</param>
///<param name="passwordAnswer">The password answer for the new user</param>
///<param name="username">The user name for the new user. </param>
///<param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
///<param name="password">The password for the new user. </param>
///<param name="passwordQuestion">The password question for the new user.</param>
///<param name="email">The e-mail address for the new user.</param>
///<param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param>
public override MembershipUser CreateUser(string username, string password, string email,
string passwordQuestion, string passwordAnswer, bool isApproved,
object providerUserKey, out MembershipCreateStatus status)
{
throw new NotImplementedException();
}
///<summary>
///Processes a request to update the password question and answer for a membership user.
///</summary>
///
///<returns>
///true if the password question and answer are updated successfully; otherwise, false.
///</returns>
///
///<param name="newPasswordQuestion">The new password question for the specified user. </param>
///<param name="newPasswordAnswer">The new password answer for the specified user. </param>
///<param name="username">The user to change the password question and answer for. </param>
///<param name="password">The password for the specified user. </param>
public override bool ChangePasswordQuestionAndAnswer(string username, string password,
string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotImplementedException();
}
///<summary>
///Gets the password for the specified user name from the data source.
///</summary>
///
///<returns>
///The password for the specified user name.
///</returns>
///
///<param name="username">The user to retrieve the password for. </param>
///<param name="answer">The password answer for the user. </param>
public override string GetPassword(string username, string answer)
{
throw new NotImplementedException();
}
///<summary>
///Processes a request to update the password for a membership user.
///</summary>
///
///<returns>
///true if the password was updated successfully; otherwise, false.
///</returns>
///
///<param name="newPassword">The new password for the specified user. </param>
///<param name="oldPassword">The current password for the specified user. </param>
///<param name="username">The user to update the password for. </param>
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotImplementedException();
}
///<summary>
///Resets a user's password to a new, automatically generated password.
///</summary>
///
///<returns>
///The new password for the specified user.
///</returns>
///
///<param name="username">The user to reset the password for. </param>
///<param name="answer">The password answer for the specified user. </param>
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
///<summary>
///Updates information about a user in the data source.
///</summary>
///
///<param name="user">A <see cref="T:System.Web.Security.MembershipUser"></see> object that represents the user to update and the updated information for the user. </param>
public override void UpdateUser(MembershipUser user)
{
throw new NotImplementedException();
}
///<summary>
///Verifies that the specified user name and password exist in the data source.
///</summary>
///
///<returns>
///true if the specified username and password are valid; otherwise, false.
///</returns>
///
///<param name="username">The name of the user to validate. </param>
///<param name="password">The password for the specified user. </param>
public override bool ValidateUser(string username, string password)
{
throw new NotImplementedException();
}
///<summary>
///Clears a lock so that the membership user can be validated.
///</summary>
///
///<returns>
///true if the membership user was successfully unlocked; otherwise, false.
///</returns>
///
///<param name="userName">The membership user to clear the lock status for.</param>
public override bool UnlockUser(string userName)
{
throw new NotImplementedException();
}
///<summary>
///Gets information from the data source for a user based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user.
///</summary>
///
///<returns>
///A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source.
///</returns>
///
///<param name="providerUserKey">The unique identifier for the membership user to get information for.</param>
///<param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new NotImplementedException();
}
///<summary>
///Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
///</summary>
///
///<returns>
///A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source.
///</returns>
///
///<param name="username">The name of the user to get information for. </param>
///<param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user. </param>
public override MembershipUser GetUser(string username, bool userIsOnline)
{
throw new NotImplementedException();
}
///<summary>
///Gets the user name associated with the specified e-mail address.
///</summary>
///
///<returns>
///The user name associated with the specified e-mail address. If no match is found, return null.
///</returns>
///
///<param name="email">The e-mail address to search for. </param>
public override string GetUserNameByEmail(string email)
{
throw new NotImplementedException();
}
///<summary>
///Removes a user from the membership data source.
///</summary>
///
///<returns>
///true if the user was successfully deleted; otherwise, false.
///</returns>
///
///<param name="username">The name of the user to delete.</param>
///<param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new NotImplementedException();
}
///<summary>
///Gets a collection of all the users in the data source in pages of data.
///</summary>
///
///<returns>
///A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
///</returns>
///
///<param name="totalRecords">The total number of matched users.</param>
///<param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
///<param name="pageSize">The size of the page of results to return.</param>
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
///<summary>
///Gets the number of users currently accessing the application.
///</summary>
///
///<returns>
///The number of users currently accessing the application.
///</returns>
///
public override int GetNumberOfUsersOnline()
{
throw new NotImplementedException();
}
///<summary>
///Gets a collection of membership users where the user name contains the specified user name to match.
///</summary>
///
///<returns>
///A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
///</returns>
///
///<param name="totalRecords">The total number of matched users.</param>
///<param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
///<param name="usernameToMatch">The user name to search for.</param>
///<param name="pageSize">The size of the page of results to return.</param>
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize,
out int totalRecords)
{
throw new NotImplementedException();
}
///<summary>
///Gets a collection of membership users where the e-mail address contains the specified e-mail address to match.
///</summary>
///
///<returns>
///A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
///</returns>
///
///<param name="totalRecords">The total number of matched users.</param>
///<param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
///<param name="emailToMatch">The e-mail address to search for.</param>
///<param name="pageSize">The size of the page of results to return.</param>
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize,
out int totalRecords)
{
throw new NotImplementedException();
}
///<summary>
///Indicates whether the membership provider is configured to allow users to retrieve their passwords.
///</summary>
///
///<returns>
///true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.
///</returns>
///
public override bool EnablePasswordRetrieval
{
get { throw new NotImplementedException(); }
}
///<summary>
///Indicates whether the membership provider is configured to allow users to reset their passwords.
///</summary>
///
///<returns>
///true if the membership provider supports password reset; otherwise, false. The default is true.
///</returns>
///
public override bool EnablePasswordReset
{
get { throw new NotImplementedException(); }
}
///<summary>
///Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval.
///</summary>
///
///<returns>
///true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.
///</returns>
///
public override bool RequiresQuestionAndAnswer
{
get { throw new NotImplementedException(); }
}
///<summary>
///The name of the application using the custom membership provider.
///</summary>
///
///<returns>
///The name of the application using the custom membership provider.
///</returns>
///
public override string ApplicationName
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
///<summary>
///Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out.
///</summary>
///
///<returns>
///The number of invalid password or password-answer attempts allowed before the membership user is locked out.
///</returns>
///
public override int MaxInvalidPasswordAttempts
{
get { throw new NotImplementedException(); }
}
///<summary>
///Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.
///</summary>
///
///<returns>
///The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.
///</returns>
///
public override int PasswordAttemptWindow
{
get { throw new NotImplementedException(); }
}
///<summary>
///Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name.
///</summary>
///
///<returns>
///true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.
///</returns>
///
public override bool RequiresUniqueEmail
{
get { throw new NotImplementedException(); }
}
///<summary>
///Gets a value indicating the format for storing passwords in the membership data store.
///</summary>
///
///<returns>
///One of the <see cref="T:System.Web.Security.MembershipPasswordFormat"></see> values indicating the format for storing passwords in the data store.
///</returns>
///
public override MembershipPasswordFormat PasswordFormat
{
get { throw new NotImplementedException(); }
}
///<summary>
///Gets the minimum length required for a password.
///</summary>
///
///<returns>
///The minimum length required for a password.
///</returns>
///
public override int MinRequiredPasswordLength
{
get { throw new NotImplementedException(); }
}
///<summary>
///Gets the minimum number of special characters that must be present in a valid password.
///</summary>
///
///<returns>
///The minimum number of special characters that must be present in a valid password.
///</returns>
///
public override int MinRequiredNonAlphanumericCharacters
{
get { throw new NotImplementedException(); }
}
///<summary>
///Gets the regular expression used to evaluate a password.
///</summary>
///
///<returns>
///A regular expression used to evaluate a password.
///</returns>
///
public override string PasswordStrengthRegularExpression
{
get { throw new NotImplementedException(); }
}
}
}
| |
/*
* Copyright (c) 2014, Furore ([email protected]) and contributors
* See the file CONTRIBUTORS for details.
*
* This file is licensed under the BSD 3-Clause license
* available at https://raw.github.com/furore-fhir/spark/master/LICENSE
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using Spark.Engine.Core;
using Hl7.Fhir.Introspection;
namespace Spark.Engine.Service.FhirServiceExtensions
{
public static class ConformanceBuilder
{
public static Conformance GetSparkConformance(string sparkVersion, ILocalhost localhost)
{
string vsn = Hl7.Fhir.Model.ModelInfo.Version;
Conformance conformance = CreateServer("Spark", sparkVersion, "Furore", fhirVersion: vsn);
conformance.AddAllCoreResources(readhistory: true, updatecreate: true, versioning: Conformance.ResourceVersionPolicy.VersionedUpdate);
conformance.AddAllSystemInteractions().AddAllInteractionsForAllResources().AddCoreSearchParamsAllResources();
conformance.AddSummaryForAllResources();
conformance.AddOperation("Fetch Patient Record", new ResourceReference() { Url = localhost.Absolute(new Uri("OperationDefinition/Patient-everything", UriKind.Relative)) });
conformance.AddOperation("Generate a Document", new ResourceReference() { Url = localhost.Absolute(new Uri("OperationDefinition/Composition-document", UriKind.Relative)) });
conformance.AcceptUnknown = Conformance.UnknownContentCode.Both;
conformance.Experimental = true;
conformance.Format = new string[] { "xml", "json" };
conformance.Description = "This FHIR SERVER is a reference Implementation server built in C# on HL7.Fhir.Core (nuget) by Furore and others";
return conformance;
}
public static Conformance CreateServer(String server, String serverVersion, String publisher, String fhirVersion)
{
Conformance conformance = new Conformance();
conformance.Name = server;
conformance.Publisher = publisher;
conformance.Version = serverVersion;
conformance.FhirVersion = fhirVersion;
conformance.AcceptUnknown = Conformance.UnknownContentCode.No;
conformance.Date = Date.Today().Value;
conformance.AddServer();
return conformance;
//AddRestComponent(true);
//AddAllCoreResources(true, true, Conformance.ResourceVersionPolicy.VersionedUpdate);
//AddAllSystemInteractions();
//AddAllResourceInteractionsAllResources();
//AddCoreSearchParamsAllResources();
//return con;
}
public static Conformance.RestComponent AddRestComponent(this Conformance conformance, Boolean isServer, String documentation = null)
{
var server = new Conformance.RestComponent();
server.Mode = (isServer) ? Conformance.RestfulConformanceMode.Server : Conformance.RestfulConformanceMode.Client;
if (documentation != null)
{
server.Documentation = documentation;
}
conformance.Rest.Add(server);
return server;
}
public static Conformance AddServer(this Conformance conformance)
{
conformance.AddRestComponent(isServer: true);
return conformance;
}
public static Conformance.RestComponent Server(this Conformance conformance)
{
var server = conformance.Rest.FirstOrDefault(r => r.Mode == Conformance.RestfulConformanceMode.Server);
return (server == null) ? conformance.AddRestComponent(isServer: true) : server;
}
public static Conformance.RestComponent Rest(this Conformance conformance)
{
return conformance.Rest.FirstOrDefault();
}
public static Conformance AddAllCoreResources(this Conformance conformance, Boolean readhistory, Boolean updatecreate, Conformance.ResourceVersionPolicy versioning)
{
foreach (var resource in ModelInfo.SupportedResources)
{
conformance.AddSingleResourceComponent(resource, readhistory, updatecreate, versioning);
}
return conformance;
}
public static Conformance AddMultipleResourceComponents(this Conformance conformance, List<String> resourcetypes, Boolean readhistory, Boolean updatecreate, Conformance.ResourceVersionPolicy versioning)
{
foreach (var type in resourcetypes)
{
AddSingleResourceComponent(conformance, type, readhistory, updatecreate, versioning);
}
return conformance;
}
public static Conformance AddSingleResourceComponent(this Conformance conformance, String resourcetype, Boolean readhistory, Boolean updatecreate, Conformance.ResourceVersionPolicy versioning, ResourceReference profile = null)
{
var resource = new Conformance.ResourceComponent();
resource.Type = Hacky.GetResourceTypeForResourceName(resourcetype);
resource.Profile = profile;
resource.ReadHistory = readhistory;
resource.UpdateCreate = updatecreate;
resource.Versioning = versioning;
conformance.Server().Resource.Add(resource);
return conformance;
}
public static Conformance AddSummaryForAllResources(this Conformance conformance)
{
foreach (var resource in conformance.Rest.FirstOrDefault().Resource.ToList())
{
var p = new Conformance.SearchParamComponent();
p.Name = "_summary";
p.Type = SearchParamType.String;
p.Documentation = "Summary for resource";
resource.SearchParam.Add(p);
}
return conformance;
}
public static Conformance AddCoreSearchParamsAllResources(this Conformance conformance)
{
foreach (var r in conformance.Rest.FirstOrDefault().Resource.ToList())
{
conformance.Rest().Resource.Remove(r);
conformance.Rest().Resource.Add(AddCoreSearchParamsResource(r));
}
return conformance;
}
public static Conformance.ResourceComponent AddCoreSearchParamsResource(Conformance.ResourceComponent resourcecomp)
{
var parameters = ModelInfo.SearchParameters.Where(sp => sp.Resource == resourcecomp.Type.GetLiteral())
.Select(sp => new Conformance.SearchParamComponent
{
Name = sp.Name,
Type = sp.Type,
Documentation = sp.Description,
});
resourcecomp.SearchParam.AddRange(parameters);
return resourcecomp;
}
public static Conformance AddAllInteractionsForAllResources(this Conformance conformance)
{
foreach (var r in conformance.Rest.FirstOrDefault().Resource.ToList())
{
conformance.Rest().Resource.Remove(r);
conformance.Rest().Resource.Add(AddAllResourceInteractions(r));
}
return conformance;
}
public static Conformance.ResourceComponent AddAllResourceInteractions(Conformance.ResourceComponent resourcecomp)
{
foreach (Conformance.TypeRestfulInteraction type in Enum.GetValues(typeof(Conformance.TypeRestfulInteraction)))
{
var interaction = AddSingleResourceInteraction(resourcecomp, type);
resourcecomp.Interaction.Add(interaction);
}
return resourcecomp;
}
public static Conformance.ResourceInteractionComponent AddSingleResourceInteraction(Conformance.ResourceComponent resourcecomp, Conformance.TypeRestfulInteraction type)
{
var interaction = new Conformance.ResourceInteractionComponent();
interaction.Code = type;
return interaction;
}
public static Conformance AddAllSystemInteractions(this Conformance conformance)
{
foreach (Conformance.SystemRestfulInteraction code in Enum.GetValues(typeof(Conformance.SystemRestfulInteraction)))
{
conformance.AddSystemInteraction(code);
}
return conformance;
}
public static void AddSystemInteraction(this Conformance conformance, Conformance.SystemRestfulInteraction code)
{
var interaction = new Conformance.SystemInteractionComponent();
interaction.Code = code;
conformance.Rest().Interaction.Add(interaction);
}
public static void AddOperation(this Conformance conformance, String name, ResourceReference definition)
{
var operation = new Conformance.OperationComponent();
operation.Name = name;
operation.Definition = definition;
conformance.Server().Operation.Add(operation);
}
public static String ConformanceToXML(this Conformance conformance)
{
return FhirSerializer.SerializeResourceToXml(conformance);
}
}
}
// TODO: Code review Conformance replacement
//public const string CONFORMANCE_ID = "self";
//public static readonly string CONFORMANCE_COLLECTION_NAME = typeof(Conformance).GetCollectionName();
//public static Conformance CreateTemp()
//{
// return new Conformance();
//}
//public static Conformance Build()
//{
// //var conformance = new Conformance();
//Stream s = typeof(ConformanceBuilder).Assembly.GetManifestResourceStream("Spark.Engine.Service.Conformance.xml");
//StreamReader sr = new StreamReader(s);
//string conformanceXml = sr.ReadToEnd();
//var conformance = (Conformance)FhirParser.ParseResourceFromXml(conformanceXml);
//conformance.Software = new Conformance.ConformanceSoftwareComponent();
//conformance.Software.Version = ReadVersionFromAssembly();
//conformance.Software.Name = ReadProductNameFromAssembly();
//conformance.FhirVersion = ModelInfo.Version;
//conformance.Date = Date.Today().Value;
//conformance.Meta = new Resource.ResourceMetaComponent();
//conformance.Meta.VersionId = "0";
//Conformance.ConformanceRestComponent serverComponent = conformance.Rest[0];
// Replace anything that was there before...
//serverComponent.Resource = new List<Conformance.ConformanceRestResourceComponent>();
/*var allOperations = new List<Conformance.ConformanceRestResourceOperationComponent>()
{ new Conformance.ConformanceRestResourceOperationComponent { Code = Conformance.RestfulOperationType.Create },
new Conformance.ConformanceRestResourceOperationComponent { Code = Conformance.RestfulOperationType.Delete },
new Conformance.ConformanceRestResourceOperationComponent { Code = Conformance.RestfulOperationType.HistoryInstance },
new Conformance.ConformanceRestResourceOperationComponent { Code = Conformance.RestfulOperationType.HistoryType },
new Conformance.ConformanceRestResourceOperationComponent { Code = Conformance.RestfulOperationType.Read },
new Conformance.ConformanceRestResourceOperationComponent { Code = Conformance.RestfulOperationType.SearchType },
new Conformance.ConformanceRestResourceOperationComponent { Code = Conformance.RestfulOperationType.Update },
new Conformance.ConformanceRestResourceOperationComponent { Code = Conformance.RestfulOperationType.Validate },
new Conformance.ConformanceRestResourceOperationComponent { Code = Conformance.RestfulOperationType.Vread },
};
foreach (var resourceName in ModelInfo.SupportedResources)
{
var supportedResource = new Conformance.ConformanceRestResourceComponent();
supportedResource.Type = resourceName;
supportedResource.ReadHistory = true;
supportedResource.Operation = allOperations;
// Add supported _includes for this resource
supportedResource.SearchInclude = ModelInfo.SearchParameters
.Where(sp => sp.Resource == resourceName)
.Where(sp => sp.Type == Conformance.SearchParamType.Reference)
.Select(sp => sp.Name);
supportedResource.SearchParam = new List<Conformance.ConformanceRestResourceSearchParamComponent>();
var parameters = ModelInfo.SearchParameters.Where(sp => sp.Resource == resourceName)
.Select(sp => new Conformance.ConformanceRestResourceSearchParamComponent
{
Name = sp.Name,
Type = sp.Type,
Documentation = sp.Description,
});
supportedResource.SearchParam.AddRange(parameters);
serverComponent.Resource.Add(supportedResource);
}
*/
// This constant has become internal. Please undo. We need it.
// Update: new location: XHtml.XHTMLNS / XHtml
// // XNamespace ns = Hl7.Fhir.Support.Util.XHTMLNS;
// XNamespace ns = "http://www.w3.org/1999/xhtml";
// var summary = new XElement(ns + "div");
// foreach (string resourceName in ModelInfo.SupportedResources)
// {
// summary.Add(new XElement(ns + "p",
// String.Format("The server supports all operations on the {0} resource, including history",
// resourceName)));
// }
// conformance.Text = new Narrative();
// conformance.Text.Div = summary.ToString();
// return conformance;
// }
// public static string ReadVersionFromAssembly()
// {
// var attribute = (System.Reflection.AssemblyFileVersionAttribute)typeof(ConformanceBuilder).Assembly
// .GetCustomAttributes(typeof(System.Reflection.AssemblyFileVersionAttribute), true)
// .Single();
// return attribute.Version;
// }
// public static string ReadProductNameFromAssembly()
// {
// var attribute = (System.Reflection.AssemblyProductAttribute)typeof(ConformanceBuilder).Assembly
// .GetCustomAttributes(typeof(System.Reflection.AssemblyProductAttribute), true)
// .Single();
// return attribute.Product;
// }
//}
//}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
using Http2;
using Http2.Hpack;
using static Http2Tests.TestHeaders;
namespace Http2Tests
{
public class ServerStreamTests
{
private ILoggerProvider loggerProvider;
public ServerStreamTests(ITestOutputHelper outHelper)
{
loggerProvider = new XUnitOutputLoggerProvider(outHelper);
}
public static class StreamCreator
{
public struct Result
{
public Encoder hEncoder;
public Connection conn;
public IStream stream;
}
public static async Task<Result> CreateConnectionAndStream(
StreamState state,
ILoggerProvider loggerProvider,
IBufferedPipe iPipe, IBufferedPipe oPipe,
Settings? localSettings = null,
Settings? remoteSettings = null,
HuffmanStrategy huffmanStrategy = HuffmanStrategy.Never)
{
IStream stream = null;
var handlerDone = new SemaphoreSlim(0);
if (state == StreamState.Idle)
{
throw new Exception("Not supported");
}
Func<IStream, bool> listener = (s) =>
{
Task.Run(async () =>
{
stream = s;
try
{
await s.ReadHeadersAsync();
if (state == StreamState.Reset)
{
s.Cancel();
return;
}
if (state == StreamState.HalfClosedRemote ||
state == StreamState.Closed)
{
await s.ReadAllToArrayWithTimeout();
}
if (state == StreamState.HalfClosedLocal ||
state == StreamState.Closed)
{
await s.WriteHeadersAsync(
DefaultStatusHeaders, true);
}
}
finally
{
handlerDone.Release();
}
});
return true;
};
var conn = await ConnectionUtils.BuildEstablishedConnection(
true, iPipe, oPipe, loggerProvider, listener,
localSettings: localSettings,
remoteSettings: remoteSettings,
huffmanStrategy: huffmanStrategy);
var hEncoder = new Encoder();
await iPipe.WriteHeaders(
hEncoder, 1, false, DefaultGetHeaders);
if (state == StreamState.HalfClosedRemote ||
state == StreamState.Closed)
{
await iPipe.WriteData(1u, 0, endOfStream: true);
}
var ok = await handlerDone.WaitAsync(
ReadableStreamTestExtensions.ReadTimeout);
if (!ok) throw new Exception("Stream handler did not finish");
if (state == StreamState.HalfClosedLocal ||
state == StreamState.Closed)
{
// Consume the sent headers and data
await oPipe.ReadAndDiscardHeaders(1u, true);
}
else if (state == StreamState.Reset)
{
// Consume the sent reset frame
await oPipe.AssertResetStreamReception(1, ErrorCode.Cancel);
}
return new Result
{
conn = conn,
stream = stream,
hEncoder = hEncoder,
};
}
}
[Theory]
[InlineData(StreamState.Open)]
[InlineData(StreamState.HalfClosedLocal)]
[InlineData(StreamState.HalfClosedRemote)]
[InlineData(StreamState.Closed)]
[InlineData(StreamState.Reset)]
public async Task StreamCreatorShouldCreateStreamInCorrectState(
StreamState state)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
state, loggerProvider, inPipe, outPipe);
Assert.NotNull(res.stream);
Assert.Equal(state, res.stream.State);
}
[Fact]
public async Task ReceivingHeadersShouldCreateNewStreamsAndAllowToReadTheHeaders()
{
const int nrStreams = 10;
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
int nrAcceptedStreams = 0;
var handlerDone = new SemaphoreSlim(0);
uint streamId = 1;
var headersOk = false;
var streamIdOk = false;
var streamStateOk = false;
Func<IStream, bool> listener = (s) =>
{
Interlocked.Increment(ref nrAcceptedStreams);
Task.Run(async () =>
{
var rcvdHeaders = await s.ReadHeadersAsync();
headersOk = DefaultGetHeaders.SequenceEqual(rcvdHeaders);
streamIdOk = s.Id == streamId;
streamStateOk = s.State == StreamState.Open;
handlerDone.Release();
});
return true;
};
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
true, inPipe, outPipe, loggerProvider, listener);
var hEncoder = new Encoder();
for (var i = 0; i < nrStreams; i++)
{
headersOk = false;
streamIdOk = false;
streamStateOk = false;
await inPipe.WriteHeaders(hEncoder, streamId, false, DefaultGetHeaders);
var requestDone = await handlerDone.WaitAsync(ReadableStreamTestExtensions.ReadTimeout);
Assert.True(requestDone, "Expected handler to complete within timeout");
Assert.True(headersOk);
Assert.True(streamIdOk);
Assert.True(streamStateOk);
streamId += 2;
}
Assert.Equal(nrStreams, nrAcceptedStreams);
}
[Fact]
public async Task ReceivingHeadersWithEndOfStreamShouldAllowToReadEndOfStream()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var handlerDone = new SemaphoreSlim(0);
var gotEos = false;
var streamStateOk = false;
Func<IStream, bool> listener = (s) =>
{
Task.Run(async () =>
{
await s.ReadHeadersAsync();
var buf = new byte[1024];
var res = await s.ReadAsync(new ArraySegment<byte>(buf));
gotEos = res.EndOfStream && res.BytesRead == 0;
streamStateOk = s.State == StreamState.HalfClosedRemote;
handlerDone.Release();
});
return true;
};
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
true, inPipe, outPipe, loggerProvider, listener);
var hEncoder = new Encoder();
await inPipe.WriteHeaders(hEncoder, 1, true, DefaultGetHeaders);
var requestDone = await handlerDone.WaitAsync(ReadableStreamTestExtensions.ReadTimeout);
Assert.True(requestDone, "Expected handler to complete within timeout");
Assert.True(gotEos);
Assert.True(streamStateOk);
}
[Fact]
public async Task ReceivingHeadersAndNoDataShouldBlockTheReader()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider, inPipe, outPipe);
var buf = new byte[1024];
try
{
await res.stream.ReadWithTimeout(new ArraySegment<byte>(buf));
}
catch (TimeoutException)
{
return;
}
Assert.True(false, "Expected read timeout, but got data");
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ResponseHeadersShouldBeCorrectlySent(
bool useEndOfStream)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider, inPipe, outPipe);
await r.stream.WriteHeadersAsync(DefaultStatusHeaders, useEndOfStream);
// Check the received headers
var fh = await outPipe.ReadFrameHeaderWithTimeout();
Assert.Equal(FrameType.Headers, fh.Type);
Assert.Equal(1u, fh.StreamId);
var expectedFlags = HeadersFrameFlags.EndOfHeaders;
if (useEndOfStream) expectedFlags |= HeadersFrameFlags.EndOfStream;
Assert.Equal((byte)expectedFlags, fh.Flags);
Assert.InRange(fh.Length, 1, 1024);
var headerData = new byte[fh.Length];
await outPipe.ReadAllWithTimeout(new ArraySegment<byte>(headerData));
Assert.Equal(EncodedDefaultStatusHeaders, headerData);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task RespondingDataWithoutHeadersShouldThrowAnException(
bool useEndOfStream)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider, inPipe, outPipe);
var ex = await Assert.ThrowsAsync<Exception>(async () =>
await r.stream.WriteAsync(
new ArraySegment<byte>(new byte[8]), useEndOfStream));
Assert.Equal("Attempted to write data before headers", ex.Message);
}
[Fact]
public async Task RespondingTrailersWithoutHeadersShouldThrowAnException()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider, inPipe, outPipe);
var ex = await Assert.ThrowsAsync<Exception>(async () =>
await r.stream.WriteTrailersAsync(DefaultTrailingHeaders));
Assert.Equal("Attempted to write trailers without data", ex.Message);
}
[Fact]
public async Task ItShouldBePossibleToSendInformationalHeaders()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider, inPipe, outPipe);
var infoHeaders = new HeaderField[]
{
new HeaderField { Name = ":status", Value = "100" },
new HeaderField { Name = "extension-field", Value = "bar" },
};
await r.stream.WriteHeadersAsync(infoHeaders, false);
await r.stream.WriteHeadersAsync(DefaultStatusHeaders, false);
await r.stream.WriteAsync(new ArraySegment<byte>(new byte[0]), true);
await outPipe.ReadAndDiscardHeaders(1, false);
await outPipe.ReadAndDiscardHeaders(1, false);
await outPipe.ReadAndDiscardData(1, true, 0);
}
[Theory]
[InlineData(StreamState.HalfClosedRemote, true, false, false)]
[InlineData(StreamState.HalfClosedRemote, false, true, false)]
[InlineData(StreamState.HalfClosedRemote, false, false, true)]
// Situations where connection is full closed - not half
[InlineData(StreamState.Closed, true, false, false)]
[InlineData(StreamState.Closed, false, true, false)]
[InlineData(StreamState.Closed, false, false, true)]
public async Task ReceivingHeadersOrDataOnAClosedStreamShouldTriggerAStreamReset(
StreamState streamState,
bool sendHeaders, bool sendData, bool sendTrailers)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var localCloseDone = new SemaphoreSlim(0);
var res = await StreamCreator.CreateConnectionAndStream(
streamState, loggerProvider, inPipe, outPipe);
if (sendHeaders)
{
await inPipe.WriteHeaders(res.hEncoder, 1, false, DefaultGetHeaders);
}
if (sendData)
{
await inPipe.WriteData(1u, 0);
}
if (sendTrailers)
{
await inPipe.WriteHeaders(res.hEncoder, 1, true, DefaultGetHeaders);
}
await outPipe.AssertResetStreamReception(1u, ErrorCode.StreamClosed);
var expectedState =
streamState == StreamState.Closed
? StreamState.Closed
: StreamState.Reset;
Assert.Equal(expectedState, res.stream.State);
}
[Theory]
[InlineData(true, false, false)]
[InlineData(false, true, false)]
[InlineData(false, false, true)]
[InlineData(false, true, true)]
public async Task ReceivingHeadersOrDataOnAResetStreamShouldProduceAClosedStreamError(
bool sendHeaders, bool sendData, bool sendTrailers)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await StreamCreator.CreateConnectionAndStream(
StreamState.Reset, loggerProvider, inPipe, outPipe);
if (sendHeaders)
{
await inPipe.WriteHeaders(r.hEncoder, 1, false, DefaultGetHeaders);
}
if (sendData)
{
await inPipe.WriteData(1u, 0);
}
if (sendTrailers)
{
await inPipe.WriteHeaders(r.hEncoder, 1, true, DefaultGetHeaders);
}
await outPipe.AssertResetStreamReception(1, ErrorCode.StreamClosed);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ReceivingHeadersWithNoAttachedListenerOrRefusingListenerShouldTriggerStreamReset(
bool noListener)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
Func<IStream, bool> listener = null;
if (!noListener) listener = (s) => false;
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
true, inPipe, outPipe, loggerProvider, listener);
var hEncoder = new Encoder();
await inPipe.WriteHeaders(hEncoder, 1, false, DefaultGetHeaders);
await outPipe.AssertResetStreamReception(1, ErrorCode.RefusedStream);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ReceivingHeadersWithATooSmallStreamIdShouldTriggerAStreamReset(
bool noListener)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
Func<IStream, bool> listener = (s) => true;
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
true, inPipe, outPipe, loggerProvider, listener);
var hEncoder = new Encoder();
await inPipe.WriteHeaders(hEncoder, 33, false, DefaultGetHeaders);
await inPipe.WriteHeaders(hEncoder, 31, false, DefaultGetHeaders);
// Remark: The specification actually wants a connection error / GOAWAY
// to be emitted. However as the implementation can not safely determine
// if that stream ID was never used and valid we send and check for
// a stream reset.
await outPipe.AssertResetStreamReception(31, ErrorCode.StreamClosed);
}
[Theory]
[InlineData(20)]
public async Task IncomingStreamsAfterMaxConcurrentStreamsShouldBeRejected(
int maxConcurrentStreams)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var acceptedStreams = new List<IStream>();
Func<IStream, bool> listener = (s) =>
{
lock (acceptedStreams)
{
acceptedStreams.Add(s);
}
return true;
};
var settings = Settings.Default;
settings.MaxConcurrentStreams = (uint)maxConcurrentStreams;
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
true, inPipe, outPipe, loggerProvider, listener,
localSettings: settings);
var hEncoder = new Encoder();
// Open maxConcurrentStreams
var streamId = 1u;
for (var i = 0; i < maxConcurrentStreams; i++)
{
await inPipe.WriteHeaders(hEncoder, streamId, false, DefaultGetHeaders);
streamId += 2;
}
// Assert no rejection and response so far
await inPipe.WritePing(new byte[8], false);
await outPipe.ReadAndDiscardPong();
lock (acceptedStreams)
{
Assert.Equal(maxConcurrentStreams, acceptedStreams.Count);
}
// Try to open an additional stream
await inPipe.WriteHeaders(hEncoder, streamId, false, DefaultGetHeaders);
// This one should be rejected
await outPipe.AssertResetStreamReception(streamId, ErrorCode.RefusedStream);
lock (acceptedStreams)
{
Assert.Equal(maxConcurrentStreams, acceptedStreams.Count);
}
// Once a stream is closed a new one should be acceptable
await inPipe.WriteResetStream(streamId-2, ErrorCode.Cancel);
streamId += 2;
await inPipe.WriteHeaders(hEncoder, streamId, false, DefaultGetHeaders);
// Assert no error response
await inPipe.WritePing(new byte[8], false);
await outPipe.ReadAndDiscardPong();
lock (acceptedStreams)
{
// +1 because the dead stream isn't removed
Assert.Equal(maxConcurrentStreams+1, acceptedStreams.Count);
// Check if the reset worked
Assert.Equal(
StreamState.Reset,
acceptedStreams[acceptedStreams.Count-2].State);
}
}
}
}
| |
// 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.Linq;
using Internal.TypeSystem;
using Xunit;
namespace TypeSystemTests
{
public class StaticFieldLayoutTests
{
TestTypeSystemContext _context;
ModuleDesc _testModule;
public StaticFieldLayoutTests()
{
_context = new TestTypeSystemContext(TargetArchitecture.X64);
var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly");
_context.SetSystemModule(systemModule);
_testModule = systemModule;
}
[Fact]
public void TestNoPointers()
{
MetadataType t = _testModule.GetType("StaticFieldLayout", "NoPointers");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "int1":
Assert.Equal(0, field.Offset);
break;
case "byte1":
Assert.Equal(4, field.Offset);
break;
case "char1":
Assert.Equal(6, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestStillNoPointers()
{
//
// Test that static offsets ignore instance fields preceeding them
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "StillNoPointers");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "bool1":
Assert.Equal(0, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestClassNoPointers()
{
//
// Ensure classes behave the same as structs when containing statics
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "ClassNoPointers");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "int1":
Assert.Equal(0, field.Offset);
break;
case "byte1":
Assert.Equal(4, field.Offset);
break;
case "char1":
Assert.Equal(6, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestHasPointers()
{
//
// Test a struct containing static types with pointers
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "HasPointers");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "string1":
Assert.Equal(8, field.Offset);
break;
case "class1":
Assert.Equal(16, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestMixPointersAndNonPointers()
{
//
// Test that static fields with GC pointers get separate offsets from non-GC fields
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "MixPointersAndNonPointers");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "string1":
Assert.Equal(8, field.Offset);
break;
case "int1":
Assert.Equal(0, field.Offset);
break;
case "class1":
Assert.Equal(16, field.Offset);
break;
case "int2":
Assert.Equal(4, field.Offset);
break;
case "string2":
Assert.Equal(24, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestEnsureInheritanceResetsStaticOffsets()
{
//
// Test that when inheriting a class with static fields, the derived slice's static fields
// are again offset from 0
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "EnsureInheritanceResetsStaticOffsets");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "int3":
Assert.Equal(0, field.Offset);
break;
case "string3":
Assert.Equal(8, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestLiteralFieldsDontAffectLayout()
{
//
// Test that literal fields are not laid out.
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "LiteralFieldsDontAffectLayout");
Assert.Equal(4, t.GetFields().Count());
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "IntConstant":
case "StringConstant":
Assert.True(field.IsStatic);
Assert.True(field.IsLiteral);
Assert.Throws<BadImageFormatException>(() => field.Offset);
break;
case "Int1":
Assert.Equal(0, field.Offset);
break;
case "String1":
Assert.Equal(8, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestStaticSelfRef()
{
//
// Test that we can load a struct which has a static field referencing itself without
// going into an infinite loop
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "StaticSelfRef");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "selfRef1":
Assert.Equal(0, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Handlers.Tls
{
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Security;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Common.Concurrency;
using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels;
public sealed class TlsHandler : ByteToMessageDecoder
{
readonly TlsSettings settings;
const int FallbackReadBufferSize = 256;
const int UnencryptedWriteBatchSize = 14 * 1024;
static readonly Exception ChannelClosedException = new IOException("Channel is closed");
static readonly Action<Task, object> HandshakeCompletionCallback = new Action<Task, object>(HandleHandshakeCompleted);
readonly SslStream sslStream;
readonly MediationStream mediationStream;
readonly TaskCompletionSource closeFuture;
TlsHandlerState state;
int packetLength;
volatile IChannelHandlerContext capturedContext;
BatchingPendingWriteQueue pendingUnencryptedWrites;
Task lastContextWriteTask;
bool firedChannelRead;
IByteBuffer pendingSslStreamReadBuffer;
Task<int> pendingSslStreamReadFuture;
public TlsHandler(TlsSettings settings)
: this(stream => new SslStream(stream, true), settings)
{
}
public TlsHandler(Func<Stream, SslStream> sslStreamFactory, TlsSettings settings)
{
Contract.Requires(sslStreamFactory != null);
Contract.Requires(settings != null);
this.settings = settings;
this.closeFuture = new TaskCompletionSource();
this.mediationStream = new MediationStream(this);
this.sslStream = sslStreamFactory(this.mediationStream);
}
public static TlsHandler Client(string targetHost) => new TlsHandler(new ClientTlsSettings(targetHost));
public static TlsHandler Client(string targetHost, X509Certificate clientCertificate) => new TlsHandler(new ClientTlsSettings(targetHost, new List<X509Certificate>{ clientCertificate }));
public static TlsHandler Server(X509Certificate certificate) => new TlsHandler(new ServerTlsSettings(certificate));
// using workaround mentioned here: https://github.com/dotnet/corefx/issues/4510
public X509Certificate2 LocalCertificate => this.sslStream.LocalCertificate as X509Certificate2 ?? new X509Certificate2(this.sslStream.LocalCertificate?.Export(X509ContentType.Cert));
public X509Certificate2 RemoteCertificate => this.sslStream.RemoteCertificate as X509Certificate2 ?? new X509Certificate2(this.sslStream.RemoteCertificate?.Export(X509ContentType.Cert));
bool IsServer => this.settings is ServerTlsSettings;
public void Dispose() => this.sslStream?.Dispose();
public override void ChannelActive(IChannelHandlerContext context)
{
base.ChannelActive(context);
if (!this.IsServer)
{
this.EnsureAuthenticated();
}
}
public override void ChannelInactive(IChannelHandlerContext context)
{
// Make sure to release SslStream,
// and notify the handshake future if the connection has been closed during handshake.
this.HandleFailure(ChannelClosedException);
base.ChannelInactive(context);
}
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
{
if (this.IgnoreException(exception))
{
// Close the connection explicitly just in case the transport
// did not close the connection automatically.
if (context.Channel.Active)
{
context.CloseAsync();
}
}
else
{
base.ExceptionCaught(context, exception);
}
}
bool IgnoreException(Exception t)
{
if (t is ObjectDisposedException && this.closeFuture.Task.IsCompleted)
{
return true;
}
return false;
}
static void HandleHandshakeCompleted(Task task, object state)
{
var self = (TlsHandler)state;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
{
TlsHandlerState oldState = self.state;
Contract.Assert(!oldState.HasAny(TlsHandlerState.AuthenticationCompleted));
self.state = (oldState | TlsHandlerState.Authenticated) & ~(TlsHandlerState.Authenticating | TlsHandlerState.FlushedBeforeHandshake);
self.capturedContext.FireUserEventTriggered(TlsHandshakeCompletionEvent.Success);
if (oldState.Has(TlsHandlerState.ReadRequestedBeforeAuthenticated) && !self.capturedContext.Channel.Configuration.AutoRead)
{
self.capturedContext.Read();
}
if (oldState.Has(TlsHandlerState.FlushedBeforeHandshake))
{
self.Wrap(self.capturedContext);
self.capturedContext.Flush();
}
break;
}
case TaskStatus.Canceled:
case TaskStatus.Faulted:
{
// ReSharper disable once AssignNullToNotNullAttribute -- task.Exception will be present as task is faulted
TlsHandlerState oldState = self.state;
Contract.Assert(!oldState.HasAny(TlsHandlerState.AuthenticationCompleted));
self.HandleFailure(task.Exception);
break;
}
default:
throw new ArgumentOutOfRangeException(nameof(task), "Unexpected task status: " + task.Status);
}
}
public override void HandlerAdded(IChannelHandlerContext context)
{
base.HandlerAdded(context);
this.capturedContext = context;
this.pendingUnencryptedWrites = new BatchingPendingWriteQueue(context, UnencryptedWriteBatchSize);
if (context.Channel.Active && !this.IsServer)
{
// todo: support delayed initialization on an existing/active channel if in client mode
this.EnsureAuthenticated();
}
}
protected override void HandlerRemovedInternal(IChannelHandlerContext context)
{
if (!this.pendingUnencryptedWrites.IsEmpty)
{
// Check if queue is not empty first because create a new ChannelException is expensive
this.pendingUnencryptedWrites.RemoveAndFailAll(new ChannelException("Write has failed due to TlsHandler being removed from channel pipeline."));
}
}
protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
{
int startOffset = input.ReaderIndex;
int endOffset = input.WriterIndex;
int offset = startOffset;
int totalLength = 0;
List<int> packetLengths;
// if we calculated the length of the current SSL record before, use that information.
if (this.packetLength > 0)
{
if (endOffset - startOffset < this.packetLength)
{
// input does not contain a single complete SSL record
return;
}
else
{
packetLengths = new List<int>(4);
packetLengths.Add(this.packetLength);
offset += this.packetLength;
totalLength = this.packetLength;
this.packetLength = 0;
}
}
else
{
packetLengths = new List<int>(4);
}
bool nonSslRecord = false;
while (totalLength < TlsUtils.MAX_ENCRYPTED_PACKET_LENGTH)
{
int readableBytes = endOffset - offset;
if (readableBytes < TlsUtils.SSL_RECORD_HEADER_LENGTH)
{
break;
}
int encryptedPacketLength = TlsUtils.GetEncryptedPacketLength(input, offset);
if (encryptedPacketLength == -1)
{
nonSslRecord = true;
break;
}
Contract.Assert(encryptedPacketLength > 0);
if (encryptedPacketLength > readableBytes)
{
// wait until the whole packet can be read
this.packetLength = encryptedPacketLength;
break;
}
int newTotalLength = totalLength + encryptedPacketLength;
if (newTotalLength > TlsUtils.MAX_ENCRYPTED_PACKET_LENGTH)
{
// Don't read too much.
break;
}
// 1. call unwrap with packet boundaries - call SslStream.ReadAsync only once.
// 2. once we're through all the whole packets, switch to reading out using fallback sized buffer
// We have a whole packet.
// Increment the offset to handle the next packet.
packetLengths.Add(encryptedPacketLength);
offset += encryptedPacketLength;
totalLength = newTotalLength;
}
if (totalLength > 0)
{
// The buffer contains one or more full SSL records.
// Slice out the whole packet so unwrap will only be called with complete packets.
// Also directly reset the packetLength. This is needed as unwrap(..) may trigger
// decode(...) again via:
// 1) unwrap(..) is called
// 2) wrap(...) is called from within unwrap(...)
// 3) wrap(...) calls unwrapLater(...)
// 4) unwrapLater(...) calls decode(...)
//
// See https://github.com/netty/netty/issues/1534
input.SkipBytes(totalLength);
this.Unwrap(context, input, startOffset, totalLength, packetLengths, output);
if (!this.firedChannelRead)
{
// Check first if firedChannelRead is not set yet as it may have been set in a
// previous decode(...) call.
this.firedChannelRead = output.Count > 0;
}
}
if (nonSslRecord)
{
// Not an SSL/TLS packet
var ex = new NotSslRecordException(
"not an SSL/TLS record: " + ByteBufferUtil.HexDump(input));
input.SkipBytes(input.ReadableBytes);
context.FireExceptionCaught(ex);
this.HandleFailure(ex);
}
}
public override void ChannelReadComplete(IChannelHandlerContext ctx)
{
// Discard bytes of the cumulation buffer if needed.
this.DiscardSomeReadBytes();
this.ReadIfNeeded(ctx);
this.firedChannelRead = false;
ctx.FireChannelReadComplete();
}
void ReadIfNeeded(IChannelHandlerContext ctx)
{
// if handshake is not finished yet, we need more data
if (!ctx.Channel.Configuration.AutoRead && (!this.firedChannelRead || !this.state.HasAny(TlsHandlerState.AuthenticationCompleted)))
{
// No auto-read used and no message was passed through the ChannelPipeline or the handshake was not completed
// yet, which means we need to trigger the read to ensure we will not stall
ctx.Read();
}
}
/// <summary>Unwraps inbound SSL records.</summary>
void Unwrap(IChannelHandlerContext ctx, IByteBuffer packet, int offset, int length, List<int> packetLengths, List<object> output)
{
Contract.Requires(packetLengths.Count > 0);
//bool notifyClosure = false; // todo: netty/issues/137
bool pending = false;
IByteBuffer outputBuffer = null;
try
{
ArraySegment<byte> inputIoBuffer = packet.GetIoBuffer(offset, length);
this.mediationStream.SetSource(inputIoBuffer.Array, inputIoBuffer.Offset);
int packetIndex = 0;
while (!this.EnsureAuthenticated())
{
this.mediationStream.ExpandSource(packetLengths[packetIndex]);
if (++packetIndex == packetLengths.Count)
{
return;
}
}
Task<int> currentReadFuture = this.pendingSslStreamReadFuture;
int outputBufferLength;
if (currentReadFuture != null)
{
// restoring context from previous read
Contract.Assert(this.pendingSslStreamReadBuffer != null);
outputBuffer = this.pendingSslStreamReadBuffer;
outputBufferLength = outputBuffer.WritableBytes;
}
else
{
outputBufferLength = 0;
}
// go through packets one by one (because SslStream does not consume more than 1 packet at a time)
for (; packetIndex < packetLengths.Count; packetIndex++)
{
int currentPacketLength = packetLengths[packetIndex];
this.mediationStream.ExpandSource(currentPacketLength);
if (currentReadFuture != null)
{
// there was a read pending already, so we make sure we completed that first
if (!currentReadFuture.IsCompleted)
{
// we did feed the whole current packet to SslStream yet it did not produce any result -> move to the next packet in input
Contract.Assert(this.mediationStream.SourceReadableBytes == 0);
continue;
}
int read = currentReadFuture.Result;
// Now output the result of previous read and decide whether to do an extra read on the same source or move forward
AddBufferToOutput(outputBuffer, read, output);
currentReadFuture = null;
if (this.mediationStream.SourceReadableBytes == 0)
{
// we just made a frame available for reading but there was already pending read so SslStream read it out to make further progress there
if (read < outputBufferLength)
{
// SslStream returned non-full buffer and there's no more input to go through ->
// typically it means SslStream is done reading current frame so we skip
continue;
}
// we've read out `read` bytes out of current packet to fulfil previously outstanding read
outputBufferLength = currentPacketLength - read;
if (outputBufferLength <= 0)
{
// after feeding to SslStream current frame it read out more bytes than current packet size
outputBufferLength = FallbackReadBufferSize;
}
}
else
{
// SslStream did not get to reading current frame so it completed previous read sync
// and the next read will likely read out the new frame
outputBufferLength = currentPacketLength;
}
}
else
{
// there was no pending read before so we estimate buffer of `currentPacketLength` bytes to be sufficient
outputBufferLength = currentPacketLength;
}
outputBuffer = ctx.Allocator.Buffer(outputBufferLength);
currentReadFuture = this.ReadFromSslStreamAsync(outputBuffer, outputBufferLength);
}
// read out the rest of SslStream's output (if any) at risk of going async
// using FallbackReadBufferSize - buffer size we're ok to have pinned with the SslStream until it's done reading
while (true)
{
if (currentReadFuture != null)
{
if (!currentReadFuture.IsCompleted)
{
break;
}
int read = currentReadFuture.Result;
AddBufferToOutput(outputBuffer, read, output);
}
outputBuffer = ctx.Allocator.Buffer(FallbackReadBufferSize);
currentReadFuture = this.ReadFromSslStreamAsync(outputBuffer, FallbackReadBufferSize);
}
pending = true;
this.pendingSslStreamReadBuffer = outputBuffer;
this.pendingSslStreamReadFuture = currentReadFuture;
}
catch (Exception ex)
{
this.HandleFailure(ex);
throw;
}
finally
{
this.mediationStream.ResetSource();
if (!pending && outputBuffer != null)
{
if (outputBuffer.IsReadable())
{
output.Add(outputBuffer);
}
else
{
outputBuffer.SafeRelease();
}
}
}
}
static void AddBufferToOutput(IByteBuffer outputBuffer, int length, List<object> output)
{
Contract.Assert(length > 0);
output.Add(outputBuffer.SetWriterIndex(outputBuffer.WriterIndex + length));
}
Task<int> ReadFromSslStreamAsync(IByteBuffer outputBuffer, int outputBufferLength)
{
ArraySegment<byte> outlet = outputBuffer.GetIoBuffer(outputBuffer.WriterIndex, outputBufferLength);
return this.sslStream.ReadAsync(outlet.Array, outlet.Offset, outlet.Count);
}
public override void Read(IChannelHandlerContext context)
{
TlsHandlerState oldState = this.state;
if (!oldState.HasAny(TlsHandlerState.AuthenticationCompleted))
{
this.state = oldState | TlsHandlerState.ReadRequestedBeforeAuthenticated;
}
context.Read();
}
bool EnsureAuthenticated()
{
TlsHandlerState oldState = this.state;
if (!oldState.HasAny(TlsHandlerState.AuthenticationStarted))
{
this.state = oldState | TlsHandlerState.Authenticating;
if (this.IsServer)
{
var serverSettings = (ServerTlsSettings)this.settings;
this.sslStream.AuthenticateAsServerAsync(serverSettings.Certificate, serverSettings.NegotiateClientCertificate, serverSettings.EnabledProtocols, serverSettings.CheckCertificateRevocation)
.ContinueWith(HandshakeCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously);
}
else
{
var clientSettings = (ClientTlsSettings)this.settings;
this.sslStream.AuthenticateAsClientAsync(clientSettings.TargetHost, clientSettings.X509CertificateCollection, clientSettings.EnabledProtocols, clientSettings.CheckCertificateRevocation)
.ContinueWith(HandshakeCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously);
}
return false;
}
return oldState.Has(TlsHandlerState.Authenticated);
}
public override Task WriteAsync(IChannelHandlerContext context, object message)
{
if (!(message is IByteBuffer))
{
return TaskEx.FromException(new UnsupportedMessageTypeException(message, typeof(IByteBuffer)));
}
return this.pendingUnencryptedWrites.Add(message);
}
public override void Flush(IChannelHandlerContext context)
{
if (this.pendingUnencryptedWrites.IsEmpty)
{
this.pendingUnencryptedWrites.Add(Unpooled.Empty);
}
if (!this.EnsureAuthenticated())
{
this.state |= TlsHandlerState.FlushedBeforeHandshake;
return;
}
try
{
this.Wrap(context);
}
finally
{
// We may have written some parts of data before an exception was thrown so ensure we always flush.
context.Flush();
}
}
void Wrap(IChannelHandlerContext context)
{
Contract.Assert(context == this.capturedContext);
IByteBuffer buf = null;
try
{
while (true)
{
List<object> messages = this.pendingUnencryptedWrites.Current;
if (messages == null || messages.Count == 0)
{
break;
}
if (messages.Count == 1)
{
buf = (IByteBuffer)messages[0];
}
else
{
buf = context.Allocator.Buffer((int)this.pendingUnencryptedWrites.CurrentSize);
foreach (IByteBuffer buffer in messages)
{
buffer.ReadBytes(buf, buffer.ReadableBytes);
buffer.Release();
}
}
buf.ReadBytes(this.sslStream, buf.ReadableBytes); // this leads to FinishWrap being called 0+ times
buf.Release();
TaskCompletionSource promise = this.pendingUnencryptedWrites.Remove();
Task task = this.lastContextWriteTask;
if (task != null)
{
task.LinkOutcome(promise);
this.lastContextWriteTask = null;
}
else
{
promise.TryComplete();
}
}
}
catch (Exception ex)
{
buf.SafeRelease();
this.HandleFailure(ex);
throw;
}
}
void FinishWrap(byte[] buffer, int offset, int count)
{
IByteBuffer output;
if (count == 0)
{
output = Unpooled.Empty;
}
else
{
output = this.capturedContext.Allocator.Buffer(count);
output.WriteBytes(buffer, offset, count);
}
this.lastContextWriteTask = this.capturedContext.WriteAsync(output);
}
Task FinishWrapNonAppDataAsync(byte[] buffer, int offset, int count)
{
var future = this.capturedContext.WriteAndFlushAsync(Unpooled.WrappedBuffer(buffer, offset, count));
this.ReadIfNeeded(this.capturedContext);
return future;
}
public override Task CloseAsync(IChannelHandlerContext context)
{
this.closeFuture.TryComplete();
this.sslStream.Dispose();
return base.CloseAsync(context);
}
void HandleFailure(Exception cause)
{
// Release all resources such as internal buffers that SSLEngine
// is managing.
try
{
this.sslStream.Dispose();
}
catch (Exception)
{
// todo: evaluate following:
// only log in Debug mode as it most likely harmless and latest chrome still trigger
// this all the time.
//
// See https://github.com/netty/netty/issues/1340
//string msg = ex.Message;
//if (msg == null || !msg.contains("possible truncation attack"))
//{
// //Logger.Debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e);
//}
}
this.NotifyHandshakeFailure(cause);
this.pendingUnencryptedWrites.RemoveAndFailAll(cause);
}
void NotifyHandshakeFailure(Exception cause)
{
if (!this.state.HasAny(TlsHandlerState.AuthenticationCompleted))
{
// handshake was not completed yet => TlsHandler react to failure by closing the channel
this.state = (this.state | TlsHandlerState.FailedAuthentication) & ~TlsHandlerState.Authenticating;
this.capturedContext.FireUserEventTriggered(new TlsHandshakeCompletionEvent(cause));
this.CloseAsync(this.capturedContext);
}
}
sealed class MediationStream : Stream
{
readonly TlsHandler owner;
byte[] input;
int inputStartOffset;
int inputOffset;
int inputLength;
TaskCompletionSource<int> readCompletionSource;
ArraySegment<byte> sslOwnedBuffer;
#if NETSTANDARD1_3
int readByteCount;
#else
SynchronousAsyncResult<int> syncReadResult;
AsyncCallback readCallback;
TaskCompletionSource writeCompletion;
AsyncCallback writeCallback;
#endif
public MediationStream(TlsHandler owner)
{
this.owner = owner;
}
public int SourceReadableBytes => this.inputLength - this.inputOffset;
public void SetSource(byte[] source, int offset)
{
this.input = source;
this.inputStartOffset = offset;
this.inputOffset = 0;
this.inputLength = 0;
}
public void ResetSource()
{
this.input = null;
this.inputLength = 0;
}
public void ExpandSource(int count)
{
Contract.Assert(this.input != null);
this.inputLength += count;
TaskCompletionSource<int> promise = this.readCompletionSource;
if (promise == null)
{
// there is no pending read operation - keep for future
return;
}
ArraySegment<byte> sslBuffer = this.sslOwnedBuffer;
#if NETSTANDARD1_3
this.readByteCount = this.ReadFromInput(sslBuffer.Array, sslBuffer.Offset, sslBuffer.Count);
// hack: this tricks SslStream's continuation to run synchronously instead of dispatching to TP. Remove once Begin/EndRead are available.
new Task(
ms =>
{
var self = (MediationStream)ms;
TaskCompletionSource<int> p = self.readCompletionSource;
this.readCompletionSource = null;
p.TrySetResult(self.readByteCount);
},
this)
.RunSynchronously(TaskScheduler.Default);
#else
int read = this.ReadFromInput(sslBuffer.Array, sslBuffer.Offset, sslBuffer.Count);
this.readCompletionSource = null;
promise.TrySetResult(read);
this.readCallback?.Invoke(promise.Task);
#endif
}
#if NETSTANDARD1_3
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (this.inputLength - this.inputOffset > 0)
{
// we have the bytes available upfront - write out synchronously
int read = this.ReadFromInput(buffer, offset, count);
return Task.FromResult(read);
}
// take note of buffer - we will pass bytes there once available
this.sslOwnedBuffer = new ArraySegment<byte>(buffer, offset, count);
this.readCompletionSource = new TaskCompletionSource<int>();
return this.readCompletionSource.Task;
}
#else
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (this.inputLength - this.inputOffset > 0)
{
// we have the bytes available upfront - write out synchronously
int read = this.ReadFromInput(buffer, offset, count);
return this.PrepareSyncReadResult(read, state);
}
// take note of buffer - we will pass bytes there once available
this.sslOwnedBuffer = new ArraySegment<byte>(buffer, offset, count);
this.readCompletionSource = new TaskCompletionSource<int>(state);
this.readCallback = callback;
return this.readCompletionSource.Task;
}
public override int EndRead(IAsyncResult asyncResult)
{
SynchronousAsyncResult<int> syncResult = this.syncReadResult;
if (ReferenceEquals(asyncResult, syncResult))
{
return syncResult.Result;
}
Contract.Assert(!((Task<int>)asyncResult).IsCanceled);
try
{
return ((Task<int>)asyncResult).Result;
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw; // unreachable
}
finally
{
this.readCompletionSource = null;
this.readCallback = null;
this.sslOwnedBuffer = default(ArraySegment<byte>);
}
}
IAsyncResult PrepareSyncReadResult(int readBytes, object state)
{
// it is safe to reuse sync result object as it can't lead to leak (no way to attach to it via handle)
SynchronousAsyncResult<int> result = this.syncReadResult ?? (this.syncReadResult = new SynchronousAsyncResult<int>());
result.Result = readBytes;
result.AsyncState = state;
return result;
}
#endif
public override void Write(byte[] buffer, int offset, int count) => this.owner.FinishWrap(buffer, offset, count);
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
=> this.owner.FinishWrapNonAppDataAsync(buffer, offset, count);
#if !NETSTANDARD1_3
static readonly Action<Task, object> WriteCompleteCallback = HandleChannelWriteComplete;
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
Task task = this.WriteAsync(buffer, offset, count);
switch (task.Status)
{
case TaskStatus.RanToCompletion:
// write+flush completed synchronously (and successfully)
var result = new SynchronousAsyncResult<int>();
result.AsyncState = state;
callback(result);
return result;
default:
this.writeCallback = callback;
var tcs = new TaskCompletionSource(state);
this.writeCompletion = tcs;
task.ContinueWith(WriteCompleteCallback, this, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
}
static void HandleChannelWriteComplete(Task writeTask, object state)
{
var self = (MediationStream)state;
switch (writeTask.Status)
{
case TaskStatus.RanToCompletion:
self.writeCompletion.TryComplete();
break;
case TaskStatus.Canceled:
self.writeCompletion.TrySetCanceled();
break;
case TaskStatus.Faulted:
self.writeCompletion.TrySetException(writeTask.Exception);
break;
default:
throw new ArgumentOutOfRangeException("Unexpected task status: " + writeTask.Status);
}
self.writeCallback?.Invoke(self.writeCompletion.Task);
}
public override void EndWrite(IAsyncResult asyncResult)
{
this.writeCallback = null;
this.writeCompletion = null;
if (asyncResult is SynchronousAsyncResult<int>)
{
return;
}
try
{
((Task<int>)asyncResult).Wait();
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
}
#endif
int ReadFromInput(byte[] destination, int destinationOffset, int destinationCapacity)
{
Contract.Assert(destination != null);
byte[] source = this.input;
int readableBytes = this.inputLength - this.inputOffset;
int length = Math.Min(readableBytes, destinationCapacity);
Buffer.BlockCopy(source, this.inputStartOffset + this.inputOffset, destination, destinationOffset, length);
this.inputOffset += length;
return length;
}
public override void Flush()
{
// NOOP: called on SslStream.Close
}
#region plumbing
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
#endregion
#region sync result
sealed class SynchronousAsyncResult<T> : IAsyncResult
{
public T Result { get; set; }
public bool IsCompleted => true;
public WaitHandle AsyncWaitHandle
{
get { throw new InvalidOperationException("Cannot wait on a synchronous result."); }
}
public object AsyncState { get; set; }
public bool CompletedSynchronously => true;
}
#endregion
}
}
[Flags]
enum TlsHandlerState
{
Authenticating = 1,
Authenticated = 1 << 1,
FailedAuthentication = 1 << 2,
ReadRequestedBeforeAuthenticated = 1 << 3,
FlushedBeforeHandshake = 1 << 4,
AuthenticationStarted = Authenticating | Authenticated | FailedAuthentication,
AuthenticationCompleted = Authenticated | FailedAuthentication
}
static class TlsHandlerStateExtensions
{
public static bool Has(this TlsHandlerState value, TlsHandlerState testValue) => (value & testValue) == testValue;
public static bool HasAny(this TlsHandlerState value, TlsHandlerState testValue) => (value & testValue) != 0;
}
}
| |
// 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.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Samples.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace CreateSimpleInternetFacingLoadBalancer
{
public class Program
{
/**
* Azure Network sample for creating a simple Internet facing load balancer -
*
* Summary ...
*
* - This sample creates a simple Internet facing load balancer that receives network traffic on
* port 80 and sends load-balanced traffic to two virtual machines
*
* Details ...
*
* 1. Create two virtual machines for the backend...
* - in the same availability set
* - in the same virtual network
*
* Create an Internet facing load balancer with ...
* - A public IP address assigned to an implicitly created frontend
* - One backend address pool with the two virtual machines to receive HTTP network traffic from the load balancer
* - One load balancing rule for HTTP to map public ports on the load
* balancer to ports in the backend address pool
* Delete the load balancer
*/
public static void RunSample(IAzure azure)
{
string rgName = SdkContext.RandomResourceName("rg", 15);
string vnetName = SdkContext.RandomResourceName("vnet", 24);
Region region = Region.USEast;
string loadBalancerName = SdkContext.RandomResourceName("lb", 18);
string publicIpName = SdkContext.RandomResourceName("pip", 18);
string availSetName = SdkContext.RandomResourceName("av", 24);
string httpLoadBalancingRuleName = "httpRule";
string userName = "tirekicker";
string sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD [email protected]";
try
{
//=============================================================
// Define a common availability set for the backend virtual machines
ICreatable<IAvailabilitySet> availabilitySetDefinition = azure.AvailabilitySets.Define(availSetName)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithSku(AvailabilitySetSkuTypes.Managed);
//=============================================================
// Define a common virtual network for the virtual machines
ICreatable<INetwork> networkDefinition = azure.Networks.Define(vnetName)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithAddressSpace("10.0.0.0/28");
//=============================================================
// Create two virtual machines for the backend of the load balancer
Utilities.Log("Creating two virtual machines in the frontend subnet ...\n"
+ "and putting them in the shared availability set and virtual network.");
List<ICreatable<IVirtualMachine>> virtualMachineDefinitions = new List<ICreatable<IVirtualMachine>>();
for (int i = 0; i < 2; i++)
{
virtualMachineDefinitions.Add(
azure.VirtualMachines.Define(SdkContext.RandomResourceName("vm", 24))
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithNewPrimaryNetwork(networkDefinition)
.WithPrimaryPrivateIPAddressDynamic()
.WithoutPrimaryPublicIPAddress()
.WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
.WithRootUsername(userName)
.WithSsh(sshKey)
.WithSize(VirtualMachineSizeTypes.StandardD3V2)
.WithNewAvailabilitySet(availabilitySetDefinition));
}
Stopwatch stopwatch = Stopwatch.StartNew();
// Create and retrieve the VMs by the interface accepted by the load balancing rule
var virtualMachines = azure.VirtualMachines.Create(virtualMachineDefinitions);
stopwatch.Stop();
Utilities.Log("Created 2 Linux VMs: (took " + (stopwatch.ElapsedMilliseconds / 1000) + " seconds)\n");
// Print virtual machine details
foreach(var vm in virtualMachines)
{
Utilities.PrintVirtualMachine((IVirtualMachine)vm);
}
//=============================================================
// Create an Internet facing load balancer
// - implicitly creating a frontend with the public IP address definition provided for the load balancing rule
// - implicitly creating a backend and assigning the created virtual machines to it
// - creating a load balancing rule, mapping public ports on the load balancer to ports in the backend address pool
Utilities.Log(
"Creating a Internet facing load balancer with ...\n"
+ "- A frontend public IP address\n"
+ "- One backend address pool with the two virtual machines\n"
+ "- One load balancing rule for HTTP, mapping public ports on the load\n"
+ " balancer to ports in the backend address pool");
var loadBalancer = azure.LoadBalancers.Define(loadBalancerName)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
// Add a load balancing rule sending traffic from an implicitly created frontend with the public IP address
// to an implicitly created backend with the two virtual machines
.DefineLoadBalancingRule(httpLoadBalancingRuleName)
.WithProtocol(TransportProtocol.Tcp)
.FromNewPublicIPAddress(publicIpName)
.FromFrontendPort(80)
.ToExistingVirtualMachines(new List<IHasNetworkInterfaces>(virtualMachines)) // Convert VMs to the expected interface
.Attach()
.Create();
// Print load balancer details
Utilities.Log("Created a load balancer");
Utilities.PrintLoadBalancer(loadBalancer);
//=============================================================
// Update a load balancer with 15 minute idle time for the load balancing rule
Utilities.Log("Updating the load balancer ...");
loadBalancer.Update()
.UpdateLoadBalancingRule(httpLoadBalancingRuleName)
.WithIdleTimeoutInMinutes(15)
.Parent()
.Apply();
Utilities.Log("Updated the load balancer with a TCP idle timeout to 15 minutes");
//=============================================================
// Show the load balancer info
Utilities.PrintLoadBalancer(loadBalancer);
//=============================================================
// Remove a load balancer
Utilities.Log("Deleting load balancer " + loadBalancerName
+ "(" + loadBalancer.Id + ")");
azure.LoadBalancers.DeleteById(loadBalancer.Id);
Utilities.Log("Deleted load balancer" + loadBalancerName);
}
finally
{
try
{
Utilities.Log("Starting the deletion of the resource group: " + rgName);
azure.ResourceGroups.BeginDeleteByName(rgName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
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 ex)
{
Utilities.Log(ex);
}
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Rendering\Testing\Tcl\labeledContours.tcl
// output file is AVlabeledContours.cs
/// <summary>
/// The testing class derived from AVlabeledContours
/// </summary>
public class AVlabeledContoursClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVlabeledContours(String [] argv)
{
//Prefix Content is: ""
// demonstrate labeling of contour with scalar value[]
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
// Read a slice and contour it[]
v16 = new vtkVolume16Reader();
v16.SetDataDimensions((int)64,(int)64);
v16.GetOutput().SetOrigin((double)0.0,(double)0.0,(double)0.0);
v16.SetDataByteOrderToLittleEndian();
v16.SetFilePrefix((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/headsq/quarter");
v16.SetImageRange((int)45,(int)45);
v16.SetDataSpacing((double)3.2,(double)3.2,(double)1.5);
iso = new vtkContourFilter();
iso.SetInputConnection((vtkAlgorithmOutput)v16.GetOutputPort());
iso.GenerateValues((int)6,(double)500,(double)1150);
iso.Update();
numPts = iso.GetOutput().GetNumberOfPoints();
isoMapper = vtkPolyDataMapper.New();
isoMapper.SetInputConnection((vtkAlgorithmOutput)iso.GetOutputPort());
isoMapper.ScalarVisibilityOn();
isoMapper.SetScalarRange((double)((vtkDataSet)iso.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)iso.GetOutput()).GetScalarRange()[1]);
isoActor = new vtkActor();
isoActor.SetMapper((vtkMapper)isoMapper);
// Subsample the points and label them[]
mask = new vtkMaskPoints();
mask.SetInputConnection((vtkAlgorithmOutput)iso.GetOutputPort());
mask.SetOnRatio((int)(numPts/50));
mask.SetMaximumNumberOfPoints((int)50);
mask.RandomModeOn();
// Create labels for points - only show visible points[]
visPts = new vtkSelectVisiblePoints();
visPts.SetInputConnection((vtkAlgorithmOutput)mask.GetOutputPort());
visPts.SetRenderer((vtkRenderer)ren1);
ldm = new vtkLabeledDataMapper();
ldm.SetInputConnection((vtkAlgorithmOutput)mask.GetOutputPort());
// ldm SetLabelFormat "%g"[]
ldm.SetLabelModeToLabelScalars();
tprop = ldm.GetLabelTextProperty();
tprop.SetFontFamilyToArial();
tprop.SetFontSize((int)10);
tprop.SetColor((double)1,(double)0,(double)0);
contourLabels = new vtkActor2D();
contourLabels.SetMapper((vtkMapper2D)ldm);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor2D((vtkProp)isoActor);
ren1.AddActor2D((vtkProp)contourLabels);
ren1.SetBackground((double)1,(double)1,(double)1);
renWin.SetSize((int)500,(int)500);
renWin.Render();
ren1.GetActiveCamera().Zoom((double)1.5);
// render the image[]
//[]
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkVolume16Reader v16;
static vtkContourFilter iso;
static long numPts;
static vtkPolyDataMapper isoMapper;
static vtkActor isoActor;
static vtkMaskPoints mask;
static vtkSelectVisiblePoints visPts;
static vtkLabeledDataMapper ldm;
static vtkTextProperty tprop;
static vtkActor2D contourLabels;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkVolume16Reader Getv16()
{
return v16;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setv16(vtkVolume16Reader toSet)
{
v16 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkContourFilter Getiso()
{
return iso;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiso(vtkContourFilter toSet)
{
iso = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static long GetnumPts()
{
return numPts;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetnumPts(long toSet)
{
numPts = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetisoMapper()
{
return isoMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetisoMapper(vtkPolyDataMapper toSet)
{
isoMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetisoActor()
{
return isoActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetisoActor(vtkActor toSet)
{
isoActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkMaskPoints Getmask()
{
return mask;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmask(vtkMaskPoints toSet)
{
mask = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkSelectVisiblePoints GetvisPts()
{
return visPts;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetvisPts(vtkSelectVisiblePoints toSet)
{
visPts = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkLabeledDataMapper Getldm()
{
return ldm;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setldm(vtkLabeledDataMapper toSet)
{
ldm = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTextProperty Gettprop()
{
return tprop;
}
///<summary> A Set Method for Static Variables </summary>
public static void Settprop(vtkTextProperty toSet)
{
tprop = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor2D GetcontourLabels()
{
return contourLabels;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcontourLabels(vtkActor2D toSet)
{
contourLabels = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(v16!= null){v16.Dispose();}
if(iso!= null){iso.Dispose();}
if(isoMapper!= null){isoMapper.Dispose();}
if(isoActor!= null){isoActor.Dispose();}
if(mask!= null){mask.Dispose();}
if(visPts!= null){visPts.Dispose();}
if(ldm!= null){ldm.Dispose();}
if(tprop!= null){tprop.Dispose();}
if(contourLabels!= null){contourLabels.Dispose();}
}
}
//--- end of script --//
| |
// 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.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using System.Net.Http.WinHttpHandlerUnitTests;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
internal static partial class Interop
{
internal static partial class Crypt32
{
public static bool CertFreeCertificateContext(IntPtr certContext)
{
return true;
}
public static bool CertVerifyCertificateChainPolicy(
IntPtr pszPolicyOID,
SafeX509ChainHandle pChainContext,
ref CERT_CHAIN_POLICY_PARA pPolicyPara,
ref CERT_CHAIN_POLICY_STATUS pPolicyStatus)
{
return true;
}
}
internal static partial class Kernel32
{
public static string GetMessage(int error, IntPtr moduleName)
{
string messageFormat = "Fake error message, error code: {0}";
return string.Format(messageFormat, error);
}
public static IntPtr GetModuleHandle(string moduleName)
{
return IntPtr.Zero;
}
}
internal static partial class WinHttp
{
public static SafeWinHttpHandle WinHttpOpen(
IntPtr userAgent,
uint accessType,
string proxyName,
string proxyBypass,
uint flags)
{
if (TestControl.WinHttpOpen.ErrorWithApiCall)
{
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_HANDLE;
return new FakeSafeWinHttpHandle(false);
}
if (accessType == Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY &&
!TestControl.WinHttpAutomaticProxySupport)
{
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_PARAMETER;
return new FakeSafeWinHttpHandle(false);
}
APICallHistory.ProxyInfo proxyInfo;
proxyInfo.AccessType = accessType;
proxyInfo.Proxy = proxyName;
proxyInfo.ProxyBypass = proxyBypass;
APICallHistory.SessionProxySettings = proxyInfo;
return new FakeSafeWinHttpHandle(true);
}
public static bool WinHttpCloseHandle(IntPtr sessionHandle)
{
Marshal.FreeHGlobal(sessionHandle);
return true;
}
public static SafeWinHttpHandle WinHttpConnect(
SafeWinHttpHandle sessionHandle,
string serverName,
ushort serverPort,
uint reserved)
{
return new FakeSafeWinHttpHandle(true);
}
public static bool WinHttpAddRequestHeaders(
SafeWinHttpHandle requestHandle,
StringBuilder headers,
uint headersLength,
uint modifiers)
{
return true;
}
public static bool WinHttpAddRequestHeaders(
SafeWinHttpHandle requestHandle,
string headers,
uint headersLength,
uint modifiers)
{
return true;
}
public static SafeWinHttpHandle WinHttpOpenRequest(
SafeWinHttpHandle connectHandle,
string verb,
string objectName,
string version,
string referrer,
string acceptTypes,
uint flags)
{
return new FakeSafeWinHttpHandle(true);
}
public static bool WinHttpSendRequest(
SafeWinHttpHandle requestHandle,
StringBuilder headers,
uint headersLength,
IntPtr optional,
uint optionalLength,
uint totalLength,
IntPtr context)
{
Task.Run(() => {
var fakeHandle = (FakeSafeWinHttpHandle)requestHandle;
fakeHandle.Context = context;
fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, IntPtr.Zero, 0);
});
return true;
}
public static bool WinHttpReceiveResponse(SafeWinHttpHandle requestHandle, IntPtr reserved)
{
Task.Run(() => {
var fakeHandle = (FakeSafeWinHttpHandle)requestHandle;
bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReceiveResponse.Delay);
if (aborted || TestControl.WinHttpReadData.ErrorOnCompletion)
{
Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult;
asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_RECEIVE_RESPONSE);
asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED :
Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR;
TestControl.WinHttpReadData.Wait();
fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult);
}
else
{
TestControl.WinHttpReceiveResponse.Wait();
fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, IntPtr.Zero, 0);
}
});
return true;
}
public static bool WinHttpQueryDataAvailable(
SafeWinHttpHandle requestHandle,
IntPtr bytesAvailableShouldBeNullForAsync)
{
if (bytesAvailableShouldBeNullForAsync != IntPtr.Zero)
{
return false;
}
if (TestControl.WinHttpQueryDataAvailable.ErrorWithApiCall)
{
return false;
}
Task.Run(() => {
var fakeHandle = (FakeSafeWinHttpHandle)requestHandle;
bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReadData.Delay);
if (aborted || TestControl.WinHttpQueryDataAvailable.ErrorOnCompletion)
{
Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult;
asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_QUERY_DATA_AVAILABLE);
asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED :
Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR;
TestControl.WinHttpQueryDataAvailable.Wait();
fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult);
}
else
{
int bufferSize = sizeof(int);
IntPtr buffer = Marshal.AllocHGlobal(bufferSize);
Marshal.WriteInt32(buffer, TestServer.DataAvailable);
fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, buffer, (uint)bufferSize);
Marshal.FreeHGlobal(buffer);
}
});
return true;
}
public static bool WinHttpReadData(
SafeWinHttpHandle requestHandle,
IntPtr buffer,
uint bufferSize,
IntPtr bytesReadShouldBeNullForAsync)
{
if (bytesReadShouldBeNullForAsync != IntPtr.Zero)
{
return false;
}
if (TestControl.WinHttpReadData.ErrorWithApiCall)
{
return false;
}
uint bytesRead;
TestServer.ReadFromResponseBody(buffer, bufferSize, out bytesRead);
Task.Run(() => {
var fakeHandle = (FakeSafeWinHttpHandle)requestHandle;
bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReadData.Delay);
if (aborted || TestControl.WinHttpReadData.ErrorOnCompletion)
{
Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult;
asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_READ_DATA);
asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED :
Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR;
TestControl.WinHttpReadData.Wait();
fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult);
}
else
{
TestControl.WinHttpReadData.Wait();
fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytesRead);
}
});
return true;
}
public static bool WinHttpQueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel, string name,
IntPtr buffer,
ref uint bufferLength,
ref uint index)
{
string httpVersion = "HTTP/1.1";
string statusText = "OK";
if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_SET_COOKIE)
{
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND;
return false;
}
if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_VERSION)
{
return CopyToBufferOrFailIfInsufficientBufferLength(httpVersion, buffer, ref bufferLength);
}
if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT)
{
return CopyToBufferOrFailIfInsufficientBufferLength(statusText, buffer, ref bufferLength);
}
if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING)
{
string compression =
TestServer.ResponseHeaders.Contains("Content-Encoding: deflate") ? "deflate" :
TestServer.ResponseHeaders.Contains("Content-Encoding: gzip") ? "gzip" :
null;
if (compression == null)
{
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND;
return false;
}
return CopyToBufferOrFailIfInsufficientBufferLength(compression, buffer, ref bufferLength);
}
if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF)
{
return CopyToBufferOrFailIfInsufficientBufferLength(TestServer.ResponseHeaders, buffer, ref bufferLength);
}
return false;
}
private static bool CopyToBufferOrFailIfInsufficientBufferLength(string value, IntPtr buffer, ref uint bufferLength)
{
// The length of the string (plus terminating null char) in bytes.
uint bufferLengthNeeded = ((uint)value.Length + 1) * sizeof(char);
if (buffer == IntPtr.Zero || bufferLength < bufferLengthNeeded)
{
bufferLength = bufferLengthNeeded;
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER;
return false;
}
// Copy the string to the buffer.
char[] temp = new char[value.Length + 1]; // null terminated.
value.CopyTo(0, temp, 0, value.Length);
Marshal.Copy(temp, 0, buffer, temp.Length);
// The length in bytes, minus the length of the null char at the end.
bufferLength = (uint)value.Length * sizeof(char);
return true;
}
public static bool WinHttpQueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel,
string name,
ref uint number,
ref uint bufferLength,
IntPtr index)
{
infoLevel &= ~Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER;
if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE)
{
number = (uint)HttpStatusCode.OK;
return true;
}
return false;
}
public static bool WinHttpQueryOption(
SafeWinHttpHandle handle,
uint option,
StringBuilder buffer,
ref uint bufferSize)
{
string uri = "http://www.contoso.com/";
if (option == Interop.WinHttp.WINHTTP_OPTION_URL)
{
if (buffer == null)
{
bufferSize = ((uint)uri.Length + 1) * 2;
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER;
return false;
}
buffer.Append(uri);
return true;
}
return false;
}
public static bool WinHttpQueryOption(
SafeWinHttpHandle handle,
uint option,
ref IntPtr buffer,
ref uint bufferSize)
{
return true;
}
public static bool WinHttpQueryOption(
SafeWinHttpHandle handle,
uint option,
IntPtr buffer,
ref uint bufferSize)
{
return true;
}
public static bool WinHttpQueryOption(
SafeWinHttpHandle handle,
uint option,
ref uint buffer,
ref uint bufferSize)
{
return true;
}
public static bool WinHttpWriteData(
SafeWinHttpHandle requestHandle,
IntPtr buffer,
uint bufferSize,
IntPtr bytesWrittenShouldBeNullForAsync)
{
if (bytesWrittenShouldBeNullForAsync != IntPtr.Zero)
{
return false;
}
if (TestControl.WinHttpWriteData.ErrorWithApiCall)
{
return false;
}
uint bytesWritten;
TestServer.WriteToRequestBody(buffer, bufferSize);
bytesWritten = bufferSize;
Task.Run(() => {
var fakeHandle = (FakeSafeWinHttpHandle)requestHandle;
bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpWriteData.Delay);
if (aborted || TestControl.WinHttpWriteData.ErrorOnCompletion)
{
Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult;
asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_WRITE_DATA);
asyncResult.dwError = Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR;
TestControl.WinHttpWriteData.Wait();
fakeHandle.InvokeCallback(aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED :
Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult);
}
else
{
TestControl.WinHttpWriteData.Wait();
fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, IntPtr.Zero, 0);
}
});
return true;
}
public static bool WinHttpSetOption(
SafeWinHttpHandle handle,
uint option,
ref uint optionData,
uint optionLength = sizeof(uint))
{
if (option == Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION & !TestControl.WinHttpDecompressionSupport)
{
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION;
return false;
}
if (option == Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE &&
optionData == Interop.WinHttp.WINHTTP_DISABLE_COOKIES)
{
APICallHistory.WinHttpOptionDisableCookies = true;
}
else if (option == Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE &&
optionData == Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION)
{
APICallHistory.WinHttpOptionEnableSslRevocation = true;
}
else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS)
{
APICallHistory.WinHttpOptionSecureProtocols = optionData;
}
else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS)
{
APICallHistory.WinHttpOptionSecurityFlags = optionData;
}
else if (option == Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS)
{
APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects = optionData;
}
else if (option == Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY)
{
APICallHistory.WinHttpOptionRedirectPolicy = optionData;
}
return true;
}
public static bool WinHttpSetOption(
SafeWinHttpHandle handle,
uint option,
string optionData,
uint optionLength)
{
if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_USERNAME)
{
APICallHistory.ProxyUsernameWithDomain = optionData;
}
else if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_PASSWORD)
{
APICallHistory.ProxyPassword = optionData;
}
else if (option == Interop.WinHttp.WINHTTP_OPTION_USERNAME)
{
APICallHistory.ServerUsernameWithDomain = optionData;
}
else if (option == Interop.WinHttp.WINHTTP_OPTION_PASSWORD)
{
APICallHistory.ServerPassword = optionData;
}
return true;
}
public static bool WinHttpSetOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionLength)
{
if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY)
{
var proxyInfo = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_PROXY_INFO>(optionData);
var proxyInfoHistory = new APICallHistory.ProxyInfo();
proxyInfoHistory.AccessType = proxyInfo.AccessType;
proxyInfoHistory.Proxy = Marshal.PtrToStringUni(proxyInfo.Proxy);
proxyInfoHistory.ProxyBypass = Marshal.PtrToStringUni(proxyInfo.ProxyBypass);
APICallHistory.RequestProxySettings = proxyInfoHistory;
}
else if (option == Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT)
{
APICallHistory.WinHttpOptionClientCertContext.Add(optionData);
}
return true;
}
public static bool WinHttpSetCredentials(
SafeWinHttpHandle requestHandle,
uint authTargets,
uint authScheme,
string userName,
string password,
IntPtr reserved)
{
return true;
}
public static bool WinHttpQueryAuthSchemes(
SafeWinHttpHandle requestHandle,
out uint supportedSchemes,
out uint firstScheme,
out uint authTarget)
{
supportedSchemes = 0;
firstScheme = 0;
authTarget = 0;
return true;
}
public static bool WinHttpSetTimeouts(
SafeWinHttpHandle handle,
int resolveTimeout,
int connectTimeout,
int sendTimeout,
int receiveTimeout)
{
return true;
}
public static bool WinHttpGetIEProxyConfigForCurrentUser(
out Interop.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig)
{
if (FakeRegistry.WinInetProxySettings.RegistryKeyMissing)
{
proxyConfig.AutoDetect = false;
proxyConfig.AutoConfigUrl = IntPtr.Zero;
proxyConfig.Proxy = IntPtr.Zero;
proxyConfig.ProxyBypass = IntPtr.Zero;
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_FILE_NOT_FOUND;
return false;
}
proxyConfig.AutoDetect = FakeRegistry.WinInetProxySettings.AutoDetect;
proxyConfig.AutoConfigUrl = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.AutoConfigUrl);
proxyConfig.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy);
proxyConfig.ProxyBypass = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.ProxyBypass);
return true;
}
public static bool WinHttpGetProxyForUrl(
SafeWinHttpHandle sessionHandle,
string url,
ref Interop.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions,
out Interop.WinHttp.WINHTTP_PROXY_INFO proxyInfo)
{
if (TestControl.PACFileNotDetectedOnNetwork)
{
proxyInfo.AccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
proxyInfo.Proxy = IntPtr.Zero;
proxyInfo.ProxyBypass = IntPtr.Zero;
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED;
return false;
}
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY;
proxyInfo.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy);
proxyInfo.ProxyBypass = IntPtr.Zero;
return true;
}
public static IntPtr WinHttpSetStatusCallback(
SafeWinHttpHandle handle,
Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback,
uint notificationFlags,
IntPtr reserved)
{
if (handle == null)
{
throw new ArgumentNullException(nameof(handle));
}
var fakeHandle = (FakeSafeWinHttpHandle)handle;
fakeHandle.Callback = callback;
return IntPtr.Zero;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using GUI.Utils;
using OpenTK.Graphics.OpenGL;
using ValveResourceFormat;
using ValveResourceFormat.Blocks;
using ValveResourceFormat.ResourceTypes;
using ValveResourceFormat.Serialization;
namespace GUI.Types.Renderer
{
internal class RenderableMesh
{
public AABB BoundingBox { get; }
public Vector4 Tint { get; set; } = Vector4.One;
private readonly VrfGuiContext guiContext;
public List<DrawCall> DrawCallsOpaque { get; } = new List<DrawCall>();
public List<DrawCall> DrawCallsBlended { get; } = new List<DrawCall>();
public int? AnimationTexture { get; private set; }
public int AnimationTextureSize { get; private set; }
public float Time { get; private set; }
private Mesh mesh;
private List<DrawCall> DrawCallsAll = new List<DrawCall>();
public RenderableMesh(Mesh mesh, VrfGuiContext guiContext, Dictionary<string, string> skinMaterials = null)
{
this.guiContext = guiContext;
this.mesh = mesh;
BoundingBox = new AABB(mesh.MinBounds, mesh.MaxBounds);
SetupDrawCalls(mesh, skinMaterials);
}
public IEnumerable<string> GetSupportedRenderModes()
=> DrawCallsAll
.SelectMany(drawCall => drawCall.Shader.RenderModes)
.Distinct();
public void SetRenderMode(string renderMode)
{
var drawCalls = DrawCallsAll;
foreach (var call in drawCalls)
{
// Recycle old shader parameters that are not render modes since we are scrapping those anyway
var parameters = call.Shader.Parameters
.Where(kvp => !kvp.Key.StartsWith("renderMode"))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
if (renderMode != null && call.Shader.RenderModes.Contains(renderMode))
{
parameters.Add($"renderMode_{renderMode}", true);
}
call.Shader = guiContext.ShaderLoader.LoadShader(call.Shader.Name, parameters);
call.VertexArrayObject = guiContext.MeshBufferCache.GetVertexArrayObject(
mesh.VBIB,
call.Shader,
call.VertexBuffer.Id,
call.IndexBuffer.Id);
}
}
public void SetAnimationTexture(int? texture, int animationTextureSize)
{
AnimationTexture = texture;
AnimationTextureSize = animationTextureSize;
}
public void SetSkin(Dictionary<string, string> skinMaterials)
{
var data = mesh.GetData();
var sceneObjects = data.GetArray("m_sceneObjects");
int i = 0;
foreach (var sceneObject in sceneObjects)
{
var objectDrawCalls = sceneObject.GetArray("m_drawCalls");
foreach (var objectDrawCall in objectDrawCalls)
{
var materialName = objectDrawCall.GetProperty<string>("m_material") ?? objectDrawCall.GetProperty<string>("m_pMaterial");
if (skinMaterials != null && skinMaterials.ContainsKey(materialName))
{
materialName = skinMaterials[materialName];
}
var material = guiContext.MaterialLoader.GetMaterial(materialName);
var isOverlay = material.Material.IntParams.ContainsKey("F_OVERLAY");
// Ignore overlays for now
if (isOverlay)
{
continue;
}
var shaderArguments = new Dictionary<string, bool>();
if (Mesh.IsCompressedNormalTangent(objectDrawCall))
{
shaderArguments.Add("fulltangent", false);
}
SetupDrawCallMaterial(DrawCallsAll[i++], shaderArguments, material);
}
}
}
public void Update(float timeStep)
{
Time += timeStep;
}
private void SetupDrawCalls(Mesh mesh, Dictionary<string, string> skinMaterials)
{
var vbib = mesh.VBIB;
var data = mesh.GetData();
var gpuMeshBuffers = guiContext.MeshBufferCache.GetVertexIndexBuffers(vbib);
//Prepare drawcalls
var sceneObjects = data.GetArray("m_sceneObjects");
foreach (var sceneObject in sceneObjects)
{
var objectDrawCalls = sceneObject.GetArray("m_drawCalls");
foreach (var objectDrawCall in objectDrawCalls)
{
var materialName = objectDrawCall.GetProperty<string>("m_material") ?? objectDrawCall.GetProperty<string>("m_pMaterial");
if (skinMaterials != null && skinMaterials.ContainsKey(materialName))
{
materialName = skinMaterials[materialName];
}
var material = guiContext.MaterialLoader.GetMaterial(materialName);
var isOverlay = material.Material.IntParams.ContainsKey("F_OVERLAY");
// Ignore overlays for now
if (isOverlay)
{
continue;
}
var shaderArguments = new Dictionary<string, bool>();
if (Mesh.IsCompressedNormalTangent(objectDrawCall))
{
shaderArguments.Add("fulltangent", false);
}
// TODO: Don't pass around so much shit
var drawCall = CreateDrawCall(objectDrawCall, vbib, shaderArguments, material);
DrawCallsAll.Add(drawCall);
if (drawCall.Material.IsBlended)
{
DrawCallsBlended.Add(drawCall);
}
else
{
DrawCallsOpaque.Add(drawCall);
}
}
}
//drawCalls = drawCalls.OrderBy(x => x.Material.Parameters.Name).ToList();
}
private DrawCall CreateDrawCall(IKeyValueCollection objectDrawCall, VBIB vbib, IDictionary<string, bool> shaderArguments, RenderMaterial material)
{
var drawCall = new DrawCall();
string primitiveType = objectDrawCall.GetProperty<object>("m_nPrimitiveType") switch
{
string primitiveTypeString => primitiveTypeString,
byte primitiveTypeByte =>
(primitiveTypeByte == 5) ? "RENDER_PRIM_TRIANGLES" : ("UNKNOWN_" + primitiveTypeByte),
_ => throw new NotImplementedException("Unknown PrimitiveType in drawCall!")
};
switch (primitiveType)
{
case "RENDER_PRIM_TRIANGLES":
drawCall.PrimitiveType = PrimitiveType.Triangles;
break;
default:
throw new NotImplementedException("Unknown PrimitiveType in drawCall! (" + primitiveType + ")");
}
SetupDrawCallMaterial(drawCall, shaderArguments, material);
var indexBufferObject = objectDrawCall.GetSubCollection("m_indexBuffer");
var indexBuffer = default(DrawBuffer);
indexBuffer.Id = Convert.ToUInt32(indexBufferObject.GetProperty<object>("m_hBuffer"));
indexBuffer.Offset = Convert.ToUInt32(indexBufferObject.GetProperty<object>("m_nBindOffsetBytes"));
drawCall.IndexBuffer = indexBuffer;
var indexElementSize = vbib.IndexBuffers[(int)drawCall.IndexBuffer.Id].ElementSizeInBytes;
//drawCall.BaseVertex = Convert.ToUInt32(objectDrawCall.GetProperty<object>("m_nBaseVertex"));
//drawCall.VertexCount = Convert.ToUInt32(objectDrawCall.GetProperty<object>("m_nVertexCount"));
drawCall.StartIndex = Convert.ToUInt32(objectDrawCall.GetProperty<object>("m_nStartIndex")) * indexElementSize;
drawCall.IndexCount = Convert.ToInt32(objectDrawCall.GetProperty<object>("m_nIndexCount"));
if (objectDrawCall.ContainsKey("m_vTintColor"))
{
var tintColor = objectDrawCall.GetSubCollection("m_vTintColor").ToVector3();
drawCall.TintColor = new OpenTK.Vector3(tintColor.X, tintColor.Y, tintColor.Z);
}
if (indexElementSize == 2)
{
//shopkeeper_vr
drawCall.IndexType = DrawElementsType.UnsignedShort;
}
else if (indexElementSize == 4)
{
//glados
drawCall.IndexType = DrawElementsType.UnsignedInt;
}
else
{
throw new Exception("Unsupported index type");
}
var m_vertexBuffer = objectDrawCall.GetArray("m_vertexBuffers")[0]; // TODO: Not just 0
var vertexBuffer = default(DrawBuffer);
vertexBuffer.Id = Convert.ToUInt32(m_vertexBuffer.GetProperty<object>("m_hBuffer"));
vertexBuffer.Offset = Convert.ToUInt32(m_vertexBuffer.GetProperty<object>("m_nBindOffsetBytes"));
drawCall.VertexBuffer = vertexBuffer;
drawCall.VertexArrayObject = guiContext.MeshBufferCache.GetVertexArrayObject(
vbib,
drawCall.Shader,
drawCall.VertexBuffer.Id,
drawCall.IndexBuffer.Id);
return drawCall;
}
private void SetupDrawCallMaterial(DrawCall drawCall, IDictionary<string, bool> shaderArguments, RenderMaterial material)
{
drawCall.Material = material;
// Add shader parameters from material to the shader parameters from the draw call
var combinedShaderParameters = shaderArguments
.Concat(material.Material.GetShaderArguments())
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
// Load shader
drawCall.Shader = guiContext.ShaderLoader.LoadShader(drawCall.Material.Material.ShaderName, combinedShaderParameters);
//Bind and validate shader
GL.UseProgram(drawCall.Shader.Program);
if (!drawCall.Material.Textures.ContainsKey("g_tTintMask"))
{
drawCall.Material.Textures.Add("g_tTintMask", MaterialLoader.CreateSolidTexture(1f, 1f, 1f));
}
if (!drawCall.Material.Textures.ContainsKey("g_tNormal"))
{
drawCall.Material.Textures.Add("g_tNormal", MaterialLoader.CreateSolidTexture(0.5f, 1f, 0.5f));
}
}
}
internal interface IRenderableMeshCollection
{
IEnumerable<RenderableMesh> RenderableMeshes { get; }
}
}
| |
// 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.Linq;
using System.Xml.Linq;
using FluentAssertions;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.DotNet.Cli.List.Package.Tests
{
public class GivenDotnetListPackage : TestBase
{
private readonly ITestOutputHelper _output;
public GivenDotnetListPackage(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void RequestedAndResolvedVersionsMatch()
{
var testAsset = "TestAppSimple";
var projectDirectory = TestAssets
.Get(testAsset)
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var packageName = "Newtonsoft.Json";
var packageVersion = "9.0.1";
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"add package {packageName} --version {packageVersion}");
cmd.Should().Pass();
new RestoreCommand()
.WithWorkingDirectory(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr();
new ListPackageCommand()
.WithPath(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr()
.And.HaveStdOutContainingIgnoreSpaces(packageName+packageVersion+packageVersion);
}
[Fact]
public void ItListsAutoReferencedPackages()
{
var testAsset = "TestAppSimple";
var projectDirectory = TestAssets
.Get(testAsset)
.CreateInstance()
.WithSourceFiles()
.WithProjectChanges(ChangeTargetFrameworkTo2_1)
.Root
.FullName;
new RestoreCommand()
.WithWorkingDirectory(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr();
new ListPackageCommand()
.WithPath(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr()
.And.HaveStdOutContainingIgnoreSpaces("Microsoft.NETCore.App(A)")
.And.HaveStdOutContainingIgnoreSpaces("(A):Auto-referencedpackage");
void ChangeTargetFrameworkTo2_1(XDocument project)
{
project.Descendants()
.Single(e => e.Name.LocalName == "TargetFramework")
.Value = "netcoreapp2.1";
}
}
[Fact]
public void ItRunOnSolution()
{
var sln = "TestAppWithSlnAndSolutionFolders";
var projectDirectory = TestAssets
.Get(sln)
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
new RestoreCommand()
.WithWorkingDirectory(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr();
new ListPackageCommand()
.WithPath(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr()
.And.HaveStdOutContainingIgnoreSpaces("NewtonSoft.Json");
}
[Fact]
public void AssetsPathExistsButNotRestored()
{
var testAsset = "NewtonSoftDependentProject";
var projectDirectory = TestAssets
.Get(testAsset)
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
new ListPackageCommand()
.WithPath(projectDirectory)
.Execute()
.Should()
.Pass()
.And.HaveStdErr();
}
[Fact]
public void ItListsTransitivePackage()
{
var testAsset = "NewtonSoftDependentProject";
var projectDirectory = TestAssets
.Get(testAsset)
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
new RestoreCommand()
.WithWorkingDirectory(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr();
new ListPackageCommand()
.WithPath(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr()
.And.NotHaveStdOutContaining("System.IO.FileSystem");
new ListPackageCommand()
.WithPath(projectDirectory)
.Execute(args:"--include-transitive")
.Should()
.Pass()
.And.NotHaveStdErr()
.And.HaveStdOutContaining("System.IO.FileSystem");
}
[Theory]
[InlineData("", "[net451]", null)]
[InlineData("", "[netcoreapp3.0]", null)]
[InlineData("--framework netcoreapp3.0 --framework net451", "[net451]", null)]
[InlineData("--framework netcoreapp3.0 --framework net451", "[netcoreapp3.0]", null)]
[InlineData("--framework netcoreapp3.0", "[netcoreapp3.0]", "[net451]")]
[InlineData("--framework net451", "[net451]", "[netcoreapp3.0]")]
public void ItListsValidFrameworks(string args, string shouldInclude, string shouldntInclude)
{
var testAsset = "MSBuildAppWithMultipleFrameworks";
var projectDirectory = TestAssets
.Get(testAsset)
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
new RestoreCommand()
.WithWorkingDirectory(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr();
if (shouldntInclude == null)
{
new ListPackageCommand()
.WithPath(projectDirectory)
.Execute(args)
.Should()
.Pass()
.And.NotHaveStdErr()
.And.HaveStdOutContainingIgnoreSpaces(shouldInclude.Replace(" ", ""));
}
else
{
new ListPackageCommand()
.WithPath(projectDirectory)
.Execute(args)
.Should()
.Pass()
.And.NotHaveStdErr()
.And.HaveStdOutContainingIgnoreSpaces(shouldInclude.Replace(" ", ""))
.And.NotHaveStdOutContaining(shouldntInclude.Replace(" ", ""));
}
}
[Fact]
public void ItDoesNotAcceptInvalidFramework()
{
var testAsset = "MSBuildAppWithMultipleFrameworks";
var projectDirectory = TestAssets
.Get(testAsset)
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
new RestoreCommand()
.WithWorkingDirectory(projectDirectory)
.Execute()
.Should()
.Pass();
new ListPackageCommand()
.WithPath(projectDirectory)
.Execute("--framework invalid")
.Should()
.Fail();
}
[Fact]
public void ItListsFSharpProject()
{
var testAsset = "FSharpTestAppSimple";
var projectDirectory = TestAssets
.Get(testAsset)
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
new RestoreCommand()
.WithWorkingDirectory(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr();
new ListPackageCommand()
.WithPath(projectDirectory)
.Execute()
.Should()
.Pass()
.And.NotHaveStdErr();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using Log2Console.Log;
using Log2Console.Receiver;
namespace Log2Console.Settings
{
[Serializable]
public sealed class UserSettings
{
internal static readonly Color DefaultTraceLevelColor = Color.Gray;
internal static readonly Color DefaultDebugLevelColor = Color.Black;
internal static readonly Color DefaultInfoLevelColor = Color.Green;
internal static readonly Color DefaultWarnLevelColor = Color.Orange;
internal static readonly Color DefaultErrorLevelColor = Color.Red;
internal static readonly Color DefaultFatalLevelColor = Color.Purple;
private static readonly FieldType[] DefaultColumnConfiguration =
{
new FieldType(LogMessageField.TimeStamp, "Time"),
new FieldType(LogMessageField.Level, "Level"),
new FieldType(LogMessageField.RootLoggerName, "RootLoggerName"),
new FieldType(LogMessageField.ThreadName, "Thread"),
new FieldType(LogMessageField.Message, "Message"),
};
private static readonly FieldType[] DefaultDetailsMessageConfiguration =
{
new FieldType(LogMessageField.TimeStamp, "Time"),
new FieldType(LogMessageField.Level, "Level"),
new FieldType(LogMessageField.RootLoggerName, "RootLoggerName"),
new FieldType(LogMessageField.ThreadName, "Thread"),
new FieldType(LogMessageField.Message, "Message"),
};
private static readonly FieldType[] DefaultCsvColumnHeaderConfiguration =
{
new FieldType(LogMessageField.SequenceNr, "sequence"),
new FieldType(LogMessageField.TimeStamp, "time"),
new FieldType(LogMessageField.Level, "level"),
new FieldType(LogMessageField.ThreadName, "thread"),
new FieldType(LogMessageField.CallSiteClass, "class"),
new FieldType(LogMessageField.CallSiteMethod, "method"),
new FieldType(LogMessageField.Message, "message"),
new FieldType(LogMessageField.Exception, "exception"),
new FieldType(LogMessageField.SourceFileName, "file")
};
[NonSerialized]
private const string SettingsFileName = "UserSettings.dat";
[NonSerialized]
private Dictionary<string, int> _columnProperties = new Dictionary<string, int>();
[NonSerialized]
private Dictionary<string, FieldType> _csvHeaderFieldTypes;
[NonSerialized]
private Dictionary<string, string> _sourceCodeLocationMap;
private static UserSettings _instance;
private bool _recursivlyEnableLoggers = true;
private bool _hideTaskbarIcon = false;
private bool _notifyNewLogWhenHidden = true;
private bool _alwaysOnTop = false;
private uint _transparency = 100;
private bool _highlightLogger = true;
private bool _highlightLogMessages = true;
private FieldType[] _columnConfiguration;
private FieldType[] _messageDetailConfiguration;
private FieldType[] _csvColumnHeaderFields;
private SourceFileLocation[] _sourceLocationMapConfiguration;
private bool _autoScrollToLastLog = true;
private bool _groupLogMessages = false;
private int _messageCycleCount = 0;
private string _timeStampFormatString = "yyyy-MM-dd HH:mm:ss.ffff";
private Font _defaultFont = null;
private Font _logListFont = null;
private Font _logDetailFont = null;
private Font _loggerTreeFont = null;
private Color _logListBackColor = Color.Empty;
private Color _logMessageBackColor = Color.Empty;
private Color _traceLevelColor = DefaultTraceLevelColor;
private Color _debugLevelColor = DefaultDebugLevelColor;
private Color _infoLevelColor = DefaultInfoLevelColor;
private Color _warnLevelColor = DefaultWarnLevelColor;
private Color _errorLevelColor = DefaultErrorLevelColor;
private Color _fatalLevelColor = DefaultFatalLevelColor;
private bool _msgDetailsProperties = false;
private bool _msgDetailsException = true;
private LogLevelInfo _logLevelInfo;
private List<IReceiver> _receivers = new List<IReceiver>();
private LayoutSettings _layout = new LayoutSettings();
private UserSettings()
{
// Set default values
_logLevelInfo = LogLevels.Instance[(int)LogLevel.Trace];
}
/// <summary>
/// Creates and returns an exact copy of the settings.
/// </summary>
/// <returns></returns>
public UserSettings Clone()
{
// We're going to serialize and deserialize to make the copy. That
// way if we add new properties and/or settings, we don't have to
// maintain a copy constructor.
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
// Serialize the object.
formatter.Serialize(ms, this);
// Reset the stream and deserialize it.
ms.Position = 0;
return formatter.Deserialize(ms) as UserSettings;
}
}
public static UserSettings Instance
{
get { return _instance; }
set { _instance = value; }
}
public static bool Load()
{
bool ok = false;
_instance = new UserSettings();
string settingsFilePath = GetSettingsFilePath();
if (!File.Exists(settingsFilePath))
return ok;
try
{
using (FileStream fs = new FileStream(settingsFilePath, FileMode.Open))
{
if (fs.Length > 0)
{
BinaryFormatter bf = new BinaryFormatter();
_instance = bf.Deserialize(fs) as UserSettings;
// During 1st load, some members are set to null
if (_instance != null)
{
if (_instance._receivers == null)
_instance._receivers = new List<IReceiver>();
if (_instance._layout == null)
_instance._layout = new LayoutSettings();
}
ok = true;
}
}
}
catch (Exception)
{
// The settings file might be corrupted or from too different version, delete it...
try
{
File.Delete(settingsFilePath);
}
catch
{
ok = false;
}
}
return ok;
}
private static string GetSettingsFilePath()
{
string userDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
DirectoryInfo di = new DirectoryInfo(userDir);
di = di.CreateSubdirectory("Log2Console");
return di.FullName + Path.DirectorySeparatorChar + SettingsFileName;
}
public void Save()
{
string settingsFilePath = GetSettingsFilePath();
using (FileStream fs = new FileStream(settingsFilePath, FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, this);
}
}
public void Close()
{
foreach (IReceiver receiver in _receivers)
{
receiver.Detach();
receiver.Terminate();
}
_receivers.Clear();
}
[Category("Appearance")]
[Description("Hides the taskbar icon, only the tray icon will remain visible.")]
[DisplayName("Hide Taskbar Icon")]
public bool HideTaskbarIcon
{
get { return _hideTaskbarIcon; }
set { _hideTaskbarIcon = value; }
}
[Category("Appearance")]
[Description("The Log2Console window will remain on top of all other windows.")]
[DisplayName("Always On Top")]
public bool AlwaysOnTop
{
get { return _alwaysOnTop; }
set { _alwaysOnTop = value; }
}
[Category("Appearance")]
[Description("Select a transparency factor for the main window.")]
public uint Transparency
{
get { return _transparency; }
set { _transparency = Math.Max(10, Math.Min(100, value)); }
}
[Category("Appearance")]
[Description("Highlight the Logger of the selected Log Message.")]
[DisplayName("Highlight Logger")]
public bool HighlightLogger
{
get { return _highlightLogger; }
set { _highlightLogger = value; }
}
[Category("Appearance")]
[Description("Highlight the Log Messages of the selected Logger.")]
[DisplayName("Highlight Log Messages")]
public bool HighlightLogMessages
{
get { return _highlightLogMessages; }
set { _highlightLogMessages = value; }
}
[Category("Columns")]
[DisplayName("Column Settings")]
[Description("Configure which Columns to Display")]
public FieldType[] ColumnConfiguration
{
get { return _columnConfiguration ?? (ColumnConfiguration = DefaultColumnConfiguration); }
set
{
_columnConfiguration = value;
UpdateColumnPropeties();
}
}
[Category("Columns")]
[DisplayName("CSV File Header Column Settings")]
[Description("Configures which columns maps to which fields when auto detecting the CSV structure based on the header")]
public FieldType[] CsvHeaderColumns
{
get { return _csvColumnHeaderFields ?? (CsvHeaderColumns = DefaultCsvColumnHeaderConfiguration); }
set
{
_csvColumnHeaderFields = value;
UpdateCsvColumnHeader();
}
}
[Category("Source File Configuration")]
[DisplayName("Source Location")]
[Description("Map the Log File Location to the Local Source Code Location")]
public SourceFileLocation[] SourceLocationMapConfiguration
{
get { return _sourceLocationMapConfiguration; }
set
{
_sourceLocationMapConfiguration = value;
UpdateSourceCodeLocationMap();
}
}
[Category("Notification")]
[Description("A balloon tip will be displayed when a new log message arrives and the window is hidden.")]
[DisplayName("Notify New Log When Hidden")]
public bool NotifyNewLogWhenHidden
{
get { return _notifyNewLogWhenHidden; }
set { _notifyNewLogWhenHidden = value; }
}
[Category("Notification")]
[Description("Automatically scroll to the last log message.")]
[DisplayName("Auto Scroll to Last Log")]
public bool AutoScrollToLastLog
{
get { return _autoScrollToLastLog; }
set { _autoScrollToLastLog = value; }
}
[Category("Logging")]
[Description("Groups the log messages based on the Logger Name.")]
[DisplayName("Group Log Messages by Loggers")]
public bool GroupLogMessages
{
get { return _groupLogMessages; }
set { _groupLogMessages = value; }
}
[Category("Logging")]
[Description("When greater than 0, the log messages are limited to that number.")]
[DisplayName("Message Cycle Count")]
public int MessageCycleCount
{
get { return _messageCycleCount; }
set { _messageCycleCount = value; }
}
[Category("Logging")]
[Description("Defines the format to be used to display the log message timestamps (cf. DateTime.ToString(format) in the .NET Framework.")]
[DisplayName("TimeStamp Format String")]
public string TimeStampFormatString
{
get { return _timeStampFormatString; }
set
{
// Check validity
try
{
string str= DateTime.Now.ToString(value); // If error, will throw FormatException
_timeStampFormatString = value;
}
catch (FormatException ex)
{
MessageBox.Show(Form.ActiveForm, ex.Message, Form.ActiveForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
_timeStampFormatString = "G"; // Back to default
}
}
}
[Category("Logging")]
[Description("When a logger is enabled or disabled, do the same for all child loggers.")]
[DisplayName("Recursively Enable Loggers")]
public bool RecursivlyEnableLoggers
{
get { return _recursivlyEnableLoggers; }
set { _recursivlyEnableLoggers = value; }
}
[Category("Message Details")]
[DisplayName("Details information")]
[Description("Configure which information to Display in the message details")]
public FieldType[] MessageDetailConfiguration
{
get { return _messageDetailConfiguration ?? (MessageDetailConfiguration = DefaultDetailsMessageConfiguration); }
set
{
_messageDetailConfiguration = value;
}
}
[Category("Message Details")]
[Description("Show or hide the message properties in the message details panel.")]
[DisplayName("Show Properties")]
public bool ShowMsgDetailsProperties
{
get { return _msgDetailsProperties; }
set { _msgDetailsProperties = value; }
}
[Category("Message Details")]
[Description("Show or hide the exception in the message details panel.")]
[DisplayName("Show Exception")]
public bool ShowMsgDetailsException
{
get { return _msgDetailsException; }
set { _msgDetailsException = value; }
}
[Category("Fonts")]
[Description("Set the default Font.")]
[DisplayName("Default Font")]
public Font DefaultFont
{
get { return _defaultFont; }
set { _defaultFont = value; }
}
[Category("Fonts")]
[Description("Set the Font of the Log List View.")]
[DisplayName("Log List View Font")]
public Font LogListFont
{
get { return _logListFont; }
set { _logListFont = value; }
}
[Category("Fonts")]
[Description("Set the Font of the Log Detail View.")]
[DisplayName("Log Detail View Font")]
public Font LogDetailFont
{
get { return _logDetailFont; }
set { _logDetailFont = value; }
}
[Category("Fonts")]
[Description("Set the Font of the Logger Tree.")]
[DisplayName("Logger Tree Font")]
public Font LoggerTreeFont
{
get { return _loggerTreeFont; }
set { _loggerTreeFont = value; }
}
[Category("Colors")]
[Description("Set the Background Color of the Log List View.")]
[DisplayName("Log List View Background Color")]
public Color LogListBackColor
{
get { return _logListBackColor; }
set { _logListBackColor = value; }
}
[Category("Colors")]
[Description("Set the Background Color of the Log Message details.")]
[DisplayName("Log Message details Background Color")]
public Color LogMessageBackColor
{
get { return _logMessageBackColor; }
set { _logMessageBackColor = value; }
}
[Category("Log Level Colors")]
[DisplayName("1 - Trace Level Color")]
public Color TraceLevelColor
{
get { return _traceLevelColor; }
set { _traceLevelColor = value; }
}
[Category("Log Level Colors")]
[DisplayName("2 - Debug Level Color")]
public Color DebugLevelColor
{
get { return _debugLevelColor; }
set { _debugLevelColor = value; }
}
[Category("Log Level Colors")]
[DisplayName("3 - Info Level Color")]
public Color InfoLevelColor
{
get { return _infoLevelColor; }
set { _infoLevelColor = value; }
}
[Category("Log Level Colors")]
[DisplayName("4 - Warning Level Color")]
public Color WarnLevelColor
{
get { return _warnLevelColor; }
set { _warnLevelColor = value; }
}
[Category("Log Level Colors")]
[DisplayName("5 - Error Level Color")]
public Color ErrorLevelColor
{
get { return _errorLevelColor; }
set { _errorLevelColor = value; }
}
[Category("Log Level Colors")]
[DisplayName("6 - Fatal Level Color")]
public Color FatalLevelColor
{
get { return _fatalLevelColor; }
set { _fatalLevelColor = value; }
}
/// <summary>
/// This setting is not available through the Settings PropertyGrid.
/// </summary>
[Browsable(false)]
internal LogLevelInfo LogLevelInfo
{
get { return _logLevelInfo; }
set { _logLevelInfo = value; }
}
/// <summary>
/// This setting is not available through the Settings PropertyGrid.
/// </summary>
[Browsable(false)]
internal List<IReceiver> Receivers
{
get { return _receivers; }
set { _receivers = value; }
}
/// <summary>
/// This setting is not available through the Settings PropertyGrid.
/// </summary>
[Browsable(false)]
internal LayoutSettings Layout
{
get { return _layout; }
set { _layout = value; }
}
[Browsable(false)]
public Dictionary<string, int> ColumnProperties
{
get
{
if (_columnProperties == null)
UpdateColumnPropeties();
return _columnProperties;
}
set { _columnProperties = value; }
}
[Browsable(false)]
public Dictionary<string, FieldType> CsvHeaderFieldTypes
{
get
{
if (_csvHeaderFieldTypes == null)
UpdateCsvColumnHeader();
return _csvHeaderFieldTypes;
}
set { _csvHeaderFieldTypes = value; }
}
[Browsable(false)]
public Dictionary<string, string> SourceFileLocationMap
{
get
{
if (_sourceCodeLocationMap == null)
UpdateSourceCodeLocationMap();
return _sourceCodeLocationMap;
}
set { _sourceCodeLocationMap = value; }
}
private void UpdateColumnPropeties()
{
_columnProperties = new Dictionary<string, int>();
for(int i=0; i<ColumnConfiguration.Length; i++)
{
try
{
if (ColumnConfiguration[i].Field == LogMessageField.Properties)
_columnProperties.Add(ColumnConfiguration[i].Property, i);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error Configuring Columns");
}
}
}
private void UpdateCsvColumnHeader()
{
_csvHeaderFieldTypes = new Dictionary<string, FieldType>();
foreach (var column in CsvHeaderColumns)
{
_csvHeaderFieldTypes.Add(column.Name, column);
}
}
private void UpdateSourceCodeLocationMap()
{
_sourceCodeLocationMap = new Dictionary<string, string>();
foreach (var map in SourceLocationMapConfiguration)
{
_sourceCodeLocationMap.Add(map.LogSource, map.LocalSource);
}
}
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2010 the Open Toolkit library.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using OpenTK.Input;
namespace OpenTK.Platform.X11
{
// Todo: multi-mouse support. Right now we aggregate all data into a single mouse device.
// This should be easy: just read the device id and route the data to the correct device.
sealed class XI2Mouse : IMouseDriver2
{
List<MouseState> mice = new List<MouseState>();
Dictionary<int, int> rawids = new Dictionary<int, int>(); // maps raw ids to mouse ids
internal readonly X11WindowInfo window;
static int XIOpCode;
static readonly Functions.EventPredicate PredicateImpl = IsEventValid;
readonly IntPtr Predicate = Marshal.GetFunctionPointerForDelegate(PredicateImpl);
// Store information on a mouse warp event, so it can be ignored.
struct MouseWarp : IEquatable<MouseWarp>
{
public MouseWarp(double x, double y) { X = x; Y = y; }
double X, Y;
public bool Equals(MouseWarp warp) { return X == warp.X && Y == warp.Y; }
}
MouseWarp? mouse_warp_event;
int mouse_warp_event_count;
public XI2Mouse()
{
Debug.WriteLine("Using XI2Mouse.");
using (new XLock(API.DefaultDisplay))
{
window = new X11WindowInfo();
window.Display = API.DefaultDisplay;
window.Screen = Functions.XDefaultScreen(window.Display);
window.RootWindow = Functions.XRootWindow(window.Display, window.Screen);
window.WindowHandle = window.RootWindow;
}
if (!IsSupported(window.Display))
throw new NotSupportedException("XInput2 not supported.");
using (XIEventMask mask = new XIEventMask(1, XIEventMasks.RawButtonPressMask |
XIEventMasks.RawButtonReleaseMask | XIEventMasks.RawMotionMask))
{
Functions.XISelectEvents(window.Display, window.WindowHandle, mask);
Functions.XISelectEvents(window.Display, window.RootWindow, mask);
}
}
// Checks whether XInput2 is supported on the specified display.
// If a display is not specified, the default display is used.
internal static bool IsSupported(IntPtr display)
{
if (display == IntPtr.Zero)
display = API.DefaultDisplay;
using (new XLock(display))
{
int major, ev, error;
if (Functions.XQueryExtension(display, "XInputExtension", out major, out ev, out error) == 0)
{
return false;
}
XIOpCode = major;
}
return true;
}
#region IMouseDriver2 Members
public MouseState GetState()
{
ProcessEvents();
MouseState master = new MouseState();
foreach (MouseState ms in mice)
{
master.MergeBits(ms);
}
return master;
}
public MouseState GetState(int index)
{
ProcessEvents();
if (mice.Count > index)
return mice[index];
else
return new MouseState();
}
public void SetPosition(double x, double y)
{
using (new XLock(window.Display))
{
Functions.XWarpPointer(window.Display,
IntPtr.Zero, window.RootWindow, 0, 0, 0, 0, (int)x, (int)y);
// Mark the expected warp-event so it can be ignored.
if (mouse_warp_event == null)
mouse_warp_event_count = 0;
mouse_warp_event_count++;
mouse_warp_event = new MouseWarp((int)x, (int)y);
}
ProcessEvents();
}
#endregion
bool CheckMouseWarp(double x, double y)
{
// Check if a mouse warp with the specified destination exists.
bool is_warp =
mouse_warp_event.HasValue &&
mouse_warp_event.Value.Equals(new MouseWarp((int)x, (int)y));
if (is_warp && --mouse_warp_event_count <= 0)
mouse_warp_event = null;
return is_warp;
}
void ProcessEvents()
{
while (true)
{
XEvent e = new XEvent();
XGenericEventCookie cookie;
using (new XLock(window.Display))
{
if (!Functions.XCheckIfEvent(window.Display, ref e, Predicate, new IntPtr(XIOpCode)))
return;
cookie = e.GenericEventCookie;
if (Functions.XGetEventData(window.Display, ref cookie) != 0)
{
XIRawEvent raw = (XIRawEvent)
Marshal.PtrToStructure(cookie.data, typeof(XIRawEvent));
if (!rawids.ContainsKey(raw.deviceid))
{
mice.Add(new MouseState());
rawids.Add(raw.deviceid, mice.Count - 1);
}
MouseState state = mice[rawids[raw.deviceid]];
switch (raw.evtype)
{
case XIEventType.RawMotion:
double x = 0, y = 0;
if (IsBitSet(raw.valuators.mask, 0))
{
x = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(raw.raw_values, 0));
}
if (IsBitSet(raw.valuators.mask, 1))
{
y = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(raw.raw_values, 8));
}
if (!CheckMouseWarp(x, y))
{
state.X += (int)x;
state.Y += (int)y;
}
break;
case XIEventType.RawButtonPress:
switch (raw.detail)
{
case 1: state.EnableBit((int)MouseButton.Left); break;
case 2: state.EnableBit((int)MouseButton.Middle); break;
case 3: state.EnableBit((int)MouseButton.Right); break;
case 4: state.WheelPrecise++; break;
case 5: state.WheelPrecise--; break;
case 6: state.EnableBit((int)MouseButton.Button1); break;
case 7: state.EnableBit((int)MouseButton.Button2); break;
case 8: state.EnableBit((int)MouseButton.Button3); break;
case 9: state.EnableBit((int)MouseButton.Button4); break;
case 10: state.EnableBit((int)MouseButton.Button5); break;
case 11: state.EnableBit((int)MouseButton.Button6); break;
case 12: state.EnableBit((int)MouseButton.Button7); break;
case 13: state.EnableBit((int)MouseButton.Button8); break;
case 14: state.EnableBit((int)MouseButton.Button9); break;
}
break;
case XIEventType.RawButtonRelease:
switch (raw.detail)
{
case 1: state.DisableBit((int)MouseButton.Left); break;
case 2: state.DisableBit((int)MouseButton.Middle); break;
case 3: state.DisableBit((int)MouseButton.Right); break;
case 6: state.DisableBit((int)MouseButton.Button1); break;
case 7: state.DisableBit((int)MouseButton.Button2); break;
case 8: state.DisableBit((int)MouseButton.Button3); break;
case 9: state.DisableBit((int)MouseButton.Button4); break;
case 10: state.DisableBit((int)MouseButton.Button5); break;
case 11: state.DisableBit((int)MouseButton.Button6); break;
case 12: state.DisableBit((int)MouseButton.Button7); break;
case 13: state.DisableBit((int)MouseButton.Button8); break;
case 14: state.DisableBit((int)MouseButton.Button9); break;
}
break;
}
mice[rawids[raw.deviceid]] = state;
}
Functions.XFreeEventData(window.Display, ref cookie);
}
}
}
static bool IsEventValid(IntPtr display, ref XEvent e, IntPtr arg)
{
return e.GenericEventCookie.extension == arg.ToInt32() &&
(e.GenericEventCookie.evtype == (int)XIEventType.RawMotion ||
e.GenericEventCookie.evtype == (int)XIEventType.RawButtonPress ||
e.GenericEventCookie.evtype == (int)XIEventType.RawButtonRelease);
}
static bool IsBitSet(IntPtr mask, int bit)
{
unsafe
{
return (*((byte*)mask + (bit >> 3)) & (1 << (bit & 7))) != 0;
}
}
}
}
| |
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using BinanceExchange.API.Caching.Interfaces;
using BinanceExchange.API.Enums;
using BinanceExchange.API.Models.Response.Error;
using log4net;
using Newtonsoft.Json;
namespace BinanceExchange.API
{
/// <summary>
/// The API Processor is the chief piece of functionality responsible for handling and creating requests to the API
/// </summary>
public class APIProcessor : IAPIProcessor
{
private readonly string _apiKey;
private readonly string _secretKey;
private IAPICacheManager _apiCache;
private ILog _logger;
private bool _cacheEnabled;
private TimeSpan _cacheTime;
public APIProcessor(string apiKey, string secretKey, IAPICacheManager apiCache)
{
_apiKey = apiKey;
_secretKey = secretKey;
if (apiCache != null)
{
_apiCache = apiCache;
_cacheEnabled = true;
}
_logger = LogManager.GetLogger(typeof(APIProcessor));
_logger.Debug( $"API Processor set up. Cache Enabled={_cacheEnabled}");
}
/// <summary>
/// Set the cache expiry time
/// </summary>
/// <param name="time"></param>
public void SetCacheTime(TimeSpan time)
{
_cacheTime = time;
}
private async Task<T> HandleResponse<T>(HttpResponseMessage message, string requestMessage, string fullCacheKey) where T : class
{
if (message.IsSuccessStatusCode)
{
var messageJson = await message.Content.ReadAsStringAsync();
T messageObject = null;
try
{
messageObject = JsonConvert.DeserializeObject<T>(messageJson);
}
catch (Exception ex)
{
string deserializeErrorMessage = $"Unable to deserialize message from: {requestMessage}. Exception: {ex.Message}";
_logger.Error(deserializeErrorMessage);
throw new BinanceException(deserializeErrorMessage, new BinanceError()
{
RequestMessage = requestMessage,
Message = ex.Message
});
}
_logger.Debug($"Successful Message Response={messageJson}");
if (messageObject == null)
{
throw new Exception("Unable to deserialize to provided type");
}
if (_apiCache.Contains(fullCacheKey))
{
_apiCache.Remove(fullCacheKey);
}
_apiCache.Add(messageObject, fullCacheKey, _cacheTime);
return messageObject;
}
var errorJson = await message.Content.ReadAsStringAsync();
var errorObject = JsonConvert.DeserializeObject<BinanceError>(errorJson);
if (errorObject == null) throw new BinanceException("Unexpected Error whilst handling the response", null);
errorObject.RequestMessage = requestMessage;
var exception = CreateBinanceException(message.StatusCode, errorObject);
_logger.Error($"Error Message Received:{errorJson}", exception);
throw exception;
}
private BinanceException CreateBinanceException(HttpStatusCode statusCode, BinanceError errorObject)
{
if (statusCode == HttpStatusCode.GatewayTimeout)
{
return new BinanceTimeoutException(errorObject);
}
var parsedStatusCode = (int)statusCode;
if (parsedStatusCode >= 400 && parsedStatusCode <= 500)
{
return new BinanceBadRequestException(errorObject);
}
return parsedStatusCode >= 500 ?
new BinanceServerException(errorObject) :
new BinanceException("Binance API Error", errorObject);
}
/// <summary>
/// Checks the cache for an item, and if it exists returns it
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="partialKey">The absolute Uri of the endpoint being hit. This is used in combination with the Type name to generate a unique key</param>
/// <param name="item"></param>
/// <returns>Whether the item exists</returns>
private bool CheckAndRetrieveCachedItem<T>(string fullKey, out T item) where T : class
{
item = null;
var result = _apiCache.Contains(fullKey);
item = result ? _apiCache.Get<T>(fullKey) : null;
return result;
}
/// <summary>
/// Processes a GET request
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="receiveWindow"></param>
/// <returns></returns>
public async Task<T> ProcessGetRequest<T>(BinanceEndpointData endpoint, int receiveWindow = 5000) where T : class
{
var fullKey = $"{typeof(T).Name}-{endpoint.Uri.AbsoluteUri}";
if (_cacheEnabled && endpoint.UseCache)
{
if (CheckAndRetrieveCachedItem<T>(fullKey, out var item))
{
return item;
}
}
HttpResponseMessage message;
switch (endpoint.SecurityType) {
case EndpointSecurityType.ApiKey:
case EndpointSecurityType.None:
message = await RequestClient.GetRequest(endpoint.Uri);
break;
case EndpointSecurityType.Signed:
message = await RequestClient.SignedGetRequest(endpoint.Uri, _apiKey, _secretKey, endpoint.Uri.Query, receiveWindow);
break;
default:
throw new ArgumentOutOfRangeException();
}
return await HandleResponse<T>(message, endpoint.ToString(), fullKey);
}
/// <summary>
/// Processes a DELETE request
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="receiveWindow"></param>
/// <returns></returns>
public async Task<T> ProcessDeleteRequest<T>(BinanceEndpointData endpoint, int receiveWindow = 5000) where T : class
{
var fullKey = $"{typeof(T).Name}-{endpoint.Uri.AbsoluteUri}";
if (_cacheEnabled && endpoint.UseCache)
{
T item;
if (CheckAndRetrieveCachedItem<T>(fullKey, out item))
{
return item;
}
}
HttpResponseMessage message;
switch (endpoint.SecurityType) {
case EndpointSecurityType.ApiKey:
message = await RequestClient.DeleteRequest(endpoint.Uri);
break;
case EndpointSecurityType.Signed:
message = await RequestClient.SignedDeleteRequest(endpoint.Uri, _apiKey, _secretKey, endpoint.Uri.Query, receiveWindow);
break;
case EndpointSecurityType.None:
default:
throw new ArgumentOutOfRangeException();
}
return await HandleResponse<T>(message, endpoint.ToString(), fullKey);
}
/// <summary>
/// Processes a POST request
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="receiveWindow"></param>
/// <returns></returns>
public async Task<T> ProcessPostRequest<T>(BinanceEndpointData endpoint, int receiveWindow = 5000) where T : class
{
var fullKey = $"{typeof(T).Name}-{endpoint.Uri.AbsoluteUri}";
if (_cacheEnabled && endpoint.UseCache)
{
T item;
if (CheckAndRetrieveCachedItem<T>(fullKey, out item))
{
return item;
}
}
HttpResponseMessage message;
switch (endpoint.SecurityType) {
case EndpointSecurityType.ApiKey:
message = await RequestClient.PostRequest(endpoint.Uri);
break;
case EndpointSecurityType.None:
throw new ArgumentOutOfRangeException();
case EndpointSecurityType.Signed:
message = await RequestClient.SignedPostRequest(endpoint.Uri, _apiKey, _secretKey, endpoint.Uri.Query, receiveWindow);
break;
default:
throw new ArgumentOutOfRangeException();
}
return await HandleResponse<T>(message, endpoint.ToString(), fullKey);
}
/// <summary>
/// Processes a PUT request
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="receiveWindow"></param>
/// <returns></returns>
public async Task<T> ProcessPutRequest<T>(BinanceEndpointData endpoint, int receiveWindow = 5000) where T : class
{
var fullKey = $"{typeof(T).Name}-{endpoint.Uri.AbsoluteUri}";
if (_cacheEnabled && endpoint.UseCache)
{
T item;
if (CheckAndRetrieveCachedItem<T>(fullKey, out item))
{
return item;
}
}
HttpResponseMessage message;
switch (endpoint.SecurityType) {
case EndpointSecurityType.ApiKey:
message = await RequestClient.PutRequest(endpoint.Uri);
break;
case EndpointSecurityType.None:
case EndpointSecurityType.Signed:
default:
throw new ArgumentOutOfRangeException();
}
return await HandleResponse<T>(message, endpoint.ToString(), fullKey);
}
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Diagnostics;
using System.Security.AccessControl;
using System.Xml;
using System.Text;
using Ionic.Zip;
using Ionic.Zlib;
namespace UnrealBuildTool
{
class IOSToolChain : AppleToolChain
{
public override void RegisterToolChain()
{
RegisterRemoteToolChain(UnrealTargetPlatform.Mac, CPPTargetPlatform.IOS);
}
/***********************************************************************
* NOTE:
* Do NOT change the defaults to set your values, instead you should set the environment variables
* properly in your system, as other tools make use of them to work properly!
* The defaults are there simply for examples so you know what to put in your env vars...
***********************************************************************/
// If you are looking for where to change the remote compile server name, look in RemoteToolChain.cs
/** If this is set, then we don't do any post-compile steps except moving the executable into the proper spot on the Mac */
[XmlConfig]
public static bool bUseDangerouslyFastMode = false;
/** Which version of the iOS SDK to target at build time */
[XmlConfig]
public static string IOSSDKVersion = "latest";
public static float IOSSDKVersionFloat = 0.0f;
/** Which version of the iOS to allow at build time */
[XmlConfig]
public static string BuildIOSVersion = "7.0";
/** Which developer directory to root from */
private static string XcodeDeveloperDir = "xcode-select";
/** Directory for the developer binaries */
private static string ToolchainDir = "";
/** Location of the SDKs */
private static string BaseSDKDir;
private static string BaseSDKDirSim;
/** Which compiler frontend to use */
private static string IOSCompiler = "clang++";
/** Which linker frontend to use */
private static string IOSLinker = "clang++";
/** Which library archiver to use */
private static string IOSArchiver = "libtool";
public List<string> BuiltBinaries = new List<string>();
/** Additional frameworks stored locally so we have access without LinkEnvironment */
public List<UEBuildFramework> RememberedAdditionalFrameworks = new List<UEBuildFramework>();
private static void SetupXcodePaths(bool bVerbose)
{
// choose the XCode to use
SelectXcode(ref XcodeDeveloperDir, bVerbose);
// update cached paths
BaseSDKDir = XcodeDeveloperDir + "Platforms/iPhoneOS.platform/Developer/SDKs";
BaseSDKDirSim = XcodeDeveloperDir + "Platforms/iPhoneSimulator.platform/Developer/SDKs";
ToolchainDir = XcodeDeveloperDir + "Toolchains/XcodeDefault.xctoolchain/usr/bin/";
// make sure SDK is selected
SelectSDK(BaseSDKDir, "iPhoneOS", ref IOSSDKVersion, bVerbose);
// convert to float for easy comparison
IOSSDKVersionFloat = float.Parse(IOSSDKVersion, System.Globalization.CultureInfo.InvariantCulture);
}
/** Hunt down the latest IOS sdk if desired */
public override void SetUpGlobalEnvironment()
{
base.SetUpGlobalEnvironment();
SetupXcodePaths(true);
}
public override void AddFilesToReceipt(BuildReceipt Receipt, UEBuildBinary Binary)
{
if (BuildConfiguration.bCreateStubIPA && Binary.Config.Type != UEBuildBinaryType.StaticLibrary)
{
string StubFile = Path.Combine (Path.GetDirectoryName (Binary.Config.OutputFilePath), Path.GetFileNameWithoutExtension (Binary.Config.OutputFilePath) + ".stub");
Receipt.AddBuildProduct(StubFile, BuildProductType.Executable);
}
}
/// <summary>
/// Adds a build product and its associated debug file to a receipt.
/// </summary>
/// <param name="OutputFile">Build product to add</param>
/// <param name="DebugExtension">Extension for the matching debug file (may be null).</param>
public override bool ShouldAddDebugFileToReceipt(string OutputFile, BuildProductType OutputType)
{
return OutputType == BuildProductType.Executable;
}
static bool bHasPrinted = false;
static string GetArchitectureArgument(CPPTargetConfiguration Configuration, string UBTArchitecture)
{
IOSPlatform BuildPlat = UEBuildPlatform.GetBuildPlatform(UnrealTargetPlatform.IOS) as IOSPlatform;
BuildPlat.SetUpProjectEnvironment(UnrealTargetPlatform.IOS);
// get the list of architectures to compile
string Archs =
UBTArchitecture == "-simulator" ? "i386" :
(Configuration == CPPTargetConfiguration.Shipping) ? IOSPlatform.ShippingArchitectures : IOSPlatform.NonShippingArchitectures;
if (!bHasPrinted)
{
bHasPrinted = true;
Console.WriteLine("Compiling with these architectures: " + Archs);
}
// parse the string
string[] Tokens = Archs.Split(",".ToCharArray());
string Result = "";
foreach (string Token in Tokens)
{
Result += " -arch " + Token;
}
return Result;
}
string GetCompileArguments_Global(CPPEnvironment CompileEnvironment)
{
IOSPlatform BuildPlat = UEBuildPlatform.GetBuildPlatform(UnrealTargetPlatform.IOS) as IOSPlatform;
BuildPlat.SetUpProjectEnvironment(UnrealTargetPlatform.IOS);
string Result = "";
Result += " -fmessage-length=0";
Result += " -pipe";
Result += " -fpascal-strings";
Result += " -fno-exceptions";
Result += " -fno-rtti";
Result += " -fvisibility=hidden"; // hides the linker warnings with PhysX
// if (CompileEnvironment.Config.TargetConfiguration == CPPTargetConfiguration.Shipping)
// {
// Result += " -flto";
// }
Result += " -Wall -Werror";
if (CompileEnvironment.Config.bEnableShadowVariableWarning)
{
Result += " -Wshadow" + (BuildConfiguration.bShadowVariableErrors? "" : " -Wno-error=shadow");
}
Result += " -Wno-unused-variable";
Result += " -Wno-unused-value";
// this will hide the warnings about static functions in headers that aren't used in every single .cpp file
Result += " -Wno-unused-function";
// this hides the "enumeration value 'XXXXX' not handled in switch [-Wswitch]" warnings - we should maybe remove this at some point and add UE_LOG(, Fatal, ) to default cases
Result += " -Wno-switch";
// this hides the "warning : comparison of unsigned expression < 0 is always false" type warnings due to constant comparisons, which are possible with template arguments
Result += " -Wno-tautological-compare";
//This will prevent the issue of warnings for unused private variables.
Result += " -Wno-unused-private-field";
Result += " -Wno-invalid-offsetof"; // needed to suppress warnings about using offsetof on non-POD types.
if (IOSSDKVersionFloat >= 9.0)
{
Result += " -Wno-inconsistent-missing-override"; // too many missing overrides...
Result += " -Wno-unused-local-typedef"; // PhysX has some, hard to remove
}
Result += " -c";
// What architecture(s) to build for
Result += GetArchitectureArgument(CompileEnvironment.Config.Target.Configuration, CompileEnvironment.Config.Target.Architecture);
if (CompileEnvironment.Config.Target.Architecture == "-simulator")
{
Result += " -isysroot " + BaseSDKDirSim + "/iPhoneSimulator" + IOSSDKVersion + ".sdk";
}
else
{
Result += " -isysroot " + BaseSDKDir + "/iPhoneOS" + IOSSDKVersion + ".sdk";
}
Result += " -miphoneos-version-min=" + BuildPlat.GetRunTimeVersion();
// Optimize non- debug builds.
if (CompileEnvironment.Config.Target.Configuration != CPPTargetConfiguration.Debug)
{
if (UEBuildConfiguration.bCompileForSize)
{
Result += " -Oz";
}
else
{
Result += " -O3";
}
}
else
{
Result += " -O0";
}
// Create DWARF format debug info if wanted,
if (CompileEnvironment.Config.bCreateDebugInfo)
{
Result += " -gdwarf-2";
}
// Add additional frameworks so that their headers can be found
foreach (UEBuildFramework Framework in CompileEnvironment.Config.AdditionalFrameworks)
{
if (Framework.OwningModule != null && Framework.FrameworkZipPath != null && Framework.FrameworkZipPath != "")
{
Result += " -F\"" + GetRemoteIntermediateFrameworkZipPath(Framework) + "\"";
}
}
return Result;
}
static string GetCompileArguments_CPP()
{
string Result = "";
Result += " -x objective-c++";
Result += " -fno-rtti";
Result += " -fobjc-abi-version=2";
Result += " -fobjc-legacy-dispatch";
Result += " -std=c++11";
Result += " -stdlib=libc++";
return Result;
}
static string GetCompileArguments_MM()
{
string Result = "";
Result += " -x objective-c++";
Result += " -fobjc-abi-version=2";
Result += " -fobjc-legacy-dispatch";
Result += " -fno-rtti";
Result += " -std=c++11";
Result += " -stdlib=libc++";
return Result;
}
static string GetCompileArguments_M()
{
string Result = "";
Result += " -x objective-c";
Result += " -fobjc-abi-version=2";
Result += " -fobjc-legacy-dispatch";
Result += " -std=c++11";
Result += " -stdlib=libc++";
return Result;
}
static string GetCompileArguments_C()
{
string Result = "";
Result += " -x c";
return Result;
}
static string GetCompileArguments_PCH()
{
string Result = "";
Result += " -x objective-c++-header";
Result += " -fno-rtti";
Result += " -std=c++11";
Result += " -stdlib=libc++";
return Result;
}
string GetLocalFrameworkZipPath( UEBuildFramework Framework )
{
if ( Framework.OwningModule == null )
{
throw new BuildException( "GetLocalFrameworkZipPath: No owning module for framework {0}", Framework.FrameworkName );
}
return Path.GetFullPath( Framework.OwningModule.ModuleDirectory + "/" + Framework.FrameworkZipPath );
}
string GetRemoteFrameworkZipPath( UEBuildFramework Framework )
{
if ( BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac )
{
return ConvertPath( GetLocalFrameworkZipPath( Framework ) );
}
return GetLocalFrameworkZipPath( Framework );
}
string GetRemoteIntermediateFrameworkZipPath( UEBuildFramework Framework )
{
if ( Framework.OwningModule == null )
{
throw new BuildException( "GetRemoteIntermediateFrameworkZipPath: No owning module for framework {0}", Framework.FrameworkName );
}
string IntermediatePath = Framework.OwningModule.Target.ProjectDirectory + "/Intermediate/UnzippedFrameworks/" + Framework.OwningModule.Name;
IntermediatePath = Path.GetFullPath( ( IntermediatePath + Framework.FrameworkZipPath ).Replace( ".zip", "" ) );
if ( BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac )
{
return ConvertPath( IntermediatePath );
}
return IntermediatePath;
}
void CleanIntermediateDirectory( string Path )
{
if ( BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac )
{
// Delete the intermediate directory on the mac
RPCUtilHelper.Command( "/", String.Format( "rm -rf \"{0}\"", Path ), "", null );
// Create a fresh intermediate after we delete it
RPCUtilHelper.Command( "/", String.Format( "mkdir -p \"{0}\"", Path ), "", null );
}
else
{
// Delete the local dest directory if it exists
if ( Directory.Exists( Path ) )
{
Directory.Delete( Path, true );
}
// Create the intermediate local directory
string ResultsText;
RunExecutableAndWait( "mkdir", String.Format( "-p \"{0}\"", Path ), out ResultsText );
}
}
string GetLinkArguments_Global( LinkEnvironment LinkEnvironment )
{
IOSPlatform BuildPlat = UEBuildPlatform.GetBuildPlatform(UnrealTargetPlatform.IOS) as IOSPlatform;
BuildPlat.SetUpProjectEnvironment(UnrealTargetPlatform.IOS);
string Result = "";
if (LinkEnvironment.Config.Target.Architecture == "-simulator")
{
Result += " -arch i386";
Result += " -isysroot " + XcodeDeveloperDir + "Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator" + IOSSDKVersion + ".sdk";
}
else
{
Result += Result += GetArchitectureArgument(LinkEnvironment.Config.Target.Configuration, LinkEnvironment.Config.Target.Architecture);
Result += " -isysroot " + XcodeDeveloperDir + "Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS" + IOSSDKVersion + ".sdk";
}
Result += " -dead_strip";
Result += " -miphoneos-version-min=" + BuildPlat.GetRunTimeVersion();
Result += " -Wl,-no_pie";
// Result += " -v";
// link in the frameworks
foreach (string Framework in LinkEnvironment.Config.Frameworks)
{
Result += " -framework " + Framework;
}
foreach (UEBuildFramework Framework in LinkEnvironment.Config.AdditionalFrameworks)
{
if ( Framework.OwningModule != null && Framework.FrameworkZipPath != null && Framework.FrameworkZipPath != "" )
{
// If this framework has a zip specified, we'll need to setup the path as well
Result += " -F\"" + GetRemoteIntermediateFrameworkZipPath( Framework ) + "\"";
}
Result += " -framework " + Framework.FrameworkName;
}
foreach (string Framework in LinkEnvironment.Config.WeakFrameworks)
{
Result += " -weak_framework " + Framework;
}
return Result;
}
static string GetArchiveArguments_Global(LinkEnvironment LinkEnvironment)
{
string Result = "";
Result += " -static";
return Result;
}
public override CPPOutput CompileCPPFiles(UEBuildTarget Target, CPPEnvironment CompileEnvironment, List<FileItem> SourceFiles, string ModuleName)
{
string Arguments = GetCompileArguments_Global(CompileEnvironment);
string PCHArguments = "";
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Include)
{
// Add the precompiled header file's path to the include path so GCC can find it.
// This needs to be before the other include paths to ensure GCC uses it instead of the source header file.
var PrecompiledFileExtension = UEBuildPlatform.BuildPlatformDictionary[UnrealTargetPlatform.IOS].GetBinaryExtension(UEBuildBinaryType.PrecompiledHeader);
PCHArguments += string.Format(" -include \"{0}\"", ConvertPath(CompileEnvironment.PrecompiledHeaderFile.AbsolutePath.Replace(PrecompiledFileExtension, "")));
}
// Add include paths to the argument list.
HashSet<string> AllIncludes = new HashSet<string>(CompileEnvironment.Config.CPPIncludeInfo.IncludePaths);
AllIncludes.UnionWith(CompileEnvironment.Config.CPPIncludeInfo.SystemIncludePaths);
foreach (string IncludePath in AllIncludes)
{
Arguments += string.Format(" -I\"{0}\"", ConvertPath(Path.GetFullPath(IncludePath)));
if (BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
// sync any third party headers we may need
if (IncludePath.Contains("ThirdParty"))
{
string[] FileList = Directory.GetFiles(IncludePath, "*.h", SearchOption.AllDirectories);
foreach (string File in FileList)
{
FileItem ExternalDependency = FileItem.GetItemByPath(File);
LocalToRemoteFileItem(ExternalDependency, true);
}
FileList = Directory.GetFiles(IncludePath, "*.cpp", SearchOption.AllDirectories);
foreach (string File in FileList)
{
FileItem ExternalDependency = FileItem.GetItemByPath(File);
LocalToRemoteFileItem(ExternalDependency, true);
}
}
}
}
foreach (string Definition in CompileEnvironment.Config.Definitions)
{
Arguments += string.Format(" -D\"{0}\"", Definition);
}
var BuildPlatform = UEBuildPlatform.GetBuildPlatformForCPPTargetPlatform(CompileEnvironment.Config.Target.Platform);
CPPOutput Result = new CPPOutput();
// Create a compile action for each source file.
foreach (FileItem SourceFile in SourceFiles)
{
Action CompileAction = new Action(ActionType.Compile);
string FileArguments = "";
string Extension = Path.GetExtension(SourceFile.AbsolutePath).ToUpperInvariant();
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Create)
{
// Compile the file as a C++ PCH.
FileArguments += GetCompileArguments_PCH();
}
else if (Extension == ".C")
{
// Compile the file as C code.
FileArguments += GetCompileArguments_C();
}
else if (Extension == ".CC")
{
// Compile the file as C++ code.
FileArguments += GetCompileArguments_CPP();
}
else if (Extension == ".MM")
{
// Compile the file as Objective-C++ code.
FileArguments += GetCompileArguments_MM();
}
else if (Extension == ".M")
{
// Compile the file as Objective-C++ code.
FileArguments += GetCompileArguments_M();
}
else
{
// Compile the file as C++ code.
FileArguments += GetCompileArguments_CPP();
// only use PCH for .cpp files
FileArguments += PCHArguments;
}
// Add the C++ source file and its included files to the prerequisite item list.
AddPrerequisiteSourceFile( Target, BuildPlatform, CompileEnvironment, SourceFile, CompileAction.PrerequisiteItems );
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Create)
{
var PrecompiledFileExtension = UEBuildPlatform.BuildPlatformDictionary[UnrealTargetPlatform.IOS].GetBinaryExtension(UEBuildBinaryType.PrecompiledHeader);
// Add the precompiled header file to the produced item list.
FileItem PrecompiledHeaderFile = FileItem.GetItemByPath(
Path.Combine(
CompileEnvironment.Config.OutputDirectory,
Path.GetFileName(SourceFile.AbsolutePath) + PrecompiledFileExtension
)
);
FileItem RemotePrecompiledHeaderFile = LocalToRemoteFileItem(PrecompiledHeaderFile, false);
CompileAction.ProducedItems.Add(RemotePrecompiledHeaderFile);
Result.PrecompiledHeaderFile = RemotePrecompiledHeaderFile;
// Add the parameters needed to compile the precompiled header file to the command-line.
FileArguments += string.Format(" -o \"{0}\"", RemotePrecompiledHeaderFile.AbsolutePath, false);
}
else
{
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Include)
{
CompileAction.bIsUsingPCH = true;
CompileAction.PrerequisiteItems.Add(CompileEnvironment.PrecompiledHeaderFile);
}
var ObjectFileExtension = UEBuildPlatform.BuildPlatformDictionary[UnrealTargetPlatform.IOS].GetBinaryExtension(UEBuildBinaryType.Object);
// Add the object file to the produced item list.
FileItem ObjectFile = FileItem.GetItemByPath(
Path.Combine(
CompileEnvironment.Config.OutputDirectory,
Path.GetFileName(SourceFile.AbsolutePath) + ObjectFileExtension
)
);
FileItem RemoteObjectFile = LocalToRemoteFileItem(ObjectFile, false);
CompileAction.ProducedItems.Add(RemoteObjectFile);
Result.ObjectFiles.Add(RemoteObjectFile);
FileArguments += string.Format(" -o \"{0}\"", RemoteObjectFile.AbsolutePath, false);
}
// Add the source file path to the command-line.
FileArguments += string.Format(" \"{0}\"", ConvertPath(SourceFile.AbsolutePath), false);
string CompilerPath = ToolchainDir + IOSCompiler;
if (!Utils.IsRunningOnMono && BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
CompileAction.ActionHandler = new Action.BlockingActionHandler(RPCUtilHelper.RPCActionHandler);
}
// RPC utility parameters are in terms of the Mac side
CompileAction.WorkingDirectory = GetMacDevSrcRoot();
CompileAction.CommandPath = CompilerPath;
CompileAction.CommandArguments = Arguments + FileArguments + CompileEnvironment.Config.AdditionalArguments;
CompileAction.StatusDescription = string.Format("{0}", Path.GetFileName(SourceFile.AbsolutePath));
CompileAction.bIsGCCCompiler = true;
// We're already distributing the command by execution on Mac.
CompileAction.bCanExecuteRemotely = false;
CompileAction.bShouldOutputStatusDescription = true;
CompileAction.OutputEventHandler = new DataReceivedEventHandler(RemoteOutputReceivedEventHandler);
}
return Result;
}
public override FileItem LinkFiles(LinkEnvironment LinkEnvironment, bool bBuildImportLibraryOnly)
{
string LinkerPath = ToolchainDir +
(LinkEnvironment.Config.bIsBuildingLibrary ? IOSArchiver : IOSLinker);
// Create an action that invokes the linker.
Action LinkAction = new Action(ActionType.Link);
if (!Utils.IsRunningOnMono && BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
LinkAction.ActionHandler = new Action.BlockingActionHandler(RPCUtilHelper.RPCActionHandler);
}
// RPC utility parameters are in terms of the Mac side
LinkAction.WorkingDirectory = GetMacDevSrcRoot();
LinkAction.CommandPath = LinkerPath;
// build this up over the rest of the function
LinkAction.CommandArguments = LinkEnvironment.Config.bIsBuildingLibrary ? GetArchiveArguments_Global(LinkEnvironment) : GetLinkArguments_Global(LinkEnvironment);
if (!LinkEnvironment.Config.bIsBuildingLibrary)
{
// Add the library paths to the argument list.
foreach (string LibraryPath in LinkEnvironment.Config.LibraryPaths)
{
LinkAction.CommandArguments += string.Format(" -L\"{0}\"", LibraryPath);
}
// Add the additional libraries to the argument list.
foreach (string AdditionalLibrary in LinkEnvironment.Config.AdditionalLibraries)
{
// for absolute library paths, convert to remote filename
if (!String.IsNullOrEmpty(Path.GetDirectoryName(AdditionalLibrary)))
{
// add it to the prerequisites to make sure it's built first (this should be the case of non-system libraries)
FileItem LibFile = FileItem.GetItemByPath(Path.GetFullPath(AdditionalLibrary));
FileItem RemoteLibFile = LocalToRemoteFileItem(LibFile, false);
LinkAction.PrerequisiteItems.Add(RemoteLibFile);
// and add to the commandline
LinkAction.CommandArguments += string.Format(" \"{0}\"", ConvertPath(Path.GetFullPath(AdditionalLibrary)));
}
else
{
LinkAction.CommandArguments += string.Format(" -l\"{0}\"", AdditionalLibrary);
}
}
}
if (BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
// Add any additional files that we'll need in order to link the app
foreach (string AdditionalShadowFile in LinkEnvironment.Config.AdditionalShadowFiles)
{
FileItem ShadowFile = FileItem.GetExistingItemByPath(AdditionalShadowFile);
if (ShadowFile != null)
{
QueueFileForBatchUpload(ShadowFile);
LinkAction.PrerequisiteItems.Add(ShadowFile);
}
else
{
throw new BuildException("Couldn't find required additional file to shadow: {0}", AdditionalShadowFile);
}
}
}
// Handle additional framework assets that might need to be shadowed
foreach ( UEBuildFramework Framework in LinkEnvironment.Config.AdditionalFrameworks )
{
if ( Framework.OwningModule == null || Framework.FrameworkZipPath == null || Framework.FrameworkZipPath == "" )
{
continue; // Only care about frameworks that have a zip specified
}
// If we've already remembered this framework, skip
if ( RememberedAdditionalFrameworks.Contains( Framework ) )
{
continue;
}
// Remember any files we need to unzip
RememberedAdditionalFrameworks.Add( Framework );
// Copy them to remote mac if needed
if ( BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac )
{
FileItem ShadowFile = FileItem.GetExistingItemByPath( GetLocalFrameworkZipPath( Framework ) );
if ( ShadowFile != null )
{
QueueFileForBatchUpload( ShadowFile );
LinkAction.PrerequisiteItems.Add( ShadowFile );
}
else
{
throw new BuildException( "Couldn't find required additional file to shadow: {0}", Framework.FrameworkZipPath );
}
}
}
// Add the output file as a production of the link action.
FileItem OutputFile = FileItem.GetItemByPath(Path.GetFullPath(LinkEnvironment.Config.OutputFilePath));
FileItem RemoteOutputFile = LocalToRemoteFileItem(OutputFile, false);
LinkAction.ProducedItems.Add(RemoteOutputFile);
// Add the input files to a response file, and pass the response file on the command-line.
List<string> InputFileNames = new List<string>();
foreach (FileItem InputFile in LinkEnvironment.InputFiles)
{
InputFileNames.Add(string.Format("\"{0}\"", InputFile.AbsolutePath));
LinkAction.PrerequisiteItems.Add(InputFile);
}
// Write the list of input files to a response file, with a tempfilename, on remote machine
if (LinkEnvironment.Config.bIsBuildingLibrary)
{
foreach (string Filename in InputFileNames)
{
LinkAction.CommandArguments += " " + Filename;
}
// @todo rocket lib: the -filelist command should take a response file (see else condition), except that it just says it can't
// find the file that's in there. Rocket.lib may overflow the commandline by putting all files on the commandline, so this
// may be needed:
// LinkAction.CommandArguments += string.Format(" -filelist \"{0}\"", ConvertPath(ResponsePath));
}
else
{
bool bIsUE4Game = LinkEnvironment.Config.OutputFilePath.Contains("UE4Game");
string ResponsePath = Path.GetFullPath(Path.Combine((!bIsUE4Game && !string.IsNullOrEmpty(UnrealBuildTool.GetUProjectPath())) ? UnrealBuildTool.GetUProjectPath() : BuildConfiguration.RelativeEnginePath, BuildConfiguration.PlatformIntermediateFolder, "LinkFileList_" + Path.GetFileNameWithoutExtension(LinkEnvironment.Config.OutputFilePath) + ".tmp"));
if (!Utils.IsRunningOnMono && BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
ResponseFile.Create (ResponsePath, InputFileNames);
RPCUtilHelper.CopyFile (ResponsePath, ConvertPath (ResponsePath), true);
}
else
{
ResponseFile.Create(ConvertPath(ResponsePath), InputFileNames);
}
LinkAction.CommandArguments += string.Format(" @\"{0}\"", ConvertPath(ResponsePath));
}
// Add the output file to the command-line.
LinkAction.CommandArguments += string.Format(" -o \"{0}\"", RemoteOutputFile.AbsolutePath);
// Add the additional arguments specified by the environment.
LinkAction.CommandArguments += LinkEnvironment.Config.AdditionalArguments;
// Only execute linking on the local PC.
LinkAction.bCanExecuteRemotely = false;
LinkAction.StatusDescription = string.Format("{0}", OutputFile.AbsolutePath);
LinkAction.OutputEventHandler = new DataReceivedEventHandler(RemoteOutputReceivedEventHandler);
// For iPhone, generate the dSYM file if the config file is set to do so
if (BuildConfiguration.bGeneratedSYMFile == true && Path.GetExtension(OutputFile.AbsolutePath) != ".a")
{
Log.TraceInformation("Generating the dSYM file - this will add some time to your build...");
RemoteOutputFile = GenerateDebugInfo(RemoteOutputFile);
}
return RemoteOutputFile;
}
/**
* Generates debug info for a given executable
*
* @param Executable FileItem describing the executable to generate debug info for
*/
static public FileItem GenerateDebugInfo(FileItem Executable)
{
// Make a file item for the source and destination files
string FullDestPathRoot = Executable.AbsolutePath + ".dSYM";
string FullDestPath = FullDestPathRoot;
FileItem DestFile;
if (!Utils.IsRunningOnMono && BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
DestFile = FileItem.GetRemoteItemByPath (FullDestPath, UnrealTargetPlatform.IOS);
}
else
{
DestFile = FileItem.GetItemByPath (FullDestPath);
}
// Make the compile action
Action GenDebugAction = new Action(ActionType.GenerateDebugInfo);
if (!Utils.IsRunningOnMono)
{
GenDebugAction.ActionHandler = new Action.BlockingActionHandler(RPCUtilHelper.RPCActionHandler);
}
IOSToolChain Toolchain = UEToolChain.GetPlatformToolChain(CPPTargetPlatform.IOS) as IOSToolChain;
GenDebugAction.WorkingDirectory = Toolchain.GetMacDevSrcRoot();
GenDebugAction.CommandPath = "sh";
// note that the source and dest are switched from a copy command
if (!Utils.IsRunningOnMono && BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
GenDebugAction.CommandArguments = string.Format("-c '/usr/bin/dsymutil \"{0}\" -f -o \"{1}\"; cd \"{1}/..\"; zip -r -y -1 {2}.dSYM.zip {2}.dSYM'",
Executable.AbsolutePath,
FullDestPathRoot,
Path.GetFileName(Executable.AbsolutePath));
}
else
{
GenDebugAction.CommandArguments = string.Format("-c '/usr/bin/dsymutil \"{0}\" -f -o \"{1}\"'",
Executable.AbsolutePath,
FullDestPathRoot);
}
GenDebugAction.PrerequisiteItems.Add(Executable);
GenDebugAction.ProducedItems.Add(DestFile);
GenDebugAction.StatusDescription = GenDebugAction.CommandArguments;// string.Format("Generating debug info for {0}", Path.GetFileName(Executable.AbsolutePath));
GenDebugAction.bCanExecuteRemotely = false;
return DestFile;
}
private void PackageStub(string BinaryPath, string GameName, string ExeName)
{
// create the ipa
string IPAName = BinaryPath + "/" + ExeName + ".stub";
// delete the old one
if (File.Exists(IPAName))
{
File.Delete(IPAName);
}
// make the subdirectory if needed
string DestSubdir = Path.GetDirectoryName(IPAName);
if (!Directory.Exists(DestSubdir))
{
Directory.CreateDirectory(DestSubdir);
}
// set up the directories
string ZipWorkingDir = String.Format("Payload/{0}.app/", GameName);
string ZipSourceDir = string.Format("{0}/Payload/{1}.app", BinaryPath, GameName);
// create the file
using (ZipFile Zip = new ZipFile())
{
// add the entire directory
Zip.AddDirectory(ZipSourceDir, ZipWorkingDir);
// Update permissions to be UNIX-style
// Modify the file attributes of any added file to unix format
foreach (ZipEntry E in Zip.Entries)
{
const byte FileAttributePlatform_NTFS = 0x0A;
const byte FileAttributePlatform_UNIX = 0x03;
const byte FileAttributePlatform_FAT = 0x00;
const int UNIX_FILETYPE_NORMAL_FILE = 0x8000;
//const int UNIX_FILETYPE_SOCKET = 0xC000;
//const int UNIX_FILETYPE_SYMLINK = 0xA000;
//const int UNIX_FILETYPE_BLOCKSPECIAL = 0x6000;
const int UNIX_FILETYPE_DIRECTORY = 0x4000;
//const int UNIX_FILETYPE_CHARSPECIAL = 0x2000;
//const int UNIX_FILETYPE_FIFO = 0x1000;
const int UNIX_EXEC = 1;
const int UNIX_WRITE = 2;
const int UNIX_READ = 4;
int MyPermissions = UNIX_READ | UNIX_WRITE;
int OtherPermissions = UNIX_READ;
int PlatformEncodedBy = (E.VersionMadeBy >> 8) & 0xFF;
int LowerBits = 0;
// Try to preserve read-only if it was set
bool bIsDirectory = E.IsDirectory;
// Check to see if this
bool bIsExecutable = false;
if (Path.GetFileNameWithoutExtension(E.FileName).Equals(GameName, StringComparison.InvariantCultureIgnoreCase))
{
bIsExecutable = true;
}
if (bIsExecutable)
{
// The executable will be encrypted in the final distribution IPA and will compress very poorly, so keeping it
// uncompressed gives a better indicator of IPA size for our distro builds
E.CompressionLevel = CompressionLevel.None;
}
if ((PlatformEncodedBy == FileAttributePlatform_NTFS) || (PlatformEncodedBy == FileAttributePlatform_FAT))
{
FileAttributes OldAttributes = E.Attributes;
//LowerBits = ((int)E.Attributes) & 0xFFFF;
if ((OldAttributes & FileAttributes.Directory) != 0)
{
bIsDirectory = true;
}
// Permissions
if ((OldAttributes & FileAttributes.ReadOnly) != 0)
{
MyPermissions &= ~UNIX_WRITE;
OtherPermissions &= ~UNIX_WRITE;
}
}
if (bIsDirectory || bIsExecutable)
{
MyPermissions |= UNIX_EXEC;
OtherPermissions |= UNIX_EXEC;
}
// Re-jigger the external file attributes to UNIX style if they're not already that way
if (PlatformEncodedBy != FileAttributePlatform_UNIX)
{
int NewAttributes = bIsDirectory ? UNIX_FILETYPE_DIRECTORY : UNIX_FILETYPE_NORMAL_FILE;
NewAttributes |= (MyPermissions << 6);
NewAttributes |= (OtherPermissions << 3);
NewAttributes |= (OtherPermissions << 0);
// Now modify the properties
E.AdjustExternalFileAttributes(FileAttributePlatform_UNIX, (NewAttributes << 16) | LowerBits);
}
}
// Save it out
Zip.Save(IPAName);
}
}
public override void PreBuildSync()
{
if (BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
BuiltBinaries = new List<string>();
}
base.PreBuildSync();
// Unzip any third party frameworks that are stored as zips
foreach ( UEBuildFramework Framework in RememberedAdditionalFrameworks )
{
string ZipSrcPath = GetRemoteFrameworkZipPath( Framework );
string ZipDstPath = GetRemoteIntermediateFrameworkZipPath( Framework );
Log.TraceInformation( "Unzipping: {0} -> {1}", ZipSrcPath, ZipDstPath );
CleanIntermediateDirectory( ZipDstPath );
// Assume that there is another directory inside the zip with the same name as the zip
ZipDstPath = ZipDstPath.Substring( 0, ZipDstPath.LastIndexOf( '/' ) );
if ( BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Mac )
{
// If we're on the mac, just unzip using the shell
string ResultsText;
RunExecutableAndWait( "unzip", String.Format( "-o \"{0}\" -d \"{1}\"", ZipSrcPath, ZipDstPath ), out ResultsText );
continue;
}
else
{
// Use RPC utility if the zip is on remote mac
Hashtable Result = RPCUtilHelper.Command( "/", String.Format( "unzip -o \"{0}\" -d \"{1}\"", ZipSrcPath, ZipDstPath ), "", null );
foreach ( DictionaryEntry Entry in Result )
{
Log.TraceInformation( "{0}", Entry.Value );
}
}
}
}
public override void PostBuildSync(UEBuildTarget Target)
{
base.PostBuildSync(Target);
string AppName = Target.TargetType == TargetRules.TargetType.Game ? Target.TargetName : Target.AppName;
if (BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Mac)
{
string RemoteShadowDirectoryMac = Path.GetDirectoryName(Target.OutputPath);
string FinalRemoteExecutablePath = String.Format("{0}/Payload/{1}.app/{1}", RemoteShadowDirectoryMac, AppName);
// strip the debug info from the executable if needed
if (BuildConfiguration.bStripSymbolsOnIOS || (Target.Configuration == UnrealTargetConfiguration.Shipping))
{
Process StripProcess = new Process();
StripProcess.StartInfo.WorkingDirectory = RemoteShadowDirectoryMac;
StripProcess.StartInfo.FileName = ToolchainDir + "strip";
StripProcess.StartInfo.Arguments = "\"" + Target.OutputPath + "\"";
StripProcess.OutputDataReceived += new DataReceivedEventHandler(OutputReceivedDataEventHandler);
StripProcess.ErrorDataReceived += new DataReceivedEventHandler(OutputReceivedDataEventHandler);
OutputReceivedDataEventHandlerEncounteredError = false;
OutputReceivedDataEventHandlerEncounteredErrorMessage = "";
Utils.RunLocalProcess(StripProcess);
if (OutputReceivedDataEventHandlerEncounteredError)
{
throw new Exception(OutputReceivedDataEventHandlerEncounteredErrorMessage);
}
}
// copy the executable
if (!File.Exists(FinalRemoteExecutablePath))
{
Directory.CreateDirectory(String.Format("{0}/Payload/{1}.app", RemoteShadowDirectoryMac, AppName));
}
File.Copy(Target.OutputPath, FinalRemoteExecutablePath, true);
if (BuildConfiguration.bCreateStubIPA)
{
string Project = Target.ProjectDirectory + "/" + AppName + ".uproject";
// generate the dummy project so signing works
if (AppName == "UE4Game" || AppName == "UE4Client" || Utils.IsFileUnderDirectory(Target.ProjectDirectory + "/" + AppName + ".uproject", Path.GetFullPath("../..")))
{
UnrealBuildTool.GenerateProjectFiles (new XcodeProjectFileGenerator (), new string[] {"-platforms=IOS", "-NoIntellIsense", "-iosdeployonly", "-ignorejunk"});
Project = Path.GetFullPath("../..") + "/UE4_IOS.xcodeproj";
}
else
{
Project = Target.ProjectDirectory + "/" + AppName + ".xcodeproj";
}
if (Directory.Exists (Project))
{
// ensure the plist, entitlements, and provision files are properly copied
var DeployHandler = UEBuildDeploy.GetBuildDeploy(Target.Platform);
if (DeployHandler != null)
{
DeployHandler.PrepTargetForDeployment(Target);
}
// code sign the project
string CmdLine = XcodeDeveloperDir + "usr/bin/xcodebuild" +
" -project \"" + Project + "\"" +
" -configuration " + Target.Configuration +
" -scheme '" + AppName + " - iOS'" +
" -sdk iphoneos" +
" CODE_SIGN_IDENTITY=\"iPhone Developer\"";
Console.WriteLine("Code signing with command line: " + CmdLine);
Process SignProcess = new Process ();
SignProcess.StartInfo.WorkingDirectory = RemoteShadowDirectoryMac;
SignProcess.StartInfo.FileName = "/usr/bin/xcrun";
SignProcess.StartInfo.Arguments = CmdLine;
SignProcess.OutputDataReceived += new DataReceivedEventHandler (OutputReceivedDataEventHandler);
SignProcess.ErrorDataReceived += new DataReceivedEventHandler (OutputReceivedDataEventHandler);
OutputReceivedDataEventHandlerEncounteredError = false;
OutputReceivedDataEventHandlerEncounteredErrorMessage = "";
Utils.RunLocalProcess (SignProcess);
// delete the temp project
if (Project.Contains ("_IOS.xcodeproj"))
{
Directory.Delete (Project, true);
}
if (OutputReceivedDataEventHandlerEncounteredError)
{
throw new Exception (OutputReceivedDataEventHandlerEncounteredErrorMessage);
}
// Package the stub
PackageStub (RemoteShadowDirectoryMac, AppName, Path.GetFileNameWithoutExtension (Target.OutputPath));
}
}
{
// Copy bundled assets from additional frameworks to the intermediate assets directory (so they can get picked up during staging)
String LocalFrameworkAssets = Path.GetFullPath( Target.ProjectDirectory + "/Intermediate/IOS/FrameworkAssets" );
// Clean the local dest directory if it exists
CleanIntermediateDirectory( LocalFrameworkAssets );
foreach ( UEBuildFramework Framework in RememberedAdditionalFrameworks )
{
if ( Framework.OwningModule == null || Framework.CopyBundledAssets == null || Framework.CopyBundledAssets == "" )
{
continue; // Only care if we need to copy bundle assets
}
if ( Framework.OwningModule.Target != Target )
{
continue; // This framework item doesn't belong to this target, skip it
}
string LocalZipPath = GetLocalFrameworkZipPath( Framework );
LocalZipPath = LocalZipPath.Replace( ".zip", "" );
// For now, this is hard coded, but we need to loop over all modules, and copy bundled assets that need it
string LocalSource = LocalZipPath + "/" + Framework.CopyBundledAssets;
string BundleName = Framework.CopyBundledAssets.Substring( Framework.CopyBundledAssets.LastIndexOf( '/' ) + 1 );
string LocalDest = LocalFrameworkAssets + "/" + BundleName;
Log.TraceInformation( "Copying bundled asset... LocalSource: {0}, LocalDest: {1}", LocalSource, LocalDest );
string ResultsText;
RunExecutableAndWait( "cp", String.Format( "-R -L {0} {1}", LocalSource.Replace(" ", "\\ "), LocalDest.Replace(" ", "\\ ") ), out ResultsText );
}
}
}
else
{
// store off the binaries
foreach (UEBuildBinary Binary in Target.AppBinaries)
{
BuiltBinaries.Add(Path.GetFullPath(Binary.ToString()));
}
// check to see if the DangerouslyFast mode is valid (in other words, a build has gone through since a Rebuild/Clean operation)
string DangerouslyFastValidFile = Path.Combine(Target.GlobalLinkEnvironment.Config.IntermediateDirectory, "DangerouslyFastIsNotDangerous");
bool bUseDangerouslyFastModeWasRequested = bUseDangerouslyFastMode;
if (bUseDangerouslyFastMode)
{
if (!File.Exists(DangerouslyFastValidFile))
{
Log.TraceInformation("Dangeroulsy Fast mode was requested, but a slow mode hasn't completed. Performing slow now...");
bUseDangerouslyFastMode = false;
}
}
foreach (string FilePath in BuiltBinaries)
{
string RemoteExecutablePath = ConvertPath(FilePath);
// when going super fast, just copy the executable to the final resting spot
if (bUseDangerouslyFastMode)
{
Log.TraceInformation("==============================================================================");
Log.TraceInformation("USING DANGEROUSLY FAST MODE! IF YOU HAVE ANY PROBLEMS, TRY A REBUILD/CLEAN!!!!");
Log.TraceInformation("==============================================================================");
// copy the executable
string RemoteShadowDirectoryMac = ConvertPath(Path.GetDirectoryName(Target.OutputPath));
string FinalRemoteExecutablePath = String.Format("{0}/Payload/{1}.app/{1}", RemoteShadowDirectoryMac, Target.TargetName);
RPCUtilHelper.Command("/", String.Format("cp -f {0} {1}", RemoteExecutablePath, FinalRemoteExecutablePath), "", null);
}
else if (!Utils.IsRunningOnMono && BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
RPCUtilHelper.CopyFile(RemoteExecutablePath, FilePath, false);
if (BuildConfiguration.bGeneratedSYMFile == true)
{
string DSYMExt = ".app.dSYM.zip";
RPCUtilHelper.CopyFile(RemoteExecutablePath + DSYMExt, FilePath + DSYMExt, false);
}
}
}
// Generate the stub
if (BuildConfiguration.bCreateStubIPA || bUseDangerouslyFastMode)
{
// ensure the plist, entitlements, and provision files are properly copied
var DeployHandler = UEBuildDeploy.GetBuildDeploy(Target.Platform);
if (DeployHandler != null)
{
DeployHandler.PrepTargetForDeployment(Target);
}
if (!bUseDangerouslyFastMode)
{
// generate the dummy project so signing works
UnrealBuildTool.GenerateProjectFiles(new XcodeProjectFileGenerator(), new string[] { "-NoIntellisense", "-iosdeployonly", (!string.IsNullOrEmpty(UnrealBuildTool.GetUProjectPath()) ? "-game" : "") });
}
// now that
Process StubGenerateProcess = new Process();
StubGenerateProcess.StartInfo.WorkingDirectory = Path.GetFullPath("..\\Binaries\\DotNET\\IOS");
StubGenerateProcess.StartInfo.FileName = Path.Combine(StubGenerateProcess.StartInfo.WorkingDirectory, "iPhonePackager.exe");
string Arguments = "";
string PathToApp = RulesCompiler.GetTargetFilename(AppName);
// right now, no programs have a Source subdirectory, so assume the PathToApp is directly in the root
if (Path.GetDirectoryName(PathToApp).Contains(@"\Engine\Source\Programs"))
{
PathToApp = Path.GetDirectoryName(PathToApp);
}
else
{
Int32 SourceIndex = PathToApp.LastIndexOf(@"\Intermediate\Source");
if (SourceIndex != -1)
{
PathToApp = PathToApp.Substring(0, SourceIndex);
}
else
{
SourceIndex = PathToApp.LastIndexOf(@"\Source");
if (SourceIndex != -1)
{
PathToApp = PathToApp.Substring(0, SourceIndex);
}
else
{
throw new BuildException("The target was not in a /Source subdirectory");
}
}
PathToApp += "\\" + AppName + ".uproject";
}
if (bUseDangerouslyFastMode)
{
// the quickness!
Arguments += "DangerouslyFast " + PathToApp;
}
else
{
Arguments += "PackageIPA \"" + PathToApp + "\" -createstub";
// if we are making the dsym, then we can strip the debug info from the executable
if (BuildConfiguration.bStripSymbolsOnIOS || (Target.Configuration == UnrealTargetConfiguration.Shipping))
{
Arguments += " -strip";
}
}
Arguments += " -config " + Target.Configuration + " -mac " + RemoteServerName;
var BuildPlatform = UEBuildPlatform.GetBuildPlatform(Target.Platform);
string Architecture = BuildPlatform.GetActiveArchitecture();
if (Architecture != "")
{
// pass along the architecture if we need, skipping the initial -, so we have "-architecture simulator"
Arguments += " -architecture " + Architecture.Substring(1);
}
if (!bUseRPCUtil )
{
Arguments += " -usessh";
Arguments += " -sshexe \"" + ResolvedSSHExe + "\"";
Arguments += " -sshauth \"" + ResolvedSSHAuthentication + "\"";
Arguments += " -sshuser \"" + ResolvedRSyncUsername + "\"";
Arguments += " -rsyncexe \"" + ResolvedRSyncExe + "\"";
Arguments += " -overridedevroot \"" + UserDevRootMac + "\"";
}
// programmers that use Xcode packaging mode should use the following commandline instead, as it will package for Xcode on each compile
// Arguments = "PackageApp " + GameName + " " + Configuration;
StubGenerateProcess.StartInfo.Arguments = Arguments;
StubGenerateProcess.OutputDataReceived += new DataReceivedEventHandler(OutputReceivedDataEventHandler);
StubGenerateProcess.ErrorDataReceived += new DataReceivedEventHandler(OutputReceivedDataEventHandler);
OutputReceivedDataEventHandlerEncounteredError = false;
OutputReceivedDataEventHandlerEncounteredErrorMessage = "";
int ExitCode = Utils.RunLocalProcess(StubGenerateProcess);
if (OutputReceivedDataEventHandlerEncounteredError)
{
UnrealBuildTool.ExtendedErrorCode = ExitCode;
throw new Exception(OutputReceivedDataEventHandlerEncounteredErrorMessage);
}
// now that a slow mode sync has finished, we can now do DangerouslyFast mode again (if requested)
if (bUseDangerouslyFastModeWasRequested)
{
File.Create(DangerouslyFastValidFile);
}
else
{
// if we didn't want dangerously fast, then delete the file so that setting/unsetting the flag will do the right thing without a Rebuild
File.Delete(DangerouslyFastValidFile);
}
}
{
// Copy bundled assets from additional frameworks to the intermediate assets directory (so they can get picked up during staging)
String LocalFrameworkAssets = Path.GetFullPath( Target.ProjectDirectory + "/Intermediate/IOS/FrameworkAssets" );
String RemoteFrameworkAssets = ConvertPath( LocalFrameworkAssets );
CleanIntermediateDirectory( RemoteFrameworkAssets );
// Delete the local dest directory if it exists
if ( Directory.Exists( LocalFrameworkAssets ) )
{
Directory.Delete( LocalFrameworkAssets, true );
}
foreach ( UEBuildFramework Framework in RememberedAdditionalFrameworks )
{
if ( Framework.OwningModule == null || Framework.CopyBundledAssets == null || Framework.CopyBundledAssets == "" )
{
continue; // Only care if we need to copy bundle assets
}
if ( Framework.OwningModule.Target != Target )
{
continue; // This framework item doesn't belong to this target, skip it
}
string RemoteZipPath = GetRemoteIntermediateFrameworkZipPath( Framework );
RemoteZipPath = RemoteZipPath.Replace( ".zip", "" );
// For now, this is hard coded, but we need to loop over all modules, and copy bundled assets that need it
string RemoteSource = RemoteZipPath + "/" + Framework.CopyBundledAssets;
string BundleName = Framework.CopyBundledAssets.Substring( Framework.CopyBundledAssets.LastIndexOf( '/' ) + 1 );
String RemoteDest = RemoteFrameworkAssets + "/" + BundleName;
String LocalDest = LocalFrameworkAssets + "\\" + BundleName;
Log.TraceInformation( "Copying bundled asset... RemoteSource: {0}, RemoteDest: {1}, LocalDest: {2}", RemoteSource, RemoteDest, LocalDest );
Hashtable Results = RPCUtilHelper.Command( "/", String.Format( "cp -R -L {0} {1}", RemoteSource.Replace(" ", "\\ "), RemoteDest.Replace(" ", "\\ ") ), "", null );
foreach ( DictionaryEntry Entry in Results )
{
Log.TraceInformation( "{0}", Entry.Value );
}
// Copy the bundled resource from the remote mac to the local dest
RPCUtilHelper.CopyDirectory( RemoteDest, LocalDest, RPCUtilHelper.ECopyOptions.None );
}
}
}
}
public override UnrealTargetPlatform GetPlatform()
{
return UnrealTargetPlatform.IOS;
}
public static int RunExecutableAndWait( string ExeName, string ArgumentList, out string StdOutResults )
{
// Create the process
ProcessStartInfo PSI = new ProcessStartInfo( ExeName, ArgumentList );
PSI.RedirectStandardOutput = true;
PSI.UseShellExecute = false;
PSI.CreateNoWindow = true;
Process NewProcess = Process.Start( PSI );
// Wait for the process to exit and grab it's output
StdOutResults = NewProcess.StandardOutput.ReadToEnd();
NewProcess.WaitForExit();
return NewProcess.ExitCode;
}
public override void StripSymbols(string SourceFileName, string TargetFileName)
{
SetupXcodePaths(false);
StripSymbolsWithXcode(SourceFileName, TargetFileName, ToolchainDir);
}
};
}
| |
using UnityEngine;
using UnityEngine.UI;
public class RowingDetectionScript : MonoBehaviour
{
private GestureListener gestureListener;
public bool controlWithGestures = true;
public bool controlWithKeys = true;
// Bunch of variable switches
private bool rowForward = false;
private bool rowLeft = false;
private bool rowRight = false;
// Sequence of gestures
private bool leftSequenceLock = false;
private bool rightSequenceLock = false;
private bool startSequenceLock = false;
// Objects and text items
public Text debugText;
public Text debugText2;
public Text debugText3;
public Text debugText4;
public GameObject modelcic;
Vector3 modelcicStartPos;
void Awake()
{
GameObject text = GameObject.Find("/Canvas/DebugText");
GameObject text2 = GameObject.Find("/Canvas/DebugText2");
GameObject text3 = GameObject.Find("/Canvas/DebugText3");
GameObject text4 = GameObject.Find("/Canvas/DebugText4");
debugText = text.GetComponent<Text>();
debugText2 = text2.GetComponent<Text>();
debugText3 = text3.GetComponent<Text>();
debugText4 = text4.GetComponent<Text>();
modelcic = GameObject.Find("Modelcic_Character");
// hide / display mouse cursor
Cursor.visible = true;
}
void Start()
{
// get the gestures listener
gestureListener = Camera.main.GetComponent<GestureListener>();
debugText.text = "";
debugText2.text = "";
debugText3.text = "";
debugText4.text = "";
modelcicStartPos = transform.position;
}
void Update()
{
// dont run Update() if there is no user
KinectManager kinectManager = KinectManager.Instance;
if (!kinectManager || !kinectManager.IsInitialized() || !kinectManager.IsUserDetected())
return;
// Gesture control and sequence start
if (controlWithGestures && gestureListener && !startSequenceLock)
{
debugText.text = "Listening for gestures!";
debugText2.text = "Waiting for sequqnce lock!";
debugText3.text = "!";
debugText4.text = "!";
// try to create a combination that is rowing forward..
// If push is detected then go into listening mode for another gesture..
// RaiseLeftHand -> Push detected. Waiting or pull..Pull detected -> action recognized -> row forward
if (gestureListener.IsWave())
{
// Reset everything...
Debug.Log("Wave detected, resetting everything!");
debugText.text = "RESET!";
Reset();
}
// Beginning of either row forward or turn left gesture detection.
if (gestureListener.IsRaiseLeftHand() || gestureListener.IsRaiseRightHand())
{
startSequenceLock = true;
debugText.text = "Started hand sequence.";
Debug.Log("Started hand sequence");
}
// Beginning of the row left gesture detection.
if (gestureListener.IsLeftPush() && startSequenceLock)
{
leftSequenceLock = true;
}
// Beginning of the row right gesture detection.
if (gestureListener.IsRightPush() && startSequenceLock)
{
rightSequenceLock = true;
}
}
if (startSequenceLock && gestureListener)
{
Debug.Log("In Hand Sequence lock.");
if (gestureListener.IsLeftPush())
{
leftSequenceLock = true;
debugText2.text = "Sequence locked, detected LEFT push, now waiting for LEFT pull.";
Debug.Log("Sequence locked, detected LEFT push, now waiting for LEFT pull.");
}
if (gestureListener.IsRightPush())
{
rightSequenceLock = true;
debugText2.text = "Sequence locked, detected RIGHT push, now waiting for RIGHT pull.";
Debug.Log("Sequence locked, detected RIGHT push, now waiting for RIGHT pull.");
}
}
// LEFT sequence lock, wait for another gesture in the sequence
if (leftSequenceLock && gestureListener)
{
Debug.Log("In LEFT Sequence lock.");
// Check if the next gesture fits the sequence of forward row (push, down / pull)
if (gestureListener.IsLeftPull())
{
// we have a rowing sequence, log to console and display info
debugText3.text = "Rowing LEFT detected.";
Debug.Log("Rowing LEFT detected.");
// Row left until new command detected...
RowLeft();
leftSequenceLock = false;
}
}
// RIGHT sequence lock, wait for another gesture in the sequence
if (rightSequenceLock && gestureListener)
{
Debug.Log("In RIGHT Sequence lock.");
// Check if the next gesture fits the sequence of forward row (push, down / pull)
if (gestureListener.IsRightPull())
{
// we have a rowing sequence, log to console and display info
debugText3.text = "Rowing RIGHT detected.";
Debug.Log("Rowing RIGHT detected.");
// Row right until new command detected...
RowRight();
rightSequenceLock = false;
}
}
}
private void RowForward()
{
for (int i = 0; i < 20; i++)
transform.Translate(Vector3.forward * Time.deltaTime, modelcic.transform);
}
private void RowLeft()
{
for (int i = 0; i < 20; i++)
transform.Translate(Vector3.left * Time.deltaTime, modelcic.transform);
}
private void RowRight()
{
for (int i = 0; i < 20; i++)
transform.Translate(Vector3.right * Time.deltaTime, modelcic.transform);
}
private void Reset()
{
debugText.text = "";
debugText2.text = "";
debugText3.text = "";
debugText4.text = "";
rowForward = false;
rowLeft = false;
rowRight = false;
startSequenceLock = false;
leftSequenceLock = false;
rightSequenceLock = false;
// Reset character position
transform.Translate(modelcicStartPos, modelcic.transform);
}
}
| |
using System;
using System.Data;
using System.Configuration;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
/// <summary>
/// Summary description for SchedulingPDFGenerator
/// </summary>
public class SchedulingPDFGenerator
{
private static PdfPTable createSchedulingBodyTable()
{
// Font definition
Font lineDataFont = new Font(Font.HELVETICA, Font.DEFAULTSIZE + 8, Font.BOLD);
Font lineHeaderFont = new Font(Font.HELVETICA, Font.DEFAULTSIZE - 1);
Font productDataFont = new Font(Font.HELVETICA, Font.DEFAULTSIZE - 1);
Font productNameFont = new Font(Font.HELVETICA, Font.DEFAULTSIZE, Font.BOLD);
Font productHeaderFont = new Font(Font.HELVETICA, Font.DEFAULTSIZE - 4);
Font notesFont = new Font(Font.HELVETICA, Font.DEFAULTSIZE - 3);
Font hiddenDataFont = new Font(Font.HELVETICA, Font.DEFAULTSIZE + 10, 0, Color.WHITE);
Font dueWeekAndMonthDataFont = new Font(Font.TIMES_ROMAN, Font.DEFAULTSIZE - 1);
// PdfPTable definition
PdfPTable dataTable;
PdfPTable subTable = new PdfPTable(1);
float normalContentHeight = 1.0f;
float normalHeaderHeight = 1.0f;
float commonPadding = 2.0f;
// /////////////////////////////////////////////////////
dataTable = PdfGenerator.createNewCompactTable(3);
dataTable.SetWidths(new float[] { 0.33f, 0.34f, 0.33f} );
SchedulingManagement scedulingManagement =
new SchedulingManagement();
PlanningManagement planningManager =
new PlanningManagement();
ProdProcessCore.SetupRow setup =
new SetupManagement().GetCurrentSetup();
for (int line = 1; line <= setup.LinesNumber; line++)
{
PdfPTable dataTableOneLine = PdfGenerator.createNewCompactTable(1);
dataTableOneLine.AddCell(
PdfGenerator.createNewCompactCell(
"" + line, lineDataFont,
"Linea", lineHeaderFont,
0.0f, 0.5f, normalContentHeight, normalHeaderHeight, commonPadding));
ProdProcessCurrent.OrderProductsDataTable productList =
scedulingManagement.GetScheduledProducts(0, line);
foreach (ProdProcessCurrent.OrderProductsRow product in productList)
{
ProdProcessCurrent.OrderRow orderData =
planningManager.GetIncomingOrders(
product.OrderSetNo, product.OrderSerialNo);
PdfPTable dataTableQuantityAndNotes = PdfGenerator.createNewCompactTable(2);
dataTableQuantityAndNotes.SetWidths(new float[] { 0.8f, 0.2f });
dataTableQuantityAndNotes.AddCell(
PdfGenerator.createNewCompactCell(
orderData.ClientName, productDataFont,
product.ProductID, productNameFont,
0.0f, 0.0f, normalContentHeight, normalHeaderHeight, commonPadding));
string notes = (product.IsNotesNull() || product.Notes.Trim().Length == 0) ?
"-" : product.Notes;
string quantityStr =
(product.OrderSetNo == 1) ? "-" :
"" + Math.Round(product.Quantity, 1) + "Kg";
dataTableQuantityAndNotes.AddCell(
PdfGenerator.createNewCompactCell(
quantityStr, productDataFont,
0.0f, 0.0f, normalContentHeight, commonPadding));
dataTableQuantityAndNotes.AddCell(
PdfGenerator.createNewCompactCell(
notes, notesFont,
0.0f, 0.0f, normalContentHeight, commonPadding));
string dueWeekAndMonth = ProdProcess.DateTimeUtility.getDueWeekAndMonth(product);
dataTableQuantityAndNotes.AddCell(
PdfGenerator.createNewCompactCell(
dueWeekAndMonth, dueWeekAndMonthDataFont,
"" + Math.Round(product.QuantityReal, 1) + "Kg", productDataFont,
0.0f, 0.0f, normalContentHeight, normalContentHeight, commonPadding));
dataTableOneLine.AddCell(dataTableQuantityAndNotes);
}
dataTable.AddCell(dataTableOneLine);
}
subTable.AddCell(
PdfGenerator.createNewCompactCell(dataTable));
return subTable;
} // createSchedulingBodyTable
// ------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <param name="schedulingCode"></param>
/// <param name="request"></param>
/// <param name="writer"></param>
/// <returns></returns>
private static PdfPTable createSchedulingHeaderTable(
string schedulingCode,
System.Web.HttpRequest request,
PdfWriter writer)
{
// Font definition
Font productDataFont = new Font(Font.HELVETICA, Font.DEFAULTSIZE + 8, Font.BOLD);
Font productHeaderFont = new Font(Font.HELVETICA, Font.DEFAULTSIZE - 2);
Font hiddenDataFont = new Font(Font.HELVETICA, Font.DEFAULTSIZE + 10, 0, Color.WHITE);
// PdfPTable definition
PdfPTable dataTable;
PdfPTable subTable = new PdfPTable(1);
float normalContentHeight = 1.0f;
float normalHeaderHeight = 1.0f;
float commonPadding = 6.0f;
// /////////////////////////////////////////////////////
dataTable = PdfGenerator.createNewCompactTable(3);
dataTable.SetWidths(new float[] { 0.25f, 0.45f, 0.3f });
Image imageLabel = Image.GetInstance(request.MapPath("Images//mdplastlabel.jpg"));
imageLabel.Alignment = Image.LEFT_ALIGN;
imageLabel.ScalePercent(50.0f);
PdfPCell cell = new PdfPCell(imageLabel);
cell.BorderWidth = 0.0f;
cell.Padding = 3.0f;
cell.PaddingBottom = 10.0f;
dataTable.AddCell(cell);
// /////////////////////////////////////////////////////
//dataTable = createNewCompactTable(1);
string dateTime = DateTime.Now.ToString("HH:mm");
dataTable.AddCell(
PdfGenerator.createNewCompactCell(
schedulingCode, productDataFont,
"Programma macchinari - " + dateTime, productHeaderFont,
0.0f, 0.0f, normalContentHeight, normalHeaderHeight, commonPadding));
// BARCODE
Barcode128 barcode = new Barcode128();
barcode.Code = schedulingCode;
Image imageBarcode = barcode.CreateImageWithBarcode(writer.DirectContent, null, null);
cell = new PdfPCell(imageBarcode);
cell.BorderWidth = 0.0f;
cell.PaddingBottom = 10.0f;
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_BOTTOM;
dataTable.AddCell(cell);
cell = PdfGenerator.createNewCompactCell(dataTable);
cell.BorderWidthBottom = 0.5f;
cell.BorderColor = Color.LIGHT_GRAY;
subTable.AddCell(
PdfGenerator.createNewCompactCell(dataTable));
// /////////////////////////////////////////////////////
return subTable;
}
public static void printSchedulingList(
Stream outStream, System.Web.HttpRequest request)
{
// Create the pdf document
Rectangle rect = new Rectangle(PageSize.A4.Rotate());
Document document = new Document(rect, 30, 30, 30, 30);
// Cretate the writer
PdfWriter writer = PdfWriter.GetInstance(document, outStream);
document.Open();
PdfPTable wholeTable = new PdfPTable(1);
wholeTable.WidthPercentage = 100;
// Create scheduling code (date)
string schedulingCode = "PM_" + DateTime.Today.ToString("dd-MM-yyyy");
PdfPCell cell = PdfGenerator.createNewCompactCell(
createSchedulingHeaderTable(schedulingCode, request, writer));
cell.BorderWidth = 0.5f;
cell.BorderColor = Color.LIGHT_GRAY;
wholeTable.AddCell(cell);
cell = PdfGenerator.createNewCompactCell(
createSchedulingBodyTable());
cell.BorderWidth = 0.5f;
cell.BorderColor = Color.LIGHT_GRAY;
wholeTable.AddCell(cell);
document.Add(wholeTable);
document.Close();
} // Scheduling
}
| |
using PA.Plugin.Threads.Attributes;
using PA.Plugin.Threads.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Threading;
namespace PA.Plugin.Threads
{
[PartNotDiscoverable]
[DefaultProperty("LoopSpan")]
public partial class PluginThread : PluginBase, IPluginThread
{
private Thread _tLoop;
private Semaphore _sLoop;
public EventHandler<EventArgs> RunStarted;
public EventHandler<EventArgs> RunLoop;
public EventHandler<EventArgs> RunCompleted;
public TimeSpan LoopSpan { get; private set; }
public TimeSpan WaitSpan { get; private set; }
public bool IsPaused { get; private set; }
public bool IsRunning { get; private set; }
public bool IsFirstLoop { get; private set; }
public PluginThread() :
base()
{
int maxInstances1 = PluginBase.GetAttribute<PluginThreadAttribute>(this.GetType()).MaxInstances;
int maxInstances2 = PluginBase.GetAttribute<PluginThreadAttribute>(typeof(PluginThread)).MaxInstances;
if (PluginThread.idList == null)
{
PluginThread.idList = new List<IPluginThread>(maxInstances2);
}
List<IPluginThread> list = new List<IPluginThread>(PluginThread.idList);
if (list.FindAll(p => p.GetType().IsSubclassOf(this.GetType())).Count >= maxInstances1)
{
throw new IndexOutOfRangeException("Cannot start more than " + maxInstances1.ToString() + " " + this + " threads");
}
else if (PluginThread.idList.Count >= maxInstances2)
{
throw new IndexOutOfRangeException("Cannot start more than " + maxInstances2.ToString() + " " + this + " threads");
}
// List thread
PluginThread.idList.Add((IPluginThread)this);
// Init Thread
this._tLoop = new Thread(new ThreadStart(this.Loop));
this._tLoop.Name = this.GetType().FullName;
this._sLoop = new Semaphore(1, 1);
this.LoopSpan = new TimeSpan(0, 1, 0);
this.IsRunning = false;
this.IsPaused = false;
this.IsFirstLoop = true;
}
#region IPluginThread Members
private static List<IPluginThread> idList;
[Browsable(false)]
public int ThreadId
{
get { return this.DesignMode ? -1 : idList.IndexOf(this as IPluginThread); }
}
public bool Start()
{
this.IsPaused = false;
if (!this._tLoop.IsAlive)
{
Trace.TraceInformation(this + " is starting...");
this._tLoop.Start();
Trace.TraceInformation(this + " is started.");
}
return true;
}
public bool Stop()
{
this.IsRunning = false;
if (this._tLoop.IsAlive)
{
Trace.TraceInformation(this + " is stopping...");
if (this._tLoop.ThreadState == System.Threading.ThreadState.WaitSleepJoin)
{
this._tLoop.Abort();
}
else
{
this._tLoop.Join();
}
Trace.TraceInformation(this + " is stopped");
}
return true;
}
public bool Pause()
{
if (this._tLoop.IsAlive)
{
this.IsPaused = true;
}
return true;
}
#endregion
[Obsolete]
private void Loop()
{
this.IsRunning = true;
this.OnRunStarted();
while (true)
{
if (!this.IsRunning)
{
break;
}
DateTime now = DateTime.Now;
if (!this.IsPaused)
{
this._sLoop.WaitOne();
{
try
{
this.Execute();
}
catch (Exception ex)
{
Trace.TraceError(this + " (" + ex.Source + ") is stopping after exception: " + ex.Message + "\n" + (ex.InnerException is Exception ? ex.InnerException.Message : ex.StackTrace), EventLogEntryType.Error);
this.IsRunning = false;
}
}
this._sLoop.Release();
}
else
{
this.Wait(TimeSpan.FromMinutes(10));
}
if (this.IsRunning)
{
if (this.WaitSpan == TimeSpan.Zero)
{
Thread.Sleep(this.LoopSpan - (now - DateTime.Now));
}
else
{
Thread.Sleep(this.WaitSpan);
}
}
this.WaitSpan = TimeSpan.Zero;
this.IsFirstLoop = false;
}
this.OnRunCompleted();
}
[Obsolete]
public virtual void OnRunStarted()
{
if (this.RunStarted != null)
{
this.RunStarted(this, new EventArgs());
}
}
[Obsolete]
public virtual void OnRunCompleted()
{
if (this.RunCompleted != null)
{
this.RunCompleted(this, new EventArgs());
}
}
// public virtual void Execute(IJobExecutionContext context)
//{
// this.Execute();
//}
[Obsolete]
public virtual void Execute()
{
if (this.RunLoop != null)
{
this.RunLoop(this, new EventArgs());
}
}
[Obsolete]
protected void Wait(TimeSpan ws)
{
this.WaitSpan = ws;
}
[Obsolete]
protected void Wait(DateTime wd)
{
bool flag = !(wd < DateTime.Now);
if (flag)
{
this.WaitSpan = wd - DateTime.Now;
return;
}
else
{
throw new ArgumentOutOfRangeException();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.crypto.engines;
namespace Org.BouncyCastle.Bcpg.OpenPgp
{
/// <remarks>A public key encrypted data object.</remarks>
public class PgpPublicKeyEncryptedData : PgpEncryptedData
{
private readonly PublicKeyEncSessionPacket _keyData;
internal PgpPublicKeyEncryptedData(PublicKeyEncSessionPacket keyData, InputStreamPacket encData)
: base(encData)
{
_keyData = keyData;
}
private static IBufferedCipher GetKeyCipher(PublicKeyAlgorithmTag algorithm)
{
try
{
switch (algorithm)
{
case PublicKeyAlgorithmTag.RsaEncrypt:
case PublicKeyAlgorithmTag.RsaGeneral:
return CipherUtilities.GetCipher("RSA//PKCS1Padding");
case PublicKeyAlgorithmTag.ElGamalEncrypt:
case PublicKeyAlgorithmTag.ElGamalGeneral:
return CipherUtilities.GetCipher("ElGamal/ECB/PKCS1Padding");
default:
throw new PgpException("unknown asymmetric algorithm: " + algorithm);
}
}
catch (PgpException)
{
throw;
}
catch (Exception e)
{
throw new PgpException("Exception creating cipher", e);
}
}
private static bool ConfirmCheckSum(byte[] sessionInfo)
{
var check = 0;
for (var i = 1; i != sessionInfo.Length - 2; i++)
{
check += sessionInfo[i] & 0xff;
}
return (sessionInfo[sessionInfo.Length - 2] == (byte)(check >> 8))
&& (sessionInfo[sessionInfo.Length - 1] == (byte)(check));
}
/// <summary>
/// Gets the key algorithm.
/// </summary>
/// <value>
/// The key algorithm.
/// </value>
public PublicKeyAlgorithmTag KeyAlgorithm
{
get { return _keyData.Algorithm; }
}
/// <summary>
/// The key ID for the key used to encrypt the data.
/// </summary>
/// <value>
/// The key id.
/// </value>
public long KeyId
{
get { return _keyData.KeyId; }
}
/// <summary>
/// Return the algorithm code for the symmetric algorithm used to encrypt the data.
/// </summary>
/// <param name="privKey">The priv key.</param>
/// <returns></returns>
public SymmetricKeyAlgorithmTag GetSymmetricAlgorithm(IPgpPrivateKey privKey)
{
var plain = FetchSymmetricKeyData(privKey);
return (SymmetricKeyAlgorithmTag)plain[0];
}
/// <summary>
/// Return the decrypted data stream for the packet.
/// </summary>
/// <param name="privKey">The priv key.</param>
/// <returns></returns>
/// <exception cref="PgpException">
/// exception creating cipher
/// or
/// Exception starting decryption
/// </exception>
/// <exception cref="System.IO.EndOfStreamException">
/// unexpected end of stream.
/// or
/// unexpected end of stream.
/// </exception>
public Stream GetDataStream(IPgpPrivateKey privKey)
{
SymmetricKeyAlgorithmTag encryptionAlgorithm;
return this.GetDataStream(privKey, out encryptionAlgorithm);
}
/// <summary>
/// Gets the data stream.
/// </summary>
/// <param name="privKey">The priv key.</param>
/// <param name="encryptionAlgorithm">The encryption algorithm.</param>
/// <returns></returns>
/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
/// exception creating cipher
/// or
/// Exception starting decryption
/// </exception>
/// <exception cref="System.IO.EndOfStreamException">
/// unexpected end of stream.
/// or
/// unexpected end of stream.
/// </exception>
public Stream GetDataStream(IPgpPrivateKey privKey, out SymmetricKeyAlgorithmTag encryptionAlgorithm)
{
var plain = this.FetchSymmetricKeyData(privKey);
encryptionAlgorithm = (SymmetricKeyAlgorithmTag)plain[0];
IBufferedCipher c2;
var cipherName = PgpUtilities.GetSymmetricCipherName(encryptionAlgorithm);
var cName = cipherName;
try
{
if (EncData is SymmetricEncIntegrityPacket)
{
cName += "/CFB/NoPadding";
}
else
{
cName += "/OpenPGPCFB/NoPadding";
}
c2 = CipherUtilities.GetCipher(cName);
}
catch (PgpException)
{
throw;
}
catch (Exception e)
{
throw new PgpException("exception creating cipher", e);
}
if (c2 == null)
return EncData.GetInputStream();
try
{
var key = ParameterUtilities.CreateKeyParameter(cipherName, plain, 1, plain.Length - 3);
var iv = new byte[c2.GetBlockSize()];
c2.Init(false, new ParametersWithIV(key, iv));
this.EncStream = BcpgInputStream.Wrap(new CipherStream(EncData.GetInputStream(), c2, null));
if (this.EncData is SymmetricEncIntegrityPacket)
{
this.TruncStream = new TruncatedStream(this.EncStream);
var digest = DigestUtilities.GetDigest(PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1));
EncStream = new DigestStream(TruncStream, digest, null);
}
if (Streams.ReadFully(EncStream, iv, 0, iv.Length) < iv.Length)
throw new EndOfStreamException("unexpected end of stream.");
var v1 = this.EncStream.ReadByte();
var v2 = this.EncStream.ReadByte();
if (v1 < 0 || v2 < 0)
throw new EndOfStreamException("unexpected end of stream.");
// Note: the oracle attack on the "quick check" bytes is deemed
// a security risk for typical public key encryption usages,
// therefore we do not perform the check.
// bool repeatCheckPassed =
// iv[iv.Length - 2] == (byte)v1
// && iv[iv.Length - 1] == (byte)v2;
//
// // Note: some versions of PGP appear to produce 0 for the extra
// // bytes rather than repeating the two previous bytes
// bool zeroesCheckPassed =
// v1 == 0
// && v2 == 0;
//
// if (!repeatCheckPassed && !zeroesCheckPassed)
// {
// throw new PgpDataValidationException("quick check failed.");
// }
return this.EncStream;
}
catch (PgpException)
{
throw;
}
catch (Exception e)
{
throw new PgpException("Exception starting decryption", e);
}
}
private void ProcessSymmetricKeyDataForRsa(IBufferedCipher cipher, IList<IBigInteger> symmetricKeyData)
{
cipher.ProcessBytes(symmetricKeyData[0].ToByteArrayUnsigned());
}
private void ProcessSymmetricKeyDataForElGamal(IPgpPrivateKey privateKey, IBufferedCipher cipher, IList<IBigInteger> symmetricKeyData)
{
var k = (ElGamalPrivateKeyParameters)privateKey.Key;
var size = (k.Parameters.P.BitLength + 7) / 8;
var bi = symmetricKeyData[0].ToByteArray();
var diff = bi.Length - size;
if (diff >= 0)
{
cipher.ProcessBytes(bi, diff, size);
}
else
{
var zeros = new byte[-diff];
cipher.ProcessBytes(zeros);
cipher.ProcessBytes(bi);
}
bi = symmetricKeyData[1].ToByteArray();
diff = bi.Length - size;
if (diff >= 0)
{
cipher.ProcessBytes(bi, diff, size);
}
else
{
var zeros = new byte[-diff];
cipher.ProcessBytes(zeros);
cipher.ProcessBytes(bi);
}
}
private byte[] ProcessSymmetricKeyDataForEcdh(IPgpPrivateKey privKey, IList<IBigInteger> symmetricKeyData)
{
var encSymKey = symmetricKeyData[1].ToByteArrayUnsigned();
var privateKey = (ECDHPrivateKeyParameters)privKey.Key;
var publicKey = privateKey.PublicKeyParameters;
var ephemeralKey = ECDHPublicKeyParameters.Create(symmetricKeyData[0], publicKey.PublicKeyParamSet, publicKey.HashAlgorithm, publicKey.SymmetricKeyAlgorithm);
var engine = new RFC6637ECDHEngine();
engine.InitForDecryption(privateKey, ephemeralKey);
return engine.ProcessBlock(encSymKey, 0, encSymKey.Length);
}
private byte[] FetchSymmetricKeyData(IPgpPrivateKey privKey)
{
byte[] plain;
var keyD = _keyData.GetEncSessionKey();
if (_keyData.Algorithm == PublicKeyAlgorithmTag.Ecdh)
{
plain = this.ProcessSymmetricKeyDataForEcdh(privKey, keyD);
}
else
{
var c1 = GetKeyCipher(_keyData.Algorithm);
try
{
c1.Init(false, privKey.Key);
}
catch (InvalidKeyException e)
{
throw new PgpException("error setting asymmetric cipher", e);
}
switch (_keyData.Algorithm)
{
case PublicKeyAlgorithmTag.RsaGeneral:
case PublicKeyAlgorithmTag.RsaEncrypt:
this.ProcessSymmetricKeyDataForRsa(c1, keyD);
break;
default:
this.ProcessSymmetricKeyDataForElGamal(privKey, c1, keyD);
break;
}
try
{
plain = c1.DoFinal();
}
catch (Exception e)
{
throw new PgpException("exception decrypting secret key", e);
}
}
if (!ConfirmCheckSum(plain))
throw new PgpKeyValidationException("key checksum failed");
return plain;
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Vevo.Domain;
using Vevo.Domain.Discounts;
using Vevo.Domain.Orders;
using Vevo.Domain.Products;
using Vevo.WebUI;
using Vevo.Shared.Utilities;
using System.Collections.Generic;
using Vevo.Domain.Stores;
using Vevo.Domain.Marketing;
public partial class Components_MobileCouponMessageDisplay : Vevo.WebUI.International.BaseLanguageUserControl
{
#region Private
private void HideAllControls()
{
uxCouponAmountDiv.Visible = false;
uxCouponExpireDateDiv.Visible = false;
uxAvailableItemHeaderListDiv.Visible = false;
uxAvailableItemListDiv.Visible = false;
uxErrorMessageDiv.Visible = false;
uxPromotionWarningDiv.Visible = false;
}
private void DisplayError( string errorMessage )
{
uxErrorMessage.DisplayErrorNoNewLine( errorMessage );
uxErrorMessageDiv.Visible = true;
}
private string GetCustomerError()
{
return "[$ErrorCouponUserName]";
}
private string GetProductError( Coupon coupon )
{
string message = "<p>[$ErrorInvalidProduct]</p> <p>[$ProductListHeader]</p>";
message += GetApplicableProductListText( coupon, "all_product" );
return message;
}
private string GetOrderAmountError( Coupon coupon )
{
string message = String.Format( "<p>[$ErrorCouponMinimumOrder] {0}.</p>",
StoreContext.Currency.FormatPrice( coupon.MinimumSubtotal ) );
if (coupon.ProductCostType == Coupon.ProductCostTypeEnum.CouponEligibleProducts)
message += "<p>[$ErrorCouponMinimumOrderEligible]</p>";
return message;
}
private string GetCategoryError( Coupon coupon )
{
string message = "<p>[$ErrorInvalidCategory]</p> <p>[$CategoryListHeader]</p>";
message += GetApplicableCategoryListText( coupon );
return message;
}
private string GetExpiredError( Coupon coupon )
{
switch (coupon.ExpirationStatus)
{
case Coupon.ExpirationStatusEnum.ExpiredByDate:
return "[$InvalidExpired]";
case Coupon.ExpirationStatusEnum.ExpiredByQuantity:
return "[$InvalidOverLimit]";
default:
return "[$InvalidCoupon]";
}
}
private string GetInvalidCodeError()
{
return "[$InvalidCoupon]";
}
private string GetBelowMinimumQuantityError( Coupon coupon )
{
string message = "<p>" + GetDiscountTypeBuyXGetYText( coupon, true ) + "</p>";
message += "<p>[$ShoppingCartProductListHeader]</p>";
message += "<p>" + GetApplicableProductListText( coupon, "not_match_product" ) + "</p>";
return message;
}
private string GetFormattedError( Coupon coupon, CartItemGroup cartItemGroup )
{
switch (coupon.Validate( cartItemGroup, StoreContext.Customer ))
{
case Coupon.ValidationStatus.InvalidCustomer:
return GetCustomerError();
case Coupon.ValidationStatus.BelowMinimumOrderAmount:
return GetOrderAmountError( coupon );
case Coupon.ValidationStatus.InvalidProduct:
if (coupon.ProductFilter == Coupon.ProductFilterEnum.ByProductIDs)
return GetProductError( coupon );
else
return GetCategoryError( coupon );
case Coupon.ValidationStatus.Expired:
return GetExpiredError( coupon );
case Coupon.ValidationStatus.InvalidCode:
return GetInvalidCodeError();
case Coupon.ValidationStatus.BelowMinimumQuantity:
return GetBelowMinimumQuantityError( coupon );
default:
return String.Empty;
}
}
private decimal GetCouponDiscount( Coupon coupon )
{
IList<decimal> discountLines;
return coupon.GetDiscount(
StoreContext.ShoppingCart.GetAllCartItems(),
StoreContext.Customer,
out discountLines );
}
private string GetApplicableProductListText( Coupon coupon, string productListType )
{
string message = String.Empty;
switch (productListType)
{
case "all_product":
{
message = "<ul>";
foreach (Product product in coupon.GetApplicableProducts( StoreContext.Culture ))
{
if (!String.IsNullOrEmpty( product.Name ))
message += "<li>" + product.Name + "</li> ";
}
message += "</ul>";
}
break;
case "match_product":
{
if (GetCouponDiscount( coupon ) > 0)
{
ICartItem[] cart = StoreContext.ShoppingCart.GetCartItems();
int productDiscoutableItemCount = 0;
if (coupon.ProductFilter != Coupon.ProductFilterEnum.All)
{
message = "<ul>";
for (int i = 0; i < cart.Length; i++)
{
if (coupon.IsProductDiscountable( cart[i].Product )
&& cart[i].DiscountGroupID == "0"
&& cart[i].Quantity > coupon.MinimumQuantity)
{
message += "<li>"
+ cart[i].GetName( StoreContext.Culture, StoreContext.Currency )
+ "</li>";
productDiscoutableItemCount++;
}
}
message += "</ul>";
if (productDiscoutableItemCount == cart.Length)
{
message = string.Empty;
}
}
}
}
break;
case "not_match_product":
{
if (GetCouponDiscount( coupon ) == 0)
{
ICartItem[] cart = StoreContext.ShoppingCart.GetCartItems();
message = "<ul>";
for (int i = 0; i < cart.Length; i++)
{
if (coupon.IsProductDiscountable( cart[i].Product )
&& cart[i].DiscountGroupID == "0")
{
message += "<li>"
+ cart[i].GetName( StoreContext.Culture, StoreContext.Currency )
+ "</li>";
}
}
message += "</ul>";
}
}
break;
}
return message;
}
private string GetApplicableCategoryListText( Coupon coupon )
{
string message = "<ul>";
foreach (Category category in coupon.GetApplicableCategories( StoreContext.Culture ))
{
if (!String.IsNullOrEmpty( category.Name ))
message += "<li>" + category.Name + "</li> ";
}
message += "</ul>";
return message;
}
private string GetDiscountTypeBuyXGetYText( Coupon coupon, bool isErrorMessage )
{
String message = "";
if (!isErrorMessage)
{
message = "Buy " + coupon.MinimumQuantity.ToString() + " item(s) full price and get ";
if (coupon.DiscountType == Coupon.DiscountTypeEnum.BuyXDiscountYPrice)
{
message += StoreContext.Currency.FormatPrice( coupon.DiscountAmount ) + " discount ";
message += "for " + coupon.PromotionQuantity.ToString() + " item(s). ";
}
else //Coupon.DiscountTypeEnum.BuyXDiscountYPercentage
{
if (ConvertUtilities.ToInt32( coupon.Percentage ) == 100)
{
message += coupon.PromotionQuantity + " item(s) free. ";
}
else // coupon.Percentage != 100
{
message += coupon.Percentage.ToString( "0.00" ) + "% discount ";
message += "for " + coupon.PromotionQuantity.ToString() + " item(s). ";
}
}
}
else
{
message += "To use this coupon, you need to buy at least ";
message += ConvertUtilities.ToString( coupon.MinimumQuantity + coupon.PromotionQuantity ) + " items per product.";
}
return message;
}
private void DisplayCouponAmount( Coupon coupon )
{
uxCouponAmountDiv.Visible = false;
if (coupon.DiscountType == Coupon.DiscountTypeEnum.Price)
{
uxCouponAmountDiv.Visible = true;
uxCouponAmountLabel.Text = StoreContext.Currency.FormatPrice( coupon.DiscountAmount );
}
if (coupon.DiscountType == Coupon.DiscountTypeEnum.Percentage)
{
uxCouponAmountDiv.Visible = true;
uxCouponAmountLabel.Text = coupon.Percentage.ToString() + "%";
}
if (coupon.DiscountType == Coupon.DiscountTypeEnum.BuyXDiscountYPrice)
{
uxCouponAmountDiv.Visible = true;
uxCouponAmountLabel.Text = GetDiscountTypeBuyXGetYText( coupon, false );
}
if (coupon.DiscountType == Coupon.DiscountTypeEnum.BuyXDiscountYPercentage)
{
uxCouponAmountDiv.Visible = true;
uxCouponAmountLabel.Text = GetDiscountTypeBuyXGetYText( coupon, false );
}
if (coupon.DiscountType == Coupon.DiscountTypeEnum.FreeShipping)
{
uxCouponAmountDiv.Visible = true;
uxCouponAmountLabel.Text = "Free Shipping Cost";
}
}
private void DisplayExpirationDetails( Coupon coupon )
{
uxCouponExpireDateDiv.Visible = false;
if (coupon.ExpirationType == Coupon.ExpirationTypeEnum.Date ||
coupon.ExpirationType == Coupon.ExpirationTypeEnum.Both)
{
uxCouponExpireDateDiv.Visible = true;
uxCouponExpireDateLabel.Text = String.Format( "{0:dd} {0:MMM} {0:yyyy}", coupon.ExpirationDate );
}
}
private void DisplayCouponApplicableItems( Coupon coupon, string productListType )
{
string message = String.Empty;
if (coupon.ProductFilter == Coupon.ProductFilterEnum.ByProductIDs)
{
message = GetApplicableProductListText( coupon, productListType );
if (!String.IsNullOrEmpty( message ))
{
if (productListType == "all_product")
{
uxAvailableItemHeaderLabel.Text = "[$ProductListHeader]";
}
else
{
uxAvailableItemHeaderLabel.Text = "[$ShoppingCartProductListHeader]";
}
uxAvailableItemHeaderListDiv.Visible = true;
uxAvailableItemLabel.Text = message;
uxAvailableItemListDiv.Visible = true;
}
}
else if (coupon.ProductFilter == Coupon.ProductFilterEnum.ByCategoryIDs)
{
uxAvailableItemHeaderLabel.Text = "[$CategoryListHeader]";
uxAvailableItemLabel.Text = GetApplicableCategoryListText( coupon );
uxAvailableItemListDiv.Visible = true;
uxAvailableItemHeaderListDiv.Visible = true;
}
}
private void DisplayPromotionWarning( Coupon coupon )
{
IList<ICartItem> cartItems = StoreContext.ShoppingCart.GetCartItems();
if (Coupon.DiscountTypeEnum.FreeShipping != coupon.DiscountType)
foreach (ICartItem cartItem in cartItems)
{
if (cartItem.IsPromotion)
{
uxPromotionWarningDiv.Visible = true;
break;
}
}
}
#endregion
#region Protected
protected void Page_Load( object sender, EventArgs e )
{
}
#endregion
#region Public Methods
public void HideAll()
{
HideAllControls();
}
public void DisplayCouponDetails( Coupon coupon, string productListType )
{
HideAllControls();
DisplayCouponAmount( coupon );
DisplayExpirationDetails( coupon );
DisplayCouponApplicableItems( coupon, productListType );
DisplayPromotionWarning( coupon );
}
public void DisplayCouponErrorMessage( Coupon coupon, CartItemGroup cartItemGroup )
{
HideAllControls();
string errorMessage = GetFormattedError( coupon, cartItemGroup );
if (!String.IsNullOrEmpty( errorMessage ))
DisplayError( errorMessage );
}
#endregion
}
| |
//
// Utilities.cs
//
// Author:
// Jb Evain ([email protected])
//
// Generated by /CodeGen/cecil-gen.rb do not edit
// Tue Mar 20 16:02:16 +0100 2007
//
// (C) 2005 Jb Evain
//
// 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 Mono.Cecil.Metadata {
using System;
using System.Collections;
using System.IO;
class Utilities {
Utilities ()
{
}
public static int ReadCompressedInteger (byte [] data, int pos, out int start)
{
int integer = 0;
start = pos;
if ((data [pos] & 0x80) == 0) {
integer = data [pos];
start++;
} else if ((data [pos] & 0x40) == 0) {
integer = (data [start] & ~0x80) << 8;
integer |= data [pos + 1];
start += 2;
} else {
integer = (data [start] & ~0xc0) << 24;
integer |= data [pos + 1] << 16;
integer |= data [pos + 2] << 8;
integer |= data [pos + 3];
start += 4;
}
return integer;
}
public static int WriteCompressedInteger (BinaryWriter writer, int value)
{
if (value < 0x80)
writer.Write ((byte) value);
else if (value < 0x4000) {
writer.Write ((byte) (0x80 | (value >> 8)));
writer.Write ((byte) (value & 0xff));
} else {
writer.Write ((byte) ((value >> 24) | 0xc0));
writer.Write ((byte) ((value >> 16) & 0xff));
writer.Write ((byte) ((value >> 8) & 0xff));
writer.Write ((byte) (value & 0xff));
}
return (int) writer.BaseStream.Position;
}
public static MetadataToken GetMetadataToken (CodedIndex cidx, uint data)
{
uint rid = 0;
switch (cidx) {
case CodedIndex.TypeDefOrRef :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.TypeRef, rid);
case 2 :
return new MetadataToken (TokenType.TypeSpec, rid);
default :
throw new MetadataFormatException("Non valid tag for TypeDefOrRef");
}
case CodedIndex.HasConstant :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.Field, rid);
case 1 :
return new MetadataToken (TokenType.Param, rid);
case 2 :
return new MetadataToken (TokenType.Property, rid);
default :
throw new MetadataFormatException("Non valid tag for HasConstant");
}
case CodedIndex.HasCustomAttribute :
rid = data >> 5;
switch (data & 31) {
case 0 :
return new MetadataToken (TokenType.Method, rid);
case 1 :
return new MetadataToken (TokenType.Field, rid);
case 2 :
return new MetadataToken (TokenType.TypeRef, rid);
case 3 :
return new MetadataToken (TokenType.TypeDef, rid);
case 4 :
return new MetadataToken (TokenType.Param, rid);
case 5 :
return new MetadataToken (TokenType.InterfaceImpl, rid);
case 6 :
return new MetadataToken (TokenType.MemberRef, rid);
case 7 :
return new MetadataToken (TokenType.Module, rid);
case 8 :
return new MetadataToken (TokenType.Permission, rid);
case 9 :
return new MetadataToken (TokenType.Property, rid);
case 10 :
return new MetadataToken (TokenType.Event, rid);
case 11 :
return new MetadataToken (TokenType.Signature, rid);
case 12 :
return new MetadataToken (TokenType.ModuleRef, rid);
case 13 :
return new MetadataToken (TokenType.TypeSpec, rid);
case 14 :
return new MetadataToken (TokenType.Assembly, rid);
case 15 :
return new MetadataToken (TokenType.AssemblyRef, rid);
case 16 :
return new MetadataToken (TokenType.File, rid);
case 17 :
return new MetadataToken (TokenType.ExportedType, rid);
case 18 :
return new MetadataToken (TokenType.ManifestResource, rid);
case 19 :
return new MetadataToken (TokenType.GenericParam, rid);
default :
throw new MetadataFormatException("Non valid tag for HasCustomAttribute");
}
case CodedIndex.HasFieldMarshal :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Field, rid);
case 1 :
return new MetadataToken (TokenType.Param, rid);
default :
throw new MetadataFormatException("Non valid tag for HasFieldMarshal");
}
case CodedIndex.HasDeclSecurity :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.Method, rid);
case 2 :
return new MetadataToken (TokenType.Assembly, rid);
default :
throw new MetadataFormatException("Non valid tag for HasDeclSecurity");
}
case CodedIndex.MemberRefParent :
rid = data >> 3;
switch (data & 7) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.TypeRef, rid);
case 2 :
return new MetadataToken (TokenType.ModuleRef, rid);
case 3 :
return new MetadataToken (TokenType.Method, rid);
case 4 :
return new MetadataToken (TokenType.TypeSpec, rid);
default :
throw new MetadataFormatException("Non valid tag for MemberRefParent");
}
case CodedIndex.HasSemantics :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Event, rid);
case 1 :
return new MetadataToken (TokenType.Property, rid);
default :
throw new MetadataFormatException("Non valid tag for HasSemantics");
}
case CodedIndex.MethodDefOrRef :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Method, rid);
case 1 :
return new MetadataToken (TokenType.MemberRef, rid);
default :
throw new MetadataFormatException("Non valid tag for MethodDefOrRef");
}
case CodedIndex.MemberForwarded :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Field, rid);
case 1 :
return new MetadataToken (TokenType.Method, rid);
default :
throw new MetadataFormatException("Non valid tag for MemberForwarded");
}
case CodedIndex.Implementation :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.File, rid);
case 1 :
return new MetadataToken (TokenType.AssemblyRef, rid);
case 2 :
return new MetadataToken (TokenType.ExportedType, rid);
default :
throw new MetadataFormatException("Non valid tag for Implementation");
}
case CodedIndex.CustomAttributeType :
rid = data >> 3;
switch (data & 7) {
case 2 :
return new MetadataToken (TokenType.Method, rid);
case 3 :
return new MetadataToken (TokenType.MemberRef, rid);
default :
throw new MetadataFormatException("Non valid tag for CustomAttributeType");
}
case CodedIndex.ResolutionScope :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.Module, rid);
case 1 :
return new MetadataToken (TokenType.ModuleRef, rid);
case 2 :
return new MetadataToken (TokenType.AssemblyRef, rid);
case 3 :
return new MetadataToken (TokenType.TypeRef, rid);
default :
throw new MetadataFormatException("Non valid tag for ResolutionScope");
}
case CodedIndex.TypeOrMethodDef :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.Method, rid);
default :
throw new MetadataFormatException("Non valid tag for TypeOrMethodDef");
}
default :
throw new MetadataFormatException ("Non valid CodedIndex");
}
}
public static uint CompressMetadataToken (CodedIndex cidx, MetadataToken token)
{
uint ret = 0;
if (token.RID == 0)
return ret;
switch (cidx) {
case CodedIndex.TypeDefOrRef :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.TypeRef :
return ret | 1;
case TokenType.TypeSpec :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for TypeDefOrRef");
}
case CodedIndex.HasConstant :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.Field :
return ret | 0;
case TokenType.Param :
return ret | 1;
case TokenType.Property :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for HasConstant");
}
case CodedIndex.HasCustomAttribute :
ret = token.RID << 5;
switch (token.TokenType) {
case TokenType.Method :
return ret | 0;
case TokenType.Field :
return ret | 1;
case TokenType.TypeRef :
return ret | 2;
case TokenType.TypeDef :
return ret | 3;
case TokenType.Param :
return ret | 4;
case TokenType.InterfaceImpl :
return ret | 5;
case TokenType.MemberRef :
return ret | 6;
case TokenType.Module :
return ret | 7;
case TokenType.Permission :
return ret | 8;
case TokenType.Property :
return ret | 9;
case TokenType.Event :
return ret | 10;
case TokenType.Signature :
return ret | 11;
case TokenType.ModuleRef :
return ret | 12;
case TokenType.TypeSpec :
return ret | 13;
case TokenType.Assembly :
return ret | 14;
case TokenType.AssemblyRef :
return ret | 15;
case TokenType.File :
return ret | 16;
case TokenType.ExportedType :
return ret | 17;
case TokenType.ManifestResource :
return ret | 18;
case TokenType.GenericParam :
return ret | 19;
default :
throw new MetadataFormatException("Non valid Token for HasCustomAttribute");
}
case CodedIndex.HasFieldMarshal :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Field :
return ret | 0;
case TokenType.Param :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for HasFieldMarshal");
}
case CodedIndex.HasDeclSecurity :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.Method :
return ret | 1;
case TokenType.Assembly :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for HasDeclSecurity");
}
case CodedIndex.MemberRefParent :
ret = token.RID << 3;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.TypeRef :
return ret | 1;
case TokenType.ModuleRef :
return ret | 2;
case TokenType.Method :
return ret | 3;
case TokenType.TypeSpec :
return ret | 4;
default :
throw new MetadataFormatException("Non valid Token for MemberRefParent");
}
case CodedIndex.HasSemantics :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Event :
return ret | 0;
case TokenType.Property :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for HasSemantics");
}
case CodedIndex.MethodDefOrRef :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Method :
return ret | 0;
case TokenType.MemberRef :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for MethodDefOrRef");
}
case CodedIndex.MemberForwarded :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Field :
return ret | 0;
case TokenType.Method :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for MemberForwarded");
}
case CodedIndex.Implementation :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.File :
return ret | 0;
case TokenType.AssemblyRef :
return ret | 1;
case TokenType.ExportedType :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for Implementation");
}
case CodedIndex.CustomAttributeType :
ret = token.RID << 3;
switch (token.TokenType) {
case TokenType.Method :
return ret | 2;
case TokenType.MemberRef :
return ret | 3;
default :
throw new MetadataFormatException("Non valid Token for CustomAttributeType");
}
case CodedIndex.ResolutionScope :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.Module :
return ret | 0;
case TokenType.ModuleRef :
return ret | 1;
case TokenType.AssemblyRef :
return ret | 2;
case TokenType.TypeRef :
return ret | 3;
default :
throw new MetadataFormatException("Non valid Token for ResolutionScope");
}
case CodedIndex.TypeOrMethodDef :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.Method :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for TypeOrMethodDef");
}
default :
throw new MetadataFormatException ("Non valid CodedIndex");
}
}
internal static Type GetCorrespondingTable (TokenType t)
{
switch (t) {
case TokenType.Assembly :
return typeof (AssemblyTable);
case TokenType.AssemblyRef :
return typeof (AssemblyRefTable);
case TokenType.CustomAttribute :
return typeof (CustomAttributeTable);
case TokenType.Event :
return typeof (EventTable);
case TokenType.ExportedType :
return typeof (ExportedTypeTable);
case TokenType.Field :
return typeof (FieldTable);
case TokenType.File :
return typeof (FileTable);
case TokenType.InterfaceImpl :
return typeof (InterfaceImplTable);
case TokenType.MemberRef :
return typeof (MemberRefTable);
case TokenType.Method :
return typeof (MethodTable);
case TokenType.Module :
return typeof (ModuleTable);
case TokenType.ModuleRef :
return typeof (ModuleRefTable);
case TokenType.Param :
return typeof (ParamTable);
case TokenType.Permission :
return typeof (DeclSecurityTable);
case TokenType.Property :
return typeof (PropertyTable);
case TokenType.Signature :
return typeof (StandAloneSigTable);
case TokenType.TypeDef :
return typeof (TypeDefTable);
case TokenType.TypeRef :
return typeof (TypeRefTable);
case TokenType.TypeSpec :
return typeof (TypeSpecTable);
default :
return null;
}
}
internal delegate int TableRowCounter (int rid);
internal static int GetCodedIndexSize (CodedIndex ci, TableRowCounter rowCounter, IDictionary codedIndexCache)
{
int bits = 0, max = 0;
if (codedIndexCache [ci] != null)
return (int) codedIndexCache [ci];
int res = 0;
int [] rids;
switch (ci) {
case CodedIndex.TypeDefOrRef :
bits = 2;
rids = new int [3];
rids [0] = TypeDefTable.RId;
rids [1] = TypeRefTable.RId;
rids [2] = TypeSpecTable.RId;
break;
case CodedIndex.HasConstant :
bits = 2;
rids = new int [3];
rids [0] = FieldTable.RId;
rids [1] = ParamTable.RId;
rids [2] = PropertyTable.RId;
break;
case CodedIndex.HasCustomAttribute :
bits = 5;
rids = new int [20];
rids [0] = MethodTable.RId;
rids [1] = FieldTable.RId;
rids [2] = TypeRefTable.RId;
rids [3] = TypeDefTable.RId;
rids [4] = ParamTable.RId;
rids [5] = InterfaceImplTable.RId;
rids [6] = MemberRefTable.RId;
rids [7] = ModuleTable.RId;
rids [8] = DeclSecurityTable.RId;
rids [9] = PropertyTable.RId;
rids [10] = EventTable.RId;
rids [11] = StandAloneSigTable.RId;
rids [12] = ModuleRefTable.RId;
rids [13] = TypeSpecTable.RId;
rids [14] = AssemblyTable.RId;
rids [15] = AssemblyRefTable.RId;
rids [16] = FileTable.RId;
rids [17] = ExportedTypeTable.RId;
rids [18] = ManifestResourceTable.RId;
rids [19] = GenericParamTable.RId;
break;
case CodedIndex.HasFieldMarshal :
bits = 1;
rids = new int [2];
rids [0] = FieldTable.RId;
rids [1] = ParamTable.RId;
break;
case CodedIndex.HasDeclSecurity :
bits = 2;
rids = new int [3];
rids [0] = TypeDefTable.RId;
rids [1] = MethodTable.RId;
rids [2] = AssemblyTable.RId;
break;
case CodedIndex.MemberRefParent :
bits = 3;
rids = new int [5];
rids [0] = TypeDefTable.RId;
rids [1] = TypeRefTable.RId;
rids [2] = ModuleRefTable.RId;
rids [3] = MethodTable.RId;
rids [4] = TypeSpecTable.RId;
break;
case CodedIndex.HasSemantics :
bits = 1;
rids = new int [2];
rids [0] = EventTable.RId;
rids [1] = PropertyTable.RId;
break;
case CodedIndex.MethodDefOrRef :
bits = 1;
rids = new int [2];
rids [0] = MethodTable.RId;
rids [1] = MemberRefTable.RId;
break;
case CodedIndex.MemberForwarded :
bits = 1;
rids = new int [2];
rids [0] = FieldTable.RId;
rids [1] = MethodTable.RId;
break;
case CodedIndex.Implementation :
bits = 2;
rids = new int [3];
rids [0] = FileTable.RId;
rids [1] = AssemblyRefTable.RId;
rids [2] = ExportedTypeTable.RId;
break;
case CodedIndex.CustomAttributeType :
bits = 3;
rids = new int [2];
rids [0] = MethodTable.RId;
rids [1] = MemberRefTable.RId;
break;
case CodedIndex.ResolutionScope :
bits = 2;
rids = new int [4];
rids [0] = ModuleTable.RId;
rids [1] = ModuleRefTable.RId;
rids [2] = AssemblyRefTable.RId;
rids [3] = TypeRefTable.RId;
break;
case CodedIndex.TypeOrMethodDef :
bits = 1;
rids = new int [2];
rids [0] = TypeDefTable.RId;
rids [1] = MethodTable.RId;
break;
default :
throw new MetadataFormatException ("Non valid CodedIndex");
}
for (int i = 0; i < rids.Length; i++) {
int rows = rowCounter (rids [i]);
if (rows > max) max = rows;
}
res = max < (1 << (16 - bits)) ? 2 : 4;
codedIndexCache [ci] = res;
return res;
}
}
}
| |
namespace OpenRiaServices.DomainServices.Tools.TextTemplate
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using OpenRiaServices.DomainServices;
using OpenRiaServices.DomainServices.Server;
using System.Text;
using OpenRiaServices.DomainServices.Tools;
using OpenRiaServices.DomainServices.Tools.TextTemplate.CSharpGenerators;
/// <summary>
/// Generator class to generate a domain service proxy using Text Templates.
/// </summary>
public abstract partial class ClientCodeGenerator : IDomainServiceClientCodeGenerator
{
private IEnumerable<DomainServiceDescription> _domainServiceDescriptions;
private ICodeGenerationHost _codeGenerationHost;
private ClientCodeGenerationOptions _options;
private HashSet<Type> _enumTypesToGenerate;
/// <summary>
/// Gets the generator object that generates entity classes on the client.
/// </summary>
protected abstract EntityGenerator EntityGenerator { get; }
/// <summary>
/// Gets the generator object that generates complex types on the client.
/// </summary>
protected abstract ComplexObjectGenerator ComplexObjectGenerator { get; }
/// <summary>
/// Gets the generator object that generates DomainContexts on the client.
/// </summary>
protected abstract DomainContextGenerator DomainContextGenerator { get; }
/// <summary>
/// Gets the generator object that generates the application wide WebContext class on the client.
/// </summary>
protected abstract WebContextGenerator WebContextGenerator { get; }
/// <summary>
/// Gets the generator object that generates enums.
/// </summary>
protected abstract EnumGenerator EnumGenerator { get; }
/// <summary>
/// Gets the code generation options.
/// </summary>
public ClientCodeGenerationOptions Options
{
get
{
return this._options;
}
}
/// <summary>
/// Gets the code generation host for this code generation instance.
/// </summary>
public ICodeGenerationHost CodeGenerationHost
{
get
{
return this._codeGenerationHost;
}
}
/// <summary>
/// Gets the list of all DomainServiceDescriptions.
/// </summary>
public IEnumerable<DomainServiceDescription> DomainServiceDescriptions
{
get
{
return this._domainServiceDescriptions;
}
}
/// <summary>
/// This method is part of the <see cref="IDomainServiceClientCodeGenerator" /> interface. The RIA Services Code Generation process uses this method as the entry point into the code generator.
/// </summary>
/// <param name="codeGenerationHost">The code generation host for this instance.</param>
/// <param name="domainServiceDescriptions">The list of all the DomainServiceDescription objects.</param>
/// <param name="options">The code generation objects.</param>
/// <returns>The generated code.</returns>
public string GenerateCode(ICodeGenerationHost codeGenerationHost, IEnumerable<DomainServiceDescription> domainServiceDescriptions, ClientCodeGenerationOptions options)
{
this._codeGenerationHost = codeGenerationHost;
this._domainServiceDescriptions = domainServiceDescriptions;
this._options = options;
this._enumTypesToGenerate = new HashSet<Type>();
if (this.EntityGenerator == null)
{
this.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture, TextTemplateResource.EntityGeneratorNotFound));
}
if (this.ComplexObjectGenerator == null)
{
this.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture, TextTemplateResource.ComplexObjectGeneratorNotFound));
}
if (this.DomainContextGenerator == null)
{
this.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture, TextTemplateResource.DomainContextGeneratorNotFound));
}
if (this.WebContextGenerator == null)
{
this.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture, TextTemplateResource.WebContextGeneratorNotFound));
}
if (this.EnumGenerator == null)
{
this.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture, TextTemplateResource.EnumGeneratorNotFound));
}
if (!this.CodeGenerationHost.HasLoggedErrors)
{
return this.GenerateCode();
}
return null;
}
/// <summary>
/// When overridden in the derived class generates code in specific to a language (C#, VB etc).
/// </summary>
/// <returns>The generated code.</returns>
protected abstract string GenerateCode();
internal void AddEnumTypeToGenerate(Type enumType)
{
if (this._enumTypesToGenerate != null)
{
if (!this._enumTypesToGenerate.Contains(enumType) && this.NeedToGenerateEnumType(enumType))
{
this._enumTypesToGenerate.Add(enumType);
}
}
}
internal void GenerateProxyClass()
{
List<Type> generatedEntities = new List<Type>();
List<Type> generatedComplexObjects = new List<Type>();
foreach (DomainServiceDescription dsd in this._domainServiceDescriptions.OrderBy(d => d.DomainServiceType.Name))
{
CodeMemberShareKind domainContextShareKind = this.GetDomainContextTypeShareKind(dsd);
if ((domainContextShareKind & CodeMemberShareKind.Shared) != 0)
{
continue;
}
this.Write(this.DomainContextGenerator.Generate(dsd, this));
this.GenerateEntitiesIfNotGenerated(dsd, generatedEntities);
this.GenerateComplexObjectsIfNotGenerated(dsd, generatedComplexObjects);
}
if (this.Options.IsApplicationContextGenerationEnabled)
{
this.Write(this.WebContextGenerator.Generate(this._domainServiceDescriptions, this));
}
this.Write(this.EnumGenerator.GenerateEnums(this._enumTypesToGenerate, this));
}
private void GenerateEntitiesIfNotGenerated(DomainServiceDescription dsd, List<Type> generatedEntities)
{
foreach (Type t in dsd.EntityTypes.OrderBy(e => e.Name))
{
if (generatedEntities.Contains(t))
{
continue;
}
CodeMemberShareKind typeShareKind = this.GetTypeShareKind(t);
if ((typeShareKind & CodeMemberShareKind.SharedByReference) != 0)
{
this.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture, "Type already shared", t));
continue;
}
generatedEntities.Add(t);
this.Write(this.EntityGenerator.Generate(t, this._domainServiceDescriptions, this));
}
}
private void GenerateComplexObjectsIfNotGenerated(DomainServiceDescription dsd, List<Type> generatedComplexObjects)
{
foreach (Type t in dsd.ComplexTypes.OrderBy(e => e.Name))
{
if (generatedComplexObjects.Contains(t))
{
continue;
}
CodeMemberShareKind typeShareKind = this.GetTypeShareKind(t);
if ((typeShareKind & CodeMemberShareKind.SharedByReference) != 0)
{
this.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture, "Type already shared", t));
continue;
}
generatedComplexObjects.Add(t);
this.Write(this.ComplexObjectGenerator.Generate(t, dsd, this));
}
}
private void PreprocessProxyTypes()
{
foreach (DomainServiceDescription dsd in this._domainServiceDescriptions)
{
// Check if the DomainService is nested
if (dsd.DomainServiceType.IsNested)
{
this.CodeGenerationHost.LogError(
string.Format(
CultureInfo.CurrentCulture,
Resource.ClientCodeGen_DomainService_CannotBeNested,
dsd.DomainServiceType));
}
// Register the DomainService type name
this.RegisterTypeName(dsd.DomainServiceType, dsd.DomainServiceType.Namespace);
// Register all associated Entity type names
foreach (Type entityType in dsd.EntityTypes)
{
this.RegisterTypeName(entityType, dsd.DomainServiceType.Namespace);
}
}
}
private void RegisterTypeName(Type type, string containingNamespace)
{
if (string.IsNullOrEmpty(type.Namespace))
{
this.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Namespace_Required, type));
return;
}
// Check if we're in conflict
// Here we register all the names of the types to be generated. We can check if we have conflicting names using this list.
if (!CodeGenUtilities.RegisterTypeName(type, containingNamespace))
{
// Aggressively check for potential conflicts across other DomainService entity types.
IEnumerable<Type> potentialConflicts =
// Entity types with namespace matches
this._domainServiceDescriptions
.SelectMany<DomainServiceDescription, Type>(d => d.EntityTypes)
.Where(entity => entity.Namespace == type.Namespace)
.Concat(
// DomainService types with namespace matches
this._domainServiceDescriptions
.Select(d => d.DomainServiceType)
.Where(dst => dst.Namespace == type.Namespace)).Distinct();
foreach (Type potentialConflict in potentialConflicts)
{
// Register potential conflicts so we qualify type names correctly
// later during codegen.
CodeGenUtilities.RegisterTypeName(potentialConflict, containingNamespace);
}
}
}
internal string ClientProjectName
{
get
{
return Path.GetFileNameWithoutExtension(this._options.ClientProjectPath);
}
}
internal CodeMemberShareKind GetDomainContextTypeShareKind(DomainServiceDescription domainServiceDescription)
{
Type domainServiceType = domainServiceDescription.DomainServiceType;
string domainContextTypeName = DomainContextGenerator.GetDomainContextTypeName(domainServiceDescription);
string fullTypeName = domainServiceType.Namespace + "." + domainContextTypeName;
CodeMemberShareKind shareKind = this._codeGenerationHost.GetTypeShareKind(fullTypeName);
return shareKind;
}
internal CodeMemberShareKind GetPropertyShareKind(Type type, string propertyName)
{
return this._codeGenerationHost.GetPropertyShareKind(type.AssemblyQualifiedName, propertyName);
}
internal CodeMemberShareKind GetMethodShareKind(MethodBase methodBase)
{
IEnumerable<string> parameterTypeNames = methodBase.GetParameters().Select<ParameterInfo, string>(p => p.ParameterType.AssemblyQualifiedName);
return this._codeGenerationHost.GetMethodShareKind(methodBase.DeclaringType.AssemblyQualifiedName, methodBase.Name, parameterTypeNames);
}
internal bool NeedToGenerateEnumType(Type enumType)
{
if (!this._enumTypesToGenerate.Contains(enumType))
{
if ((this.GetTypeShareKind(enumType) & CodeMemberShareKind.Shared) != 0)
{
return false;
}
}
return true;
}
internal bool CanExposeEnumType(Type enumType, out string errorMessage)
{
errorMessage = null;
if (!enumType.IsPublic || enumType.IsNested)
{
errorMessage = Resource.Enum_Type_Must_Be_Public;
return false;
}
// Determine whether it is visible to the client. If so,
// it is legal to expose without generating it.
if ((this.GetTypeShareKind(enumType) & CodeMemberShareKind.Shared) != 0)
{
return true;
}
// The enum is not shared (i.e. not visible to the client).
// We block attempts to generate anything from system assemblies
if (enumType.Assembly.IsSystemAssembly())
{
errorMessage = Resource.Enum_Type_Cannot_Gen_System;
return false;
}
return true;
}
internal CodeMemberShareKind GetTypeShareKind(Type type)
{
return this._codeGenerationHost.GetTypeShareKind(type.AssemblyQualifiedName);
}
}
}
| |
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 SE.DSP.Pop.Web.WebHost.Areas.HelpPage.ModelDescriptions;
using SE.DSP.Pop.Web.WebHost.Areas.HelpPage.Models;
namespace SE.DSP.Pop.Web.WebHost.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* Copyright (c) 2005, 2007 by L. Paul Chew.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, 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.Linq;
using System.Collections.Generic;
/**
* A 2D Delaunay Triangulation (DT) with incremental site insertion.
*
* This is not the fastest way to build a DT, but it's a reasonable way to build
* a DT incrementally and it makes a nice interactive display. There are several
* O(n log n) methods, but they require that the sites are all known initially.
*
* A Triangulation is a Set of Triangles. A Triangulation is unmodifiable as a
* Set; the only way to change it is to add sites (via delaunayPlace).
*
* @author Paul Chew
*
* Created July 2005. Derived from an earlier, messier version.
*
* Modified November 2007. Rewrote to use AbstractSet as parent class and to use
* the Graph class internally. Tried to make the DT algorithm clearer by
* explicitly creating a cavity. Added code needed to find a Voronoi cell.
*
*/
namespace BriLib.Delaunay
{
public class Triangulation
{
public IEnumerable<Triangle> Triangles { get { return triGraph.nodeSet(); } }
private Triangle mostRecent = null; // Most recently "active" triangle
private Graph<Triangle> triGraph; // Holds triangles for navigation
/**
* All sites must fall within the initial triangle.
* @param triangle the initial triangle
*/
public Triangulation(Triangle triangle)
{
triGraph = new Graph<Triangle>();
triGraph.add(triangle);
mostRecent = triangle;
}
public Triangulation()
{
triGraph = new Graph<Triangle>();
}
/* The following two methods are required by AbstractSet */
public int size()
{
return triGraph.nodeSet().Count;
}
public override string ToString()
{
return "Triangulation with " + size() + " triangles";
}
/**
* True iff triangle is a member of this triangulation.
* This method isn't required by AbstractSet, but it improves efficiency.
* @param triangle the object to check for membership
*/
public bool Contains(Object triangle)
{
return triGraph.nodeSet().Contains((Triangle)triangle);
}
/**
* Report neighbor opposite the given vertex of triangle.
* @param site a vertex of triangle
* @param triangle we want the neighbor of this triangle
* @return the neighbor opposite site in triangle; null if none
* @throws ArgumentException if site is not in this triangle
*/
public Triangle neighborOpposite(Pnt site, Triangle triangle)
{
if (!triangle.Contains(site))
throw new ArgumentException("Bad vertex; not in triangle");
foreach (var neighbor in triGraph.neighbors(triangle))
{
if (!neighbor.Contains(site)) return neighbor;
}
return null;
}
/**
* Return the set of triangles adjacent to triangle.
* @param triangle the triangle to check
* @return the neighbors of triangle
*/
public List<Triangle> neighbors(Triangle triangle)
{
return triGraph.neighbors(triangle);
}
/**
* Report triangles surrounding site in order (cw or ccw).
* @param site we want the surrounding triangles for this site
* @param triangle a "starting" triangle that has site as a vertex
* @return all triangles surrounding site in order (cw or ccw)
* @throws ArgumentException if site is not in triangle
*/
public List<Triangle> surroundingTriangles(Pnt site, Triangle triangle)
{
if (!triangle.Contains(site))
throw new ArgumentException("Site not in triangle");
List<Triangle> list = new List<Triangle>();
Triangle start = triangle;
Pnt guide = triangle.getVertexButNot(site); // Affects cw or ccw
while (true)
{
list.AddIfNotContains(triangle);
Triangle previous = triangle;
triangle = neighborOpposite(guide, triangle); // Next triangle
guide = previous.getVertexButNot(site, guide); // Update guide
if (triangle == start) break;
}
return list;
}
/**
* Locate the triangle with point inside it or on its boundary.
* @param point the point to locate
* @return the triangle that holds point; null if no such triangle
*/
public Triangle locate(Pnt point)
{
Triangle triangle = mostRecent;
if (!this.Contains(triangle)) triangle = null;
// Try a directed walk (this works fine in 2D, but can fail in 3D)
List<Triangle> visited = new List<Triangle>();
while (triangle != null)
{
if (visited.Contains(triangle))
{ // This should never happen
//System.out.println("Warning: Caught in a locate loop");
break;
}
visited.AddIfNotContains(triangle);
// Corner opposite point
Pnt corner = point.isOutside(triangle.ToArray());
if (corner == null) return triangle;
triangle = this.neighborOpposite(corner, triangle);
}
// No luck; try brute force
//System.out.println("Warning: Checking all triangles for " + point);
foreach (var tri in Triangles)
{
if (point.isOutside(tri.ToArray()) == null) return tri;
}
// No such triangle
//System.out.println("Warning: No triangle holds " + point);
return null;
}
/**
* Place a new site into the DT.
* Nothing happens if the site matches an existing DT vertex.
* @param site the new Pnt
* @throws ArgumentException if site does not lie in any triangle
*/
public void delaunayPlace(Pnt site)
{
// Uses straightforward scheme rather than best asymptotic time
// Locate containing triangle
Triangle triangle = locate(site);
// Give up if no containing triangle or if site is already in DT
if (triangle == null)
throw new ArgumentException("No containing triangle");
if (triangle.Contains(site)) return;
// Determine the cavity and update the triangulation
List<Triangle> cavity = getCavity(site, triangle);
mostRecent = update(site, cavity);
}
/**
* Determine the cavity caused by site.
* @param site the site causing the cavity
* @param triangle the triangle containing site
* @return set of all triangles that have site in their circumcircle
*/
private List<Triangle> getCavity(Pnt site, Triangle triangle)
{
List<Triangle> encroached = new List<Triangle>();
Queue<Triangle> toBeChecked = new Queue<Triangle>();
List<Triangle> marked = new List<Triangle>();
toBeChecked.Enqueue(triangle);
marked.AddIfNotContains(triangle);
while (toBeChecked.Count != 0)
{
triangle = toBeChecked.Dequeue();
if (site.vsCircumcircle(triangle.ToArray()) == 1)
continue; // Site outside triangle => triangle not in cavity
encroached.AddIfNotContains(triangle);
// Check the neighbors
foreach (var neighbor in triGraph.neighbors(triangle))
{
if (marked.Contains(neighbor)) continue;
marked.AddIfNotContains(neighbor);
toBeChecked.Enqueue(neighbor);
}
}
return encroached;
}
/**
* Update the triangulation by removing the cavity triangles and then
* filling the cavity with new triangles.
* @param site the site that created the cavity
* @param cavity the triangles with site in their circumcircle
* @return one of the new triangles
*/
private Triangle update(Pnt site, List<Triangle> cavity)
{
List<List<Pnt>> boundary = new List<List<Pnt>>();
List<Triangle> theTriangles = new List<Triangle>();
// Find boundary facets and adjacent triangles
foreach (var triangle in cavity)
{
var neighborTriangles = neighbors(triangle);
theTriangles.AddUniques(neighborTriangles);
foreach (var vertex in triangle)
{
List<Pnt> facet = triangle.facetOpposite(vertex);
int removeIndex = -1;
for (int i = 0; i < boundary.Count; i++)
{
if (boundary[i].ListsEqual(facet)) removeIndex = i;
}
if (removeIndex != -1) boundary.RemoveAt(removeIndex);
else boundary.Add(facet);
}
}
theTriangles.RemoveAll(cavity); // Adj triangles only
// Remove the cavity triangles from the triangulation
foreach (var triangle in cavity) triGraph.remove(triangle);
// Build each new triangle and add it to the triangulation
List<Triangle> newTriangles = new List<Triangle>();
foreach (var vertices in boundary)
{
vertices.AddIfNotContains(site);
Triangle tri = new Triangle(vertices);
triGraph.add(tri);
newTriangles.AddIfNotContains(tri);
}
// Update the graph links for each new triangle
theTriangles.AddAll(newTriangles); // Adj triangle + new triangles
foreach (var triangle in newTriangles)
foreach (var other in theTriangles)
if (triangle.isNeighbor(other))
triGraph.add(triangle, other);
// Return one of the new triangles
var enumerator = newTriangles.GetEnumerator();
enumerator.MoveNext();
return enumerator.Current;
}
public void AddExistingTriangles(List<Triangle> triangles)
{
foreach (var triangle in triangles) triGraph.add(triangle);
foreach (var triangle in triangles)
{
foreach (var other in triangles)
{
if (triangle.isNeighbor(other)) triGraph.add(triangle, other);
}
mostRecent = triangle;
}
}
/**
* Main program; used for testing.
*/
//public static void main (String[] args) {
// Triangle tri =
// new Triangle(new Pnt(-10,10), new Pnt(10,10), new Pnt(0,-10));
// System.out.println("Triangle created: " + tri);
// Triangulation dt = new Triangulation(tri);
// System.out.println("DelaunayTriangulation created: " + dt);
// dt.delaunayPlace(new Pnt(0,0));
// dt.delaunayPlace(new Pnt(1,0));
// dt.delaunayPlace(new Pnt(0,1));
// System.out.println("After adding 3 points, we have a " + dt);
// Triangle.moreInfo = true;
// System.out.println("Triangles: " + dt.triGraph.nodeSet());
//}
}
}
| |
/*
* 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;
namespace Apache.Geode.Client.Tests
{
using Apache.Geode.Client;
public class Position
: IGeodeSerializable
{
#region Private members
private long m_avg20DaysVol;
private string m_bondRating;
private double m_convRatio;
private string m_country;
private double m_delta;
private long m_industry;
private long m_issuer;
private double m_mktValue;
private double m_qty;
private string m_secId;
private string m_secLinks;
private string m_secType;
private int m_sharesOutstanding;
private string m_underlyer;
private long m_volatility;
private int m_pid;
private static int m_count = 0;
#endregion
#region Private methods
private void Init()
{
m_avg20DaysVol = 0;
m_bondRating = null;
m_convRatio = 0.0;
m_country = null;
m_delta = 0.0;
m_industry = 0;
m_issuer = 0;
m_mktValue = 0.0;
m_qty = 0.0;
m_secId = null;
m_secLinks = null;
m_secType = null;
m_sharesOutstanding = 0;
m_underlyer = null;
m_volatility = 0;
m_pid = 0;
}
private UInt64 GetObjectSize(IGeodeSerializable obj)
{
return (obj == null ? 0 : obj.ObjectSize);
}
#endregion
#region Public accessors
public string SecId
{
get
{
return m_secId;
}
}
public int Id
{
get
{
return m_pid;
}
}
public int SharesOutstanding
{
get
{
return m_sharesOutstanding;
}
}
public static int Count
{
get
{
return m_count;
}
set
{
m_count = value;
}
}
public override string ToString()
{
return "Position [secId=" + m_secId + " sharesOutstanding=" + m_sharesOutstanding + " type=" + m_secType + " id=" + m_pid + "]";
}
#endregion
#region Constructors
public Position()
{
Init();
}
//This ctor is for a data validation test
public Position(Int32 iForExactVal)
{
Init();
char[] id = new char[iForExactVal + 1];
for (int i = 0; i <= iForExactVal; i++)
{
id[i] = 'a';
}
m_secId = id.ToString();
m_qty = iForExactVal % 2 == 0 ? 1000 : 100;
m_mktValue = m_qty * 2;
m_sharesOutstanding = iForExactVal;
m_secType = "a";
m_pid = iForExactVal;
}
public Position(string id, int shares)
{
Init();
m_secId = id;
m_qty = shares * (m_count % 2 == 0 ? 10.0 : 100.0);
m_mktValue = m_qty * 1.2345998;
m_sharesOutstanding = shares;
m_secType = "a";
m_pid = m_count++;
}
#endregion
#region IGeodeSerializable Members
public void FromData(DataInput input)
{
m_avg20DaysVol = input.ReadInt64();
m_bondRating = input.ReadUTF();
m_convRatio = input.ReadDouble();
m_country = input.ReadUTF();
m_delta = input.ReadDouble();
m_industry = input.ReadInt64();
m_issuer = input.ReadInt64();
m_mktValue = input.ReadDouble();
m_qty = input.ReadDouble();
m_secId = input.ReadUTF();
m_secLinks = input.ReadUTF();
m_secType = input.ReadUTF();
m_sharesOutstanding = input.ReadInt32();
m_underlyer = input.ReadUTF();
m_volatility = input.ReadInt64();
m_pid = input.ReadInt32();
}
public void ToData(DataOutput output)
{
output.WriteInt64(m_avg20DaysVol);
output.WriteUTF(m_bondRating);
output.WriteDouble(m_convRatio);
output.WriteUTF(m_country);
output.WriteDouble(m_delta);
output.WriteInt64(m_industry);
output.WriteInt64(m_issuer);
output.WriteDouble(m_mktValue);
output.WriteDouble(m_qty);
output.WriteUTF(m_secId);
output.WriteUTF(m_secLinks);
output.WriteUTF(m_secType);
output.WriteInt32(m_sharesOutstanding);
output.WriteUTF(m_underlyer);
output.WriteInt64(m_volatility);
output.WriteInt32(m_pid);
}
public UInt64 ObjectSize
{
get
{
UInt64 objectSize = 0;
objectSize += (UInt64)sizeof(long);
objectSize += (UInt64) (m_bondRating.Length * sizeof(char));
objectSize += (UInt64)sizeof(double);
objectSize += (UInt64)(m_country.Length * sizeof(char));
objectSize += (UInt64)sizeof(double);
objectSize += (UInt64)sizeof(Int64);
objectSize += (UInt64)sizeof(Int64);
objectSize += (UInt64)sizeof(double);
objectSize += (UInt64)sizeof(double);
objectSize += (UInt64)(m_secId.Length * sizeof(char));
objectSize += (UInt64)(m_secLinks.Length * sizeof(char));
objectSize += (UInt64)(m_secType == null ? 0 : sizeof(char) * m_secType.Length);
objectSize += (UInt64)sizeof(Int32);
objectSize += (UInt64)(m_underlyer.Length * sizeof(char));
objectSize += (UInt64)sizeof(Int64);
objectSize += (UInt64)sizeof(Int32);
return objectSize;
}
}
public UInt32 ClassId
{
get
{
return 0x07;
}
}
#endregion
public static IGeodeSerializable CreateDeserializable()
{
return new Position();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Remoting;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation.Diagnostics;
using System.Collections;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Enter-PSSession cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.Enter, "PSSession", DefaultParameterSetName = "ComputerName",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135210", RemotingCapability = RemotingCapability.OwnedByCommand)]
public class EnterPSSessionCommand : PSRemotingBaseCmdlet
{
#region Strings
private const string InstanceIdParameterSet = "InstanceId";
private const string IdParameterSet = "Id";
private const string NameParameterSet = "Name";
#endregion
#region Members
/// <summary>
/// Disable ThrottleLimit parameter inherited from base class.
/// </summary>
public new int ThrottleLimit { set { } get { return 0; } }
private ObjectStream _stream;
private RemoteRunspace _tempRunspace;
#endregion
#region Parameters
#region SSH Parameter Set
/// <summary>
/// Host name for an SSH remote connection.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateNotNullOrEmpty()]
public new string HostName { get; set; }
#endregion
/// <summary>
/// Computer name parameter.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true, ParameterSetName = ComputerNameParameterSet)]
[Alias("Cn")]
[ValidateNotNullOrEmpty]
public new string ComputerName { get; set; }
/// <summary>
/// Runspace parameter.
/// </summary>
[Parameter(Position = 0, ValueFromPipelineByPropertyName = true,
ValueFromPipeline = true, ParameterSetName = SessionParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")]
public new PSSession Session { get; set; }
/// <summary>
/// ConnectionUri parameter.
/// </summary>
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true,
ParameterSetName = UriParameterSet)]
[ValidateNotNullOrEmpty]
[Alias("URI", "CU")]
public new Uri ConnectionUri { get; set; }
/// <summary>
/// RemoteRunspaceId of the remote runspace info object.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InstanceIdParameterSet)]
[ValidateNotNull]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")]
public Guid InstanceId { get; set; }
/// <summary>
/// SessionId of the remote runspace info object.
/// </summary>
[Parameter(Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = IdParameterSet)]
[ValidateNotNull]
public int Id { get; set; }
/// <summary>
/// Name of the remote runspace info object.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NameParameterSet)]
public string Name { get; set; }
/// <summary>
/// When set and in loopback scenario (localhost) this enables creation of WSMan
/// host process with the user interactive token, allowing PowerShell script network access,
/// i.e., allows going off box. When this property is true and a PSSession is disconnected,
/// reconnection is allowed only if reconnecting from a PowerShell session on the same box.
/// </summary>
[Parameter(ParameterSetName = ComputerNameParameterSet)]
[Parameter(ParameterSetName = UriParameterSet)]
public SwitchParameter EnableNetworkAccess { get; set; }
/// <summary>
/// Virtual machine ID.
/// </summary>
[ValidateNotNullOrEmpty]
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true, ParameterSetName = VMIdParameterSet)]
[Alias("VMGuid")]
public new Guid VMId { get; set; }
/// <summary>
/// Virtual machine name.
/// </summary>
[ValidateNotNullOrEmpty]
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true, ParameterSetName = VMNameParameterSet)]
public new string VMName { get; set; }
/// <summary>
/// Specifies the credentials of the user to impersonate in the
/// virtual machine. If this parameter is not specified then the
/// credentials of the current user process will be assumed.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true,
ParameterSetName = VMIdParameterSet)]
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true,
ParameterSetName = VMNameParameterSet)]
[Credential()]
public override PSCredential Credential
{
get { return base.Credential; }
set { base.Credential = value; }
}
/// <summary>
/// The Id of the target container.
/// </summary>
[ValidateNotNullOrEmpty]
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true, ParameterSetName = ContainerIdParameterSet)]
public new string ContainerId { get; set; }
/// <summary>
/// For WSMan sessions:
/// If this parameter is not specified then the value specified in
/// the environment variable DEFAULTREMOTESHELLNAME will be used. If
/// this is not set as well, then Microsoft.PowerShell is used.
///
/// For VM/Container sessions:
/// If this parameter is not specified then no configuration is used.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.UriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.VMNameParameterSet)]
public string ConfigurationName { get; set; }
#region Suppress PSRemotingBaseCmdlet SSH hash parameter set
/// <summary>
/// Suppress SSHConnection parameter set.
/// </summary>
public override Hashtable[] SSHConnection
{
get { return null; }
}
#endregion
#endregion
#region Overrides
/// <summary>
/// Resolves shellname and appname.
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
if (string.IsNullOrEmpty(ConfigurationName))
{
if ((ParameterSetName == EnterPSSessionCommand.ComputerNameParameterSet) ||
(ParameterSetName == EnterPSSessionCommand.UriParameterSet))
{
// set to default value for WSMan session
ConfigurationName = ResolveShell(null);
}
else
{
// convert null to string.Empty for VM/Container session
ConfigurationName = string.Empty;
}
}
}
/// <summary>
/// Process record.
/// </summary>
protected override void ProcessRecord()
{
// Push the remote runspace on the local host.
IHostSupportsInteractiveSession host = this.Host as IHostSupportsInteractiveSession;
if (host == null)
{
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)),
PSRemotingErrorId.HostDoesNotSupportPushRunspace.ToString(),
ErrorCategory.InvalidArgument,
null));
return;
}
// Check if current host is remote host. Enter-PSSession on remote host is not
// currently supported.
if (!IsParameterSetForVM() &&
!IsParameterSetForContainer() &&
!IsParameterSetForVMContainerSession() &&
this.Context != null &&
this.Context.EngineHostInterface != null &&
this.Context.EngineHostInterface.ExternalHost != null &&
this.Context.EngineHostInterface.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost)
{
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.RemoteHostDoesNotSupportPushRunspace)),
PSRemotingErrorId.RemoteHostDoesNotSupportPushRunspace.ToString(),
ErrorCategory.InvalidArgument,
null));
return;
}
// for the console host and Graphical PowerShell host
// we want to skip pushing into the the runspace if
// the host is in a nested prompt
System.Management.Automation.Internal.Host.InternalHost chost =
this.Host as System.Management.Automation.Internal.Host.InternalHost;
if (!IsParameterSetForVM() &&
!IsParameterSetForContainer() &&
!IsParameterSetForVMContainerSession() &&
chost != null && chost.HostInNestedPrompt())
{
ThrowTerminatingError(new ErrorRecord(
new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HostInNestedPrompt)),
"HostInNestedPrompt", ErrorCategory.InvalidOperation, chost));
}
/*Microsoft.Windows.PowerShell.Gui.Internal.GPSHost ghost = this.Host as Microsoft.Windows.PowerShell.Gui.Internal.GPSHost;
if (ghost != null && ghost.HostInNestedPrompt())
{
ThrowTerminatingError(new ErrorRecord(
new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.HostInNestedPrompt)),
"HostInNestedPrompt", ErrorCategory.InvalidOperation, wpshost));
}*/
// Get the remote runspace.
RemoteRunspace remoteRunspace = null;
switch (ParameterSetName)
{
case ComputerNameParameterSet:
remoteRunspace = CreateRunspaceWhenComputerNameParameterSpecified();
break;
case UriParameterSet:
remoteRunspace = CreateRunspaceWhenUriParameterSpecified();
break;
case SessionParameterSet:
remoteRunspace = (RemoteRunspace)Session.Runspace;
break;
case InstanceIdParameterSet:
remoteRunspace = GetRunspaceMatchingRunspaceId(this.InstanceId);
break;
case IdParameterSet:
remoteRunspace = GetRunspaceMatchingSessionId(this.Id);
break;
case NameParameterSet:
remoteRunspace = GetRunspaceMatchingName(this.Name);
break;
case VMIdParameterSet:
case VMNameParameterSet:
remoteRunspace = GetRunspaceForVMSession();
break;
case ContainerIdParameterSet:
remoteRunspace = GetRunspaceForContainerSession();
break;
case SSHHostParameterSet:
remoteRunspace = GetRunspaceForSSHSession();
break;
}
// If runspace is null then the error record has already been written and we can exit.
if (remoteRunspace == null) { return; }
// If the runspace is in a disconnected state try to connect.
bool runspaceConnected = false;
if (remoteRunspace.RunspaceStateInfo.State == RunspaceState.Disconnected)
{
if (!remoteRunspace.CanConnect)
{
string message = StringUtil.Format(RemotingErrorIdStrings.SessionNotAvailableForConnection);
WriteError(
new ErrorRecord(
new RuntimeException(message), "EnterPSSessionCannotConnectDisconnectedSession",
ErrorCategory.InvalidOperation, remoteRunspace));
return;
}
// Connect the runspace.
Exception ex = null;
try
{
remoteRunspace.Connect();
runspaceConnected = true;
}
catch (System.Management.Automation.Remoting.PSRemotingTransportException e)
{
ex = e;
}
catch (PSInvalidOperationException e)
{
ex = e;
}
catch (InvalidRunspacePoolStateException e)
{
ex = e;
}
if (ex != null)
{
string message = StringUtil.Format(RemotingErrorIdStrings.SessionConnectFailed);
WriteError(
new ErrorRecord(
new RuntimeException(message, ex), "EnterPSSessionConnectSessionFailed",
ErrorCategory.InvalidOperation, remoteRunspace));
return;
}
}
// Verify that the runspace is open.
if (remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened)
{
if (ParameterSetName == SessionParameterSet)
{
string sessionName = (Session != null) ? Session.Name : string.Empty;
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.EnterPSSessionBrokenSession,
sessionName, remoteRunspace.ConnectionInfo.ComputerName, remoteRunspace.InstanceId)),
PSRemotingErrorId.PushedRunspaceMustBeOpen.ToString(),
ErrorCategory.InvalidArgument,
null));
}
else
{
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.PushedRunspaceMustBeOpen)),
PSRemotingErrorId.PushedRunspaceMustBeOpen.ToString(),
ErrorCategory.InvalidArgument,
null));
}
return;
}
Debugger debugger = null;
try
{
if (host.Runspace != null)
{
debugger = host.Runspace.Debugger;
}
}
catch (PSNotImplementedException) { }
bool supportRunningCommand = ((debugger != null) && ((debugger.DebugMode & DebugModes.RemoteScript) == DebugModes.RemoteScript));
if (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available)
{
// Session has running command.
if (!supportRunningCommand)
{
// Host does not support remote debug and cannot connect to running command.
if (runspaceConnected)
{
// If we succeeded connecting the session (runspace) but it is already running a command,
// emit an error for this case because since it is disconnected this session object will
// never complete and the user must use *reconstruct* scenario to retrieve data.
string message = StringUtil.Format(RemotingErrorIdStrings.EnterPSSessionDisconnected,
remoteRunspace.PSSessionName);
WriteError(
new ErrorRecord(
new RuntimeException(message), "EnterPSSessionConnectSessionNotAvailable",
ErrorCategory.InvalidOperation, Session));
// Leave session in original disconnected state.
remoteRunspace.DisconnectAsync();
return;
}
else
{
// If the remote runspace is currently not available then let user know that this command
// will not complete until it becomes available.
WriteWarning(GetMessage(RunspaceStrings.RunspaceNotReady));
}
}
else
{
// Running commands supported.
// Warn user that they are entering a session that is running a command and output may
// be going to a job object.
Job job = FindJobForRunspace(remoteRunspace.InstanceId);
string msg;
if (job != null)
{
msg = StringUtil.Format(
RunspaceStrings.RunningCmdWithJob,
(!string.IsNullOrEmpty(job.Name)) ? job.Name : string.Empty);
}
else
{
if (remoteRunspace.RunspaceAvailability == RunspaceAvailability.RemoteDebug)
{
msg = StringUtil.Format(
RunspaceStrings.RunningCmdDebugStop);
}
else
{
msg = StringUtil.Format(
RunspaceStrings.RunningCmdWithoutJob);
}
}
WriteWarning(msg);
}
}
// Make sure any PSSession object passed in is saved in the local runspace repository.
if (Session != null)
{
this.RunspaceRepository.AddOrReplace(Session);
}
// prepare runspace for prompt
SetRunspacePrompt(remoteRunspace);
try
{
host.PushRunspace(remoteRunspace);
}
catch (Exception)
{
// A third-party host can throw any exception here..we should
// clean the runspace created in this case.
if ((remoteRunspace != null) && (remoteRunspace.ShouldCloseOnPop))
{
remoteRunspace.Close();
}
// rethrow the exception after cleanup.
throw;
}
}
/// <summary>
/// This method will until the runspace is opened and warnings if any
/// are reported.
/// </summary>
protected override void EndProcessing()
{
if (_stream != null)
{
while (true)
{
// Keep reading objects until end of stream is encountered
_stream.ObjectReader.WaitHandle.WaitOne();
if (!_stream.ObjectReader.EndOfPipeline)
{
object streamObject = _stream.ObjectReader.Read();
WriteStreamObject((Action<Cmdlet>)streamObject);
}
else
{
break;
}
}
}
}
/// <summary>
/// </summary>
protected override void StopProcessing()
{
var remoteRunspace = _tempRunspace;
if (remoteRunspace != null)
{
try
{
remoteRunspace.CloseAsync();
}
catch (InvalidRunspaceStateException) { }
return;
}
IHostSupportsInteractiveSession host = this.Host as IHostSupportsInteractiveSession;
if (host == null)
{
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)),
PSRemotingErrorId.HostDoesNotSupportPushRunspace.ToString(),
ErrorCategory.InvalidArgument,
null));
return;
}
host.PopRunspace();
}
#endregion
#region Private Methods
/// <summary>
/// Create temporary remote runspace.
/// </summary>
private RemoteRunspace CreateTemporaryRemoteRunspace(PSHost host, WSManConnectionInfo connectionInfo)
{
// Create and open the runspace.
int rsId;
string rsName = PSSession.GenerateRunspaceName(out rsId);
RemoteRunspace remoteRunspace = new RemoteRunspace(
Utils.GetTypeTableFromExecutionContextTLS(),
connectionInfo,
host,
this.SessionOption.ApplicationArguments,
rsName,
rsId);
Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null");
remoteRunspace.URIRedirectionReported += HandleURIDirectionReported;
_stream = new ObjectStream();
try
{
remoteRunspace.Open();
// Mark this temporary runspace so that it closes on pop.
remoteRunspace.ShouldCloseOnPop = true;
}
finally
{
// unregister uri redirection handler
remoteRunspace.URIRedirectionReported -= HandleURIDirectionReported;
// close the internal object stream after runspace is opened
// Runspace.Open() might throw exceptions..this will make sure
// the stream is always closed.
_stream.ObjectWriter.Close();
// make sure we dispose the temporary runspace if something bad happens
if (remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened)
{
remoteRunspace.Dispose();
remoteRunspace = null;
}
}
return remoteRunspace;
}
/// <summary>
/// Write error create remote runspace failed.
/// </summary>
private void WriteErrorCreateRemoteRunspaceFailed(Exception exception, object argument)
{
// set the transport message in the error detail so that
// the user can directly get to see the message without
// having to mine through the error record details
PSRemotingTransportException transException =
exception as PSRemotingTransportException;
string errorDetails = null;
if ((transException != null) &&
(transException.ErrorCode ==
System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED))
{
// Handling a special case for redirection..we should talk about
// AllowRedirection parameter and WSManMaxRedirectionCount preference
// variables
string message = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.URIRedirectionReported,
transException.Message,
"MaximumConnectionRedirectionCount",
Microsoft.PowerShell.Commands.PSRemotingBaseCmdlet.DEFAULT_SESSION_OPTION,
"AllowRedirection");
errorDetails = message;
}
ErrorRecord errorRecord = new ErrorRecord(exception, argument,
"CreateRemoteRunspaceFailed",
ErrorCategory.InvalidArgument,
null, null, null, null, null, errorDetails, null);
WriteError(errorRecord);
}
/// <summary>
/// Write invalid argument error.
/// </summary>
private void WriteInvalidArgumentError(PSRemotingErrorId errorId, string resourceString, object errorArgument)
{
string message = GetMessage(resourceString, errorArgument);
WriteError(new ErrorRecord(new ArgumentException(message), errorId.ToString(),
ErrorCategory.InvalidArgument, errorArgument));
}
/// <summary>
/// When the client remote session reports a URI redirection, this method will report the
/// message to the user as a Warning using Host method calls.
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
private void HandleURIDirectionReported(object sender, RemoteDataEventArgs<Uri> eventArgs)
{
string message = StringUtil.Format(RemotingErrorIdStrings.URIRedirectWarningToHost, eventArgs.Data.OriginalString);
Action<Cmdlet> streamObject = delegate (Cmdlet cmdlet)
{
cmdlet.WriteWarning(message);
};
_stream.Write(streamObject);
}
/// <summary>
/// Create runspace when computer name parameter specified.
/// </summary>
private RemoteRunspace CreateRunspaceWhenComputerNameParameterSpecified()
{
RemoteRunspace remoteRunspace = null;
string resolvedComputerName = ResolveComputerName(ComputerName);
try
{
WSManConnectionInfo connectionInfo = null;
connectionInfo = new WSManConnectionInfo();
string scheme = UseSSL.IsPresent ? WSManConnectionInfo.HttpsScheme : WSManConnectionInfo.HttpScheme;
connectionInfo.ComputerName = resolvedComputerName;
connectionInfo.Port = Port;
connectionInfo.AppName = ApplicationName;
connectionInfo.ShellUri = ConfigurationName;
connectionInfo.Scheme = scheme;
if (CertificateThumbprint != null)
{
connectionInfo.CertificateThumbprint = CertificateThumbprint;
}
else
{
connectionInfo.Credential = Credential;
}
connectionInfo.AuthenticationMechanism = Authentication;
UpdateConnectionInfo(connectionInfo);
connectionInfo.EnableNetworkAccess = EnableNetworkAccess;
remoteRunspace = CreateTemporaryRemoteRunspace(this.Host, connectionInfo);
}
catch (InvalidOperationException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, resolvedComputerName);
}
catch (ArgumentException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, resolvedComputerName);
}
catch (PSRemotingTransportException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, resolvedComputerName);
}
return remoteRunspace;
}
/// <summary>
/// Create runspace when uri parameter specified.
/// </summary>
private RemoteRunspace CreateRunspaceWhenUriParameterSpecified()
{
RemoteRunspace remoteRunspace = null;
try
{
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ConnectionUri = ConnectionUri;
connectionInfo.ShellUri = ConfigurationName;
if (CertificateThumbprint != null)
{
connectionInfo.CertificateThumbprint = CertificateThumbprint;
}
else
{
connectionInfo.Credential = Credential;
}
connectionInfo.AuthenticationMechanism = Authentication;
UpdateConnectionInfo(connectionInfo);
connectionInfo.EnableNetworkAccess = EnableNetworkAccess;
remoteRunspace = CreateTemporaryRemoteRunspace(this.Host, connectionInfo);
}
catch (UriFormatException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri);
}
catch (InvalidOperationException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri);
}
catch (ArgumentException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri);
}
catch (PSRemotingTransportException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri);
}
catch (NotSupportedException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri);
}
return remoteRunspace;
}
/// <summary>
/// Get runspace matching condition.
/// </summary>
private RemoteRunspace GetRunspaceMatchingCondition(
Predicate<PSSession> condition,
PSRemotingErrorId tooFew,
PSRemotingErrorId tooMany,
string tooFewResourceString,
string tooManyResourceString,
object errorArgument)
{
// Find matches.
List<PSSession> matches = this.RunspaceRepository.Runspaces.FindAll(condition);
// Validate.
RemoteRunspace remoteRunspace = null;
if (matches.Count == 0)
{
WriteInvalidArgumentError(tooFew, tooFewResourceString, errorArgument);
}
else if (matches.Count > 1)
{
WriteInvalidArgumentError(tooMany, tooManyResourceString, errorArgument);
}
else
{
remoteRunspace = (RemoteRunspace)matches[0].Runspace;
Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null");
}
return remoteRunspace;
}
/// <summary>
/// Get runspace matching runspace id.
/// </summary>
private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId)
{
Predicate<PSSession> condition = delegate (PSSession info)
{
return info.InstanceId == remoteRunspaceId;
};
PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId;
PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId;
string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId;
string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId;
return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, remoteRunspaceId);
}
/// <summary>
/// Get runspace matching session id.
/// </summary>
private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId)
{
Predicate<PSSession> condition = delegate (PSSession info)
{
return info.Id == sessionId;
};
PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId;
PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId;
string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId;
string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId;
return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, sessionId);
}
/// <summary>
/// Get runspace matching name.
/// </summary>
private RemoteRunspace GetRunspaceMatchingName(string name)
{
Predicate<PSSession> condition = delegate (PSSession info)
{
// doing case-insensitive match for session name
return info.Name.Equals(name, StringComparison.OrdinalIgnoreCase);
};
PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName;
PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName;
string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName;
string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedName;
return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, name);
}
private Job FindJobForRunspace(Guid id)
{
foreach (var repJob in this.JobRepository.Jobs)
{
foreach (Job childJob in repJob.ChildJobs)
{
PSRemotingChildJob remotingChildJob = childJob as PSRemotingChildJob;
if (remotingChildJob != null &&
remotingChildJob.Runspace != null &&
remotingChildJob.JobStateInfo.State == JobState.Running &&
remotingChildJob.Runspace.InstanceId.Equals(id))
{
return repJob;
}
}
}
return null;
}
private bool IsParameterSetForVM()
{
return ((ParameterSetName == VMIdParameterSet) ||
(ParameterSetName == VMNameParameterSet));
}
private bool IsParameterSetForContainer()
{
return (ParameterSetName == ContainerIdParameterSet);
}
/// <summary>
/// Whether the input is a session object or property that corresponds to
/// VM or container.
/// </summary>
private bool IsParameterSetForVMContainerSession()
{
RemoteRunspace remoteRunspace = null;
switch (ParameterSetName)
{
case SessionParameterSet:
if (this.Session != null)
{
remoteRunspace = (RemoteRunspace)this.Session.Runspace;
}
break;
case InstanceIdParameterSet:
remoteRunspace = GetRunspaceMatchingRunspaceId(this.InstanceId);
break;
case IdParameterSet:
remoteRunspace = GetRunspaceMatchingSessionId(this.Id);
break;
case NameParameterSet:
remoteRunspace = GetRunspaceMatchingName(this.Name);
break;
default:
break;
}
if ((remoteRunspace != null) &&
(remoteRunspace.ConnectionInfo != null))
{
if ((remoteRunspace.ConnectionInfo is VMConnectionInfo) ||
(remoteRunspace.ConnectionInfo is ContainerConnectionInfo))
{
return true;
}
}
return false;
}
/// <summary>
/// Create runspace for VM session.
/// </summary>
private RemoteRunspace GetRunspaceForVMSession()
{
RemoteRunspace remoteRunspace = null;
string command;
Collection<PSObject> results;
if (ParameterSetName == VMIdParameterSet)
{
command = "Get-VM -Id $args[0]";
try
{
results = this.InvokeCommand.InvokeScript(
command, false, PipelineResultTypes.None, null, this.VMId);
}
catch (CommandNotFoundException)
{
WriteError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable),
PSRemotingErrorId.HyperVModuleNotAvailable.ToString(),
ErrorCategory.NotInstalled,
null));
return null;
}
if (results.Count != 1)
{
WriteError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.InvalidVMId),
PSRemotingErrorId.InvalidVMId.ToString(),
ErrorCategory.InvalidArgument,
null));
return null;
}
this.VMName = (string)results[0].Properties["VMName"].Value;
}
else
{
Dbg.Assert(ParameterSetName == VMNameParameterSet, "Expected ParameterSetName == VMName");
command = "Get-VM -Name $args";
try
{
results = this.InvokeCommand.InvokeScript(
command, false, PipelineResultTypes.None, null, this.VMName);
}
catch (CommandNotFoundException)
{
WriteError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable),
PSRemotingErrorId.HyperVModuleNotAvailable.ToString(),
ErrorCategory.NotInstalled,
null));
return null;
}
if (results.Count == 0)
{
WriteError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.InvalidVMNameNoVM),
PSRemotingErrorId.InvalidVMNameNoVM.ToString(),
ErrorCategory.InvalidArgument,
null));
return null;
}
else if (results.Count > 1)
{
WriteError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.InvalidVMNameMultipleVM),
PSRemotingErrorId.InvalidVMNameMultipleVM.ToString(),
ErrorCategory.InvalidArgument,
null));
return null;
}
this.VMId = (Guid)results[0].Properties["VMId"].Value;
this.VMName = (string)results[0].Properties["VMName"].Value;
}
//
// VM should be in running state.
//
if ((VMState)results[0].Properties["State"].Value != VMState.Running)
{
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState,
this.VMName)),
PSRemotingErrorId.InvalidVMState.ToString(),
ErrorCategory.InvalidArgument,
null));
return null;
}
try
{
VMConnectionInfo connectionInfo;
connectionInfo = new VMConnectionInfo(this.Credential, this.VMId, this.VMName, this.ConfigurationName);
remoteRunspace = CreateTemporaryRemoteRunspaceForPowerShellDirect(this.Host, connectionInfo);
}
catch (InvalidOperationException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForVMFailed",
ErrorCategory.InvalidOperation,
null);
WriteError(errorRecord);
}
catch (ArgumentException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForVMFailed",
ErrorCategory.InvalidArgument,
null);
WriteError(errorRecord);
}
catch (PSRemotingDataStructureException e)
{
ErrorRecord errorRecord;
//
// In case of PSDirectException, we should output the precise error message
// in inner exception instead of the generic one in outer exception.
//
if ((e.InnerException != null) && (e.InnerException is PSDirectException))
{
errorRecord = new ErrorRecord(e.InnerException,
"CreateRemoteRunspaceForVMFailed",
ErrorCategory.InvalidArgument,
null);
}
else
{
errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForVMFailed",
ErrorCategory.InvalidOperation,
null);
}
WriteError(errorRecord);
}
catch (Exception e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForVMFailed",
ErrorCategory.InvalidOperation,
null);
WriteError(errorRecord);
}
return remoteRunspace;
}
/// <summary>
/// Create temporary remote runspace.
/// </summary>
private RemoteRunspace CreateTemporaryRemoteRunspaceForPowerShellDirect(PSHost host, RunspaceConnectionInfo connectionInfo)
{
// Create and open the runspace.
TypeTable typeTable = TypeTable.LoadDefaultTypeFiles();
RemoteRunspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo, host, typeTable) as RemoteRunspace;
remoteRunspace.Name = "PowerShellDirectAttach";
Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null");
try
{
remoteRunspace.Open();
// Mark this temporary runspace so that it closes on pop.
remoteRunspace.ShouldCloseOnPop = true;
}
finally
{
// Make sure we dispose the temporary runspace if something bad happens.
if (remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened)
{
remoteRunspace.Dispose();
remoteRunspace = null;
}
}
return remoteRunspace;
}
/// <summary>
/// Set prompt for VM/Container sessions.
/// </summary>
private void SetRunspacePrompt(RemoteRunspace remoteRunspace)
{
if (IsParameterSetForVM() ||
IsParameterSetForContainer() ||
IsParameterSetForVMContainerSession())
{
string targetName = string.Empty;
switch (ParameterSetName)
{
case VMIdParameterSet:
case VMNameParameterSet:
targetName = this.VMName;
break;
case ContainerIdParameterSet:
targetName = (this.ContainerId.Length <= 15) ? this.ContainerId
: this.ContainerId.Remove(14) + PSObjectHelper.Ellipsis;
break;
case SessionParameterSet:
targetName = (this.Session != null) ? this.Session.ComputerName : string.Empty;
break;
case InstanceIdParameterSet:
case IdParameterSet:
case NameParameterSet:
if ((remoteRunspace != null) &&
(remoteRunspace.ConnectionInfo != null))
{
targetName = remoteRunspace.ConnectionInfo.ComputerName;
}
break;
default:
Dbg.Assert(false, "Unrecognized parameter set.");
break;
}
string promptFn = StringUtil.Format(RemotingErrorIdStrings.EnterVMSessionPrompt,
@"function global:prompt { """,
targetName,
@"PS $($executionContext.SessionState.Path.CurrentLocation)> "" }");
// Set prompt in pushed named pipe runspace.
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
{
ps.Runspace = remoteRunspace;
try
{
// Set pushed runspace prompt.
ps.AddScript(promptFn).Invoke();
}
catch (Exception)
{
}
}
}
return;
}
/// <summary>
/// Create runspace for container session.
/// </summary>
private RemoteRunspace GetRunspaceForContainerSession()
{
RemoteRunspace remoteRunspace = null;
try
{
Dbg.Assert(!string.IsNullOrEmpty(ContainerId), "ContainerId has to be set.");
ContainerConnectionInfo connectionInfo = null;
//
// Hyper-V container uses Hype-V socket as transport.
// Windows Server container uses named pipe as transport.
//
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(ContainerId, RunAsAdministrator.IsPresent, this.ConfigurationName);
connectionInfo.CreateContainerProcess();
remoteRunspace = CreateTemporaryRemoteRunspaceForPowerShellDirect(this.Host, connectionInfo);
}
catch (InvalidOperationException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidOperation,
null);
WriteError(errorRecord);
}
catch (ArgumentException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidArgument,
null);
WriteError(errorRecord);
}
catch (PSRemotingDataStructureException e)
{
ErrorRecord errorRecord;
//
// In case of PSDirectException, we should output the precise error message
// in inner exception instead of the generic one in outer exception.
//
if ((e.InnerException != null) && (e.InnerException is PSDirectException))
{
errorRecord = new ErrorRecord(e.InnerException,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidOperation,
null);
}
else
{
errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidOperation,
null);
}
WriteError(errorRecord);
}
catch (Exception e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidOperation,
null);
WriteError(errorRecord);
}
return remoteRunspace;
}
/// <summary>
/// Create remote runspace for SSH session.
/// </summary>
private RemoteRunspace GetRunspaceForSSHSession()
{
ParseSshHostName(HostName, out string host, out string userName, out int port);
var sshConnectionInfo = new SSHConnectionInfo(userName, host, this.KeyFilePath, port, this.Subsystem);
var typeTable = TypeTable.LoadDefaultTypeFiles();
// Use the class _tempRunspace field while the runspace is being opened so that StopProcessing can be handled at that time.
// This is only needed for SSH sessions where a Ctrl+C during an SSH password prompt can abort the session before a connection
// is established.
_tempRunspace = RunspaceFactory.CreateRunspace(sshConnectionInfo, this.Host, typeTable) as RemoteRunspace;
_tempRunspace.Open();
_tempRunspace.ShouldCloseOnPop = true;
var remoteRunspace = _tempRunspace;
_tempRunspace = null;
return remoteRunspace;
}
#endregion
#region Internal Methods
internal static RemotePipeline ConnectRunningPipeline(RemoteRunspace remoteRunspace)
{
RemotePipeline cmd = null;
if (remoteRunspace.RemoteCommand != null)
{
// Reconstruct scenario.
// Newly connected pipeline object is added to the RemoteRunspace running
// pipeline list.
cmd = new RemotePipeline(remoteRunspace);
}
else
{
// Reconnect scenario.
cmd = remoteRunspace.GetCurrentlyRunningPipeline() as RemotePipeline;
}
// Connect the runspace pipeline so that debugging and output data from
// remote server can continue.
if (cmd != null &&
cmd.PipelineStateInfo.State == PipelineState.Disconnected)
{
using (ManualResetEvent connected = new ManualResetEvent(false))
{
cmd.StateChanged += (sender, args) =>
{
if (args.PipelineStateInfo.State != PipelineState.Disconnected)
{
try
{
connected.Set();
}
catch (ObjectDisposedException) { }
}
};
cmd.ConnectAsync();
connected.WaitOne();
}
}
return cmd;
}
internal static void ContinueCommand(RemoteRunspace remoteRunspace, Pipeline cmd, PSHost host, bool inDebugMode, System.Management.Automation.ExecutionContext context)
{
RemotePipeline remotePipeline = cmd as RemotePipeline;
if (remotePipeline != null)
{
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
{
PSInvocationSettings settings = new PSInvocationSettings()
{
Host = host
};
PSDataCollection<PSObject> input = new PSDataCollection<PSObject>();
CommandInfo commandInfo = new CmdletInfo("Out-Default", typeof(OutDefaultCommand), null, null, context);
Command outDefaultCommand = new Command(commandInfo);
ps.AddCommand(outDefaultCommand);
IAsyncResult async = ps.BeginInvoke<PSObject>(input, settings, null, null);
RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger;
if (remoteDebugger != null)
{
// Update client with breakpoint information from pushed runspace.
// Information will be passed to the client via the Debugger.BreakpointUpdated event.
remoteDebugger.SendBreakpointUpdatedEvents();
if (!inDebugMode)
{
// Enter debug mode if remote runspace is in debug stop mode.
remoteDebugger.CheckStateAndRaiseStopEvent();
}
}
// Wait for debugged cmd to complete.
while (!remotePipeline.Output.EndOfPipeline)
{
remotePipeline.Output.WaitHandle.WaitOne();
while (remotePipeline.Output.Count > 0)
{
input.Add(remotePipeline.Output.Read());
}
}
input.Complete();
ps.EndInvoke(async);
}
}
}
#endregion
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Organization
///<para>SObject Name: Organization</para>
///<para>Custom Object: False</para>
///</summary>
public class SfOrganization : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "Organization"; }
}
///<summary>
/// Organization ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Name
/// <para>Name: Name</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "name")]
[Updateable(true), Createable(false)]
public string Name { get; set; }
///<summary>
/// Division
/// <para>Name: Division</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "division")]
[Updateable(true), Createable(false)]
public string Division { get; set; }
///<summary>
/// Street
/// <para>Name: Street</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "street")]
[Updateable(true), Createable(false)]
public string Street { get; set; }
///<summary>
/// City
/// <para>Name: City</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "city")]
[Updateable(true), Createable(false)]
public string City { get; set; }
///<summary>
/// State/Province
/// <para>Name: State</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "state")]
[Updateable(true), Createable(false)]
public string State { get; set; }
///<summary>
/// Zip/Postal Code
/// <para>Name: PostalCode</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "postalCode")]
[Updateable(true), Createable(false)]
public string PostalCode { get; set; }
///<summary>
/// Country
/// <para>Name: Country</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "country")]
[Updateable(false), Createable(false)]
public string Country { get; set; }
///<summary>
/// Latitude
/// <para>Name: Latitude</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "latitude")]
[Updateable(true), Createable(false)]
public double? Latitude { get; set; }
///<summary>
/// Longitude
/// <para>Name: Longitude</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "longitude")]
[Updateable(true), Createable(false)]
public double? Longitude { get; set; }
///<summary>
/// Geocode Accuracy
/// <para>Name: GeocodeAccuracy</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "geocodeAccuracy")]
[Updateable(true), Createable(false)]
public string GeocodeAccuracy { get; set; }
///<summary>
/// Address
/// <para>Name: Address</para>
/// <para>SF Type: address</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "address")]
[Updateable(false), Createable(false)]
public Address Address { get; set; }
///<summary>
/// Phone
/// <para>Name: Phone</para>
/// <para>SF Type: phone</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "phone")]
[Updateable(true), Createable(false)]
public string Phone { get; set; }
///<summary>
/// Fax
/// <para>Name: Fax</para>
/// <para>SF Type: phone</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fax")]
[Updateable(true), Createable(false)]
public string Fax { get; set; }
///<summary>
/// Primary Contact
/// <para>Name: PrimaryContact</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "primaryContact")]
[Updateable(true), Createable(false)]
public string PrimaryContact { get; set; }
///<summary>
/// Locale
/// <para>Name: DefaultLocaleSidKey</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "defaultLocaleSidKey")]
[Updateable(true), Createable(false)]
public string DefaultLocaleSidKey { get; set; }
///<summary>
/// Time Zone
/// <para>Name: TimeZoneSidKey</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "timeZoneSidKey")]
[Updateable(true), Createable(false)]
public string TimeZoneSidKey { get; set; }
///<summary>
/// Language
/// <para>Name: LanguageLocaleKey</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "languageLocaleKey")]
[Updateable(true), Createable(false)]
public string LanguageLocaleKey { get; set; }
///<summary>
/// Info Emails
/// <para>Name: ReceivesInfoEmails</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "receivesInfoEmails")]
[Updateable(true), Createable(false)]
public bool? ReceivesInfoEmails { get; set; }
///<summary>
/// Info Emails Admin
/// <para>Name: ReceivesAdminInfoEmails</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "receivesAdminInfoEmails")]
[Updateable(true), Createable(false)]
public bool? ReceivesAdminInfoEmails { get; set; }
///<summary>
/// RequireOpportunityProducts
/// <para>Name: PreferencesRequireOpportunityProducts</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "preferencesRequireOpportunityProducts")]
[Updateable(true), Createable(false)]
public bool? PreferencesRequireOpportunityProducts { get; set; }
///<summary>
/// TransactionSecurityPolicy
/// <para>Name: PreferencesTransactionSecurityPolicy</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "preferencesTransactionSecurityPolicy")]
[Updateable(true), Createable(false)]
public bool? PreferencesTransactionSecurityPolicy { get; set; }
///<summary>
/// TerminateOldestSession
/// <para>Name: PreferencesTerminateOldestSession</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "preferencesTerminateOldestSession")]
[Updateable(true), Createable(false)]
public bool? PreferencesTerminateOldestSession { get; set; }
///<summary>
/// ConsentManagementEnabled
/// <para>Name: PreferencesConsentManagementEnabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "preferencesConsentManagementEnabled")]
[Updateable(true), Createable(false)]
public bool? PreferencesConsentManagementEnabled { get; set; }
///<summary>
/// AutoSelectIndividualOnMerge
/// <para>Name: PreferencesAutoSelectIndividualOnMerge</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "preferencesAutoSelectIndividualOnMerge")]
[Updateable(true), Createable(false)]
public bool? PreferencesAutoSelectIndividualOnMerge { get; set; }
///<summary>
/// LightningLoginEnabled
/// <para>Name: PreferencesLightningLoginEnabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "preferencesLightningLoginEnabled")]
[Updateable(true), Createable(false)]
public bool? PreferencesLightningLoginEnabled { get; set; }
///<summary>
/// OnlyLLPermUserAllowed
/// <para>Name: PreferencesOnlyLLPermUserAllowed</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "preferencesOnlyLLPermUserAllowed")]
[Updateable(true), Createable(false)]
public bool? PreferencesOnlyLLPermUserAllowed { get; set; }
///<summary>
/// Fiscal Year Starts In
/// <para>Name: FiscalYearStartMonth</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fiscalYearStartMonth")]
[Updateable(false), Createable(false)]
public int? FiscalYearStartMonth { get; set; }
///<summary>
/// Fiscal Year Name by Start
/// <para>Name: UsesStartDateAsFiscalYearName</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "usesStartDateAsFiscalYearName")]
[Updateable(false), Createable(false)]
public bool? UsesStartDateAsFiscalYearName { get; set; }
///<summary>
/// Default Account Access
/// <para>Name: DefaultAccountAccess</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "defaultAccountAccess")]
[Updateable(false), Createable(false)]
public string DefaultAccountAccess { get; set; }
///<summary>
/// Default Contact Access
/// <para>Name: DefaultContactAccess</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "defaultContactAccess")]
[Updateable(false), Createable(false)]
public string DefaultContactAccess { get; set; }
///<summary>
/// Default Opportunity Access
/// <para>Name: DefaultOpportunityAccess</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "defaultOpportunityAccess")]
[Updateable(false), Createable(false)]
public string DefaultOpportunityAccess { get; set; }
///<summary>
/// Default Lead Access
/// <para>Name: DefaultLeadAccess</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "defaultLeadAccess")]
[Updateable(false), Createable(false)]
public string DefaultLeadAccess { get; set; }
///<summary>
/// Default Case Access
/// <para>Name: DefaultCaseAccess</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "defaultCaseAccess")]
[Updateable(false), Createable(false)]
public string DefaultCaseAccess { get; set; }
///<summary>
/// Default Calendar Access
/// <para>Name: DefaultCalendarAccess</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "defaultCalendarAccess")]
[Updateable(false), Createable(false)]
public string DefaultCalendarAccess { get; set; }
///<summary>
/// Default Price Book Access
/// <para>Name: DefaultPricebookAccess</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "defaultPricebookAccess")]
[Updateable(false), Createable(false)]
public string DefaultPricebookAccess { get; set; }
///<summary>
/// Default Campaign Access
/// <para>Name: DefaultCampaignAccess</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "defaultCampaignAccess")]
[Updateable(false), Createable(false)]
public string DefaultCampaignAccess { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Compliance BCC Email
/// <para>Name: ComplianceBccEmail</para>
/// <para>SF Type: email</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "complianceBccEmail")]
[Updateable(false), Createable(false)]
public string ComplianceBccEmail { get; set; }
///<summary>
/// UI Skin
/// <para>Name: UiSkin</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "uiSkin")]
[Updateable(true), Createable(false)]
public string UiSkin { get; set; }
///<summary>
/// Signup Country
/// <para>Name: SignupCountryIsoCode</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "signupCountryIsoCode")]
[Updateable(false), Createable(false)]
public string SignupCountryIsoCode { get; set; }
///<summary>
/// Trial Expiration Date
/// <para>Name: TrialExpirationDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "trialExpirationDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? TrialExpirationDate { get; set; }
///<summary>
/// Knowledge Licenses
/// <para>Name: NumKnowledgeService</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "numKnowledgeService")]
[Updateable(false), Createable(false)]
public int? NumKnowledgeService { get; set; }
///<summary>
/// Edition
/// <para>Name: OrganizationType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "organizationType")]
[Updateable(false), Createable(false)]
public string OrganizationType { get; set; }
///<summary>
/// Namespace Prefix
/// <para>Name: NamespacePrefix</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "namespacePrefix")]
[Updateable(false), Createable(false)]
public string NamespacePrefix { get; set; }
///<summary>
/// Instance Name
/// <para>Name: InstanceName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "instanceName")]
[Updateable(false), Createable(false)]
public string InstanceName { get; set; }
///<summary>
/// Is Sandbox
/// <para>Name: IsSandbox</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isSandbox")]
[Updateable(false), Createable(false)]
public bool? IsSandbox { get; set; }
///<summary>
/// Web to Cases Default Origin
/// <para>Name: WebToCaseDefaultOrigin</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "webToCaseDefaultOrigin")]
[Updateable(true), Createable(false)]
public string WebToCaseDefaultOrigin { get; set; }
///<summary>
/// Monthly Page Views Used
/// <para>Name: MonthlyPageViewsUsed</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "monthlyPageViewsUsed")]
[Updateable(false), Createable(false)]
public int? MonthlyPageViewsUsed { get; set; }
///<summary>
/// Monthly Page Views Allowed
/// <para>Name: MonthlyPageViewsEntitlement</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "monthlyPageViewsEntitlement")]
[Updateable(false), Createable(false)]
public int? MonthlyPageViewsEntitlement { get; set; }
///<summary>
/// Is Read Only
/// <para>Name: IsReadOnly</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isReadOnly")]
[Updateable(false), Createable(false)]
public bool? IsReadOnly { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
}
}
| |
// Copyright (c) 2013-2016 CoreTweet Development Team
//
// 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.IO;
using System.Linq;
using System.Reflection;
using System.Text;
#if !NET35
using System.Threading;
using System.Threading.Tasks;
#endif
namespace CoreTweet
{
internal static class EnumerableExtensions
{
internal static IEnumerable<string> EnumerateLines(this StreamReader streamReader)
{
while(!streamReader.EndOfStream)
yield return streamReader.ReadLine();
}
internal static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach(T item in source)
action(item);
}
internal static string JoinToString<T>(this IEnumerable<T> source)
{
#if !NET35
return string.Concat(source);
#else
return string.Concat(source.Cast<object>().ToArray());
#endif
}
internal static string JoinToString<T>(this IEnumerable<T> source, string separator)
{
#if !NET35
return string.Join(separator, source);
#else
return string.Join(separator, source.Select(x => x.ToString()).ToArray());
#endif
}
internal static IEnumerable<T> EndWith<T>(this IEnumerable<T> source, params T[] second)
{
return source.Concat(second);
}
}
internal static class DisposableExtensions
{
internal class Using<T>
where T : IDisposable
{
internal T Source { get; }
internal Using(T source)
{
Source = source;
}
}
internal static Using<T> Use<T>(this T source)
where T : IDisposable
{
return new Using<T>(source);
}
internal static TResult SelectMany<T, TSecond, TResult>
(this Using<T> source, Func<T, Using<TSecond>> second, Func<T, TSecond, TResult> selector)
where T : IDisposable
where TSecond : IDisposable
{
using(source.Source)
using(var s = second(source.Source).Source)
return selector(source.Source, s);
}
internal static TResult Select<T, TResult>(this Using<T> source, Func<T, TResult> selector)
where T : IDisposable
{
using(source.Source)
return selector(source.Source);
}
}
internal static class StreamExtensions
{
internal static void WriteString(this Stream stream, string value)
{
var bytes = Encoding.UTF8.GetBytes(value);
stream.Write(bytes, 0, bytes.Length);
}
}
internal static class ExceptionExtensions
{
internal static void Rethrow(this Exception ex)
{
#if NET45 || WIN_RT || WP
System.Runtime.ExceptionServices
.ExceptionDispatchInfo.Capture(ex)
.Throw();
#else
throw ex;
#endif
}
}
#if WIN_RT || PCL
internal static class TypeInfoExtensions
{
internal static IEnumerable<TypeInfo> GetInterfaces(this TypeInfo source)
{
return source.ImplementedInterfaces.Select(IntrospectionExtensions.GetTypeInfo);
}
internal static PropertyInfo GetProperty(this TypeInfo source, string name)
{
return source.GetDeclaredProperty(name);
}
internal static MethodInfo GetGetMethod(this PropertyInfo source)
{
return source.GetMethod;
}
}
#endif
#if !NET35
internal struct Unit
{
internal static readonly Unit Default = new Unit();
}
internal static class TaskExtensions
{
internal static Task<TResult> Done<TSource, TResult>(this Task<TSource> source, Func<TSource, TResult> action, CancellationToken cancellationToken, bool longRunning = false)
{
var tcs = new TaskCompletionSource<TResult>();
source.ContinueWith(t =>
{
if(t.IsCanceled || cancellationToken.IsCancellationRequested)
{
tcs.TrySetCanceled();
return;
}
if(t.Exception != null)
{
tcs.TrySetException(t.Exception.InnerExceptions.Count == 1 ? t.Exception.InnerException : t.Exception);
return;
}
try
{
tcs.TrySetResult(action(t.Result));
}
catch(OperationCanceledException)
{
tcs.TrySetCanceled();
}
catch(Exception ex)
{
tcs.TrySetException(ex);
}
}, longRunning ? TaskContinuationOptions.LongRunning : TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
internal static Task Done<TSource>(this Task<TSource> source, Action<TSource> action, CancellationToken cancellationToken, bool longRunning = false)
{
var tcs = new TaskCompletionSource<Unit>();
source.ContinueWith(t =>
{
if (t.IsCanceled || cancellationToken.IsCancellationRequested)
{
tcs.TrySetCanceled();
return;
}
if (t.Exception != null)
{
tcs.TrySetException(t.Exception.InnerExceptions.Count == 1 ? t.Exception.InnerException : t.Exception);
return;
}
try
{
action(t.Result);
tcs.TrySetResult(Unit.Default);
}
catch (OperationCanceledException)
{
tcs.TrySetCanceled();
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}, longRunning ? TaskContinuationOptions.LongRunning : TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
internal static Task<TResult> Done<TResult>(this Task source, Func<TResult> action, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<TResult>();
source.ContinueWith(t =>
{
if (t.IsCanceled || cancellationToken.IsCancellationRequested)
{
tcs.TrySetCanceled();
return;
}
if (t.Exception != null)
{
tcs.TrySetException(t.Exception.InnerExceptions.Count == 1 ? t.Exception.InnerException : t.Exception);
return;
}
try
{
tcs.TrySetResult(action());
}
catch (OperationCanceledException)
{
tcs.TrySetCanceled();
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
}
#endif
}
| |
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace Nop.Core.Html
{
/// <summary>
/// Represents a HTML helper
/// </summary>
public partial class HtmlHelper
{
#region Fields
private readonly static Regex paragraphStartRegex = new Regex("<p>", RegexOptions.IgnoreCase);
private readonly static Regex paragraphEndRegex = new Regex("</p>", RegexOptions.IgnoreCase);
//private static Regex ampRegex = new Regex("&(?!(?:#[0-9]{2,4};|[a-z0-9]+;))", RegexOptions.Compiled | RegexOptions.IgnoreCase);
#endregion
#region Utilities
private static string EnsureOnlyAllowedHtml(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
const string allowedTags = "br,hr,b,i,u,a,div,ol,ul,li,blockquote,img,span,p,em,strong,font,pre,h1,h2,h3,h4,h5,h6,address,cite";
var m = Regex.Matches(text, "<.*?>", RegexOptions.IgnoreCase);
for (int i = m.Count - 1; i >= 0; i--)
{
string tag = text.Substring(m[i].Index + 1, m[i].Length - 1).Trim().ToLower();
if (!IsValidTag(tag, allowedTags))
{
text = text.Remove(m[i].Index, m[i].Length);
}
}
return text;
}
private static bool IsValidTag(string tag, string tags)
{
string[] allowedTags = tags.Split(',');
if (tag.IndexOf("javascript") >= 0) return false;
if (tag.IndexOf("vbscript") >= 0) return false;
if (tag.IndexOf("onclick") >= 0) return false;
var endchars = new [] { ' ', '>', '/', '\t' };
int pos = tag.IndexOfAny(endchars, 1);
if (pos > 0) tag = tag.Substring(0, pos);
if (tag[0] == '/') tag = tag.Substring(1);
foreach (string aTag in allowedTags)
{
if (tag == aTag) return true;
}
return false;
}
#endregion
#region Methods
/// <summary>
/// Formats the text
/// </summary>
/// <param name="text">Text</param>
/// <param name="stripTags">A value indicating whether to strip tags</param>
/// <param name="convertPlainTextToHtml">A value indicating whether HTML is allowed</param>
/// <param name="allowHtml">A value indicating whether HTML is allowed</param>
/// <param name="allowBBCode">A value indicating whether BBCode is allowed</param>
/// <param name="resolveLinks">A value indicating whether to resolve links</param>
/// <param name="addNoFollowTag">A value indicating whether to add "noFollow" tag</param>
/// <returns>Formatted text</returns>
public static string FormatText(string text, bool stripTags,
bool convertPlainTextToHtml, bool allowHtml,
bool allowBBCode, bool resolveLinks, bool addNoFollowTag)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
try
{
if (stripTags)
{
text = StripTags(text);
}
if (allowHtml)
{
text = EnsureOnlyAllowedHtml(text);
}
else
{
text = HttpUtility.HtmlEncode(text);
}
if (convertPlainTextToHtml)
{
text = ConvertPlainTextToHtml(text);
}
if (allowBBCode)
{
text = BBCodeHelper.FormatText(text, true, true, true, true, true, true);
}
if (resolveLinks)
{
text = ResolveLinksHelper.FormatText(text);
}
if (addNoFollowTag)
{
//add noFollow tag. not implemented
}
}
catch (Exception exc)
{
text = string.Format("Text cannot be formatted. Error: {0}", exc.Message);
}
return text;
}
/// <summary>
/// Strips tags
/// </summary>
/// <param name="text">Text</param>
/// <returns>Formatted text</returns>
public static string StripTags(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = Regex.Replace(text, @"(>)(\r|\n)*(<)", "><");
text = Regex.Replace(text, "(<[^>]*>)([^<]*)", "$2");
text = Regex.Replace(text, "(&#x?[0-9]{2,4};|"|&| |<|>|€|©|®|‰|‡|†|‹|›|„|”|“|‚|’|‘|—|–|‏|‎|‍|‌| | | |˜|ˆ|Ÿ|š|Š)", "@");
return text;
}
/// <summary>
/// replace anchor text (remove a tag from the following url <a href="http://example.com">Name</a> and output only the string "Name")
/// </summary>
/// <param name="text">Text</param>
/// <returns>Text</returns>
public static string ReplaceAnchorTags(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = Regex.Replace(text, @"<a\b[^>]+>([^<]*(?:(?!</a)<[^<]*)*)</a>", "$1", RegexOptions.IgnoreCase);
return text;
}
/// <summary>
/// Converts plain text to HTML
/// </summary>
/// <param name="text">Text</param>
/// <returns>Formatted text</returns>
public static string ConvertPlainTextToHtml(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = text.Replace("\r\n", "<br />");
text = text.Replace("\r", "<br />");
text = text.Replace("\n", "<br />");
text = text.Replace("\t", " ");
text = text.Replace(" ", " ");
return text;
}
/// <summary>
/// Converts HTML to plain text
/// </summary>
/// <param name="text">Text</param>
/// <param name="decode">A value indicating whether to decode text</param>
/// <param name="replaceAnchorTags">A value indicating whether to replace anchor text (remove a tag from the following url <a href="http://example.com">Name</a> and output only the string "Name")</param>
/// <returns>Formatted text</returns>
public static string ConvertHtmlToPlainText(string text,
bool decode = false, bool replaceAnchorTags = false)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
if (decode)
text = HttpUtility.HtmlDecode(text);
text = text.Replace("<br>", "\n");
text = text.Replace("<br >", "\n");
text = text.Replace("<br />", "\n");
text = text.Replace(" ", "\t");
text = text.Replace(" ", " ");
if (replaceAnchorTags)
text = ReplaceAnchorTags(text);
return text;
}
/// <summary>
/// Converts text to paragraph
/// </summary>
/// <param name="text">Text</param>
/// <returns>Formatted text</returns>
public static string ConvertPlainTextToParagraph(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = paragraphStartRegex.Replace(text, string.Empty);
text = paragraphEndRegex.Replace(text, "\n");
text = text.Replace("\r\n", "\n").Replace("\r", "\n");
text = text + "\n\n";
text = text.Replace("\n\n", "\n");
var strArray = text.Split(new [] { '\n' });
var builder = new StringBuilder();
foreach (string str in strArray)
{
if ((str != null) && (str.Trim().Length > 0))
{
builder.AppendFormat("<p>{0}</p>\n", str);
}
}
return builder.ToString();
}
#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.ComponentModel;
using System.Diagnostics;
using System.Drawing.Internal;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
public sealed partial class Font
{
private const int LogFontCharSetOffset = 23;
private const int LogFontNameOffset = 28;
///<summary>
/// Creates the GDI+ native font object.
///</summary>
private void CreateNativeFont()
{
Debug.Assert(_nativeFont == IntPtr.Zero, "nativeFont already initialized, this will generate a handle leak.");
Debug.Assert(_fontFamily != null, "fontFamily not initialized.");
// Note: GDI+ creates singleton font family objects (from the corresponding font file) and reference count them so
// if creating the font object from an external FontFamily, this object's FontFamily will share the same native object.
int status = Gdip.GdipCreateFont(
new HandleRef(this, _fontFamily.NativeFamily),
_fontSize,
_fontStyle,
_fontUnit,
out _nativeFont);
// Special case this common error message to give more information
if (status == Gdip.FontStyleNotFound)
{
throw new ArgumentException(SR.Format(SR.GdiplusFontStyleNotFound, _fontFamily.Name, _fontStyle.ToString()));
}
else if (status != Gdip.Ok)
{
throw Gdip.StatusException(status);
}
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class from the specified existing <see cref='Font'/>
/// and <see cref='FontStyle'/>.
/// </summary>
public Font(Font prototype, FontStyle newStyle)
{
// Copy over the originalFontName because it won't get initialized
_originalFontName = prototype.OriginalFontName;
Initialize(prototype.FontFamily, prototype.Size, newStyle, prototype.Unit, SafeNativeMethods.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit)
{
Initialize(family, emSize, style, unit, SafeNativeMethods.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)
{
Initialize(family, emSize, style, unit, gdiCharSet, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
Initialize(family, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)
{
Initialize(familyName, emSize, style, unit, gdiCharSet, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize));
}
Initialize(familyName, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style)
{
Initialize(family, emSize, style, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, GraphicsUnit unit)
{
Initialize(family, emSize, FontStyle.Regular, unit, SafeNativeMethods.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize)
{
Initialize(family, emSize, FontStyle.Regular, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit)
{
Initialize(familyName, emSize, style, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style)
{
Initialize(familyName, emSize, style, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, GraphicsUnit unit)
{
Initialize(familyName, emSize, FontStyle.Regular, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize)
{
Initialize(familyName, emSize, FontStyle.Regular, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Constructor to initialize fields from an existing native GDI+ object reference. Used by ToLogFont.
/// </summary>
private Font(IntPtr nativeFont, byte gdiCharSet, bool gdiVerticalFont)
{
Debug.Assert(_nativeFont == IntPtr.Zero, "GDI+ native font already initialized, this will generate a handle leak");
Debug.Assert(nativeFont != IntPtr.Zero, "nativeFont is null");
int status = 0;
float size = 0;
GraphicsUnit unit = GraphicsUnit.Point;
FontStyle style = FontStyle.Regular;
IntPtr nativeFamily = IntPtr.Zero;
_nativeFont = nativeFont;
status = Gdip.GdipGetFontUnit(new HandleRef(this, nativeFont), out unit);
Gdip.CheckStatus(status);
status = Gdip.GdipGetFontSize(new HandleRef(this, nativeFont), out size);
Gdip.CheckStatus(status);
status = Gdip.GdipGetFontStyle(new HandleRef(this, nativeFont), out style);
Gdip.CheckStatus(status);
status = Gdip.GdipGetFamily(new HandleRef(this, nativeFont), out nativeFamily);
Gdip.CheckStatus(status);
SetFontFamily(new FontFamily(nativeFamily));
Initialize(_fontFamily, size, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes this object's fields.
/// </summary>
private void Initialize(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
_originalFontName = familyName;
SetFontFamily(new FontFamily(StripVerticalName(familyName), createDefaultOnFail: true));
Initialize(_fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes this object's fields.
/// </summary>
private void Initialize(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
if (family == null)
{
throw new ArgumentNullException(nameof(family));
}
if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize));
}
int status;
_fontSize = emSize;
_fontStyle = style;
_fontUnit = unit;
_gdiCharSet = gdiCharSet;
_gdiVerticalFont = gdiVerticalFont;
if (_fontFamily == null)
{
// GDI+ FontFamily is a singleton object.
SetFontFamily(new FontFamily(family.NativeFamily));
}
if (_nativeFont == IntPtr.Zero)
{
CreateNativeFont();
}
// Get actual size.
status = Gdip.GdipGetFontSize(new HandleRef(this, _nativeFont), out _fontSize);
Gdip.CheckStatus(status);
}
/// <summary>
/// Creates a <see cref='System.Drawing.Font'/> from the specified Windows handle.
/// </summary>
public static Font FromHfont(IntPtr hfont)
{
var lf = new SafeNativeMethods.LOGFONT();
SafeNativeMethods.GetObject(new HandleRef(null, hfont), lf);
IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
try
{
return FromLogFont(lf, screenDC);
}
finally
{
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
}
}
public static Font FromLogFont(object lf)
{
IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
try
{
return FromLogFont(lf, screenDC);
}
finally
{
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
}
}
public static Font FromLogFont(object lf, IntPtr hdc)
{
IntPtr font = IntPtr.Zero;
int status = Gdip.GdipCreateFontFromLogfontW(new HandleRef(null, hdc), lf, out font);
// Special case this incredibly common error message to give more information
if (status == Gdip.NotTrueTypeFont)
{
throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont_NoName));
}
else if (status != Gdip.Ok)
{
throw Gdip.StatusException(status);
}
// GDI+ returns font = 0 even though the status is Ok.
if (font == IntPtr.Zero)
{
throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont, lf.ToString()));
}
#pragma warning disable 0618
bool gdiVerticalFont = (Marshal.ReadInt16(lf, LogFontNameOffset) == (short)'@');
return new Font(font, Marshal.ReadByte(lf, LogFontCharSetOffset), gdiVerticalFont);
#pragma warning restore 0618
}
/// <summary>
/// Creates a Font from the specified Windows handle to a device context.
/// </summary>
public static Font FromHdc(IntPtr hdc)
{
IntPtr font = IntPtr.Zero;
int status = Gdip.GdipCreateFontFromDC(new HandleRef(null, hdc), ref font);
// Special case this incredibly common error message to give more information
if (status == Gdip.NotTrueTypeFont)
{
throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont_NoName));
}
else if (status != Gdip.Ok)
{
throw Gdip.StatusException(status);
}
return new Font(font, 0, false);
}
/// <summary>
/// Creates an exact copy of this <see cref='Font'/>.
/// </summary>
public object Clone()
{
IntPtr clonedFont = IntPtr.Zero;
int status = Gdip.GdipCloneFont(new HandleRef(this, _nativeFont), out clonedFont);
Gdip.CheckStatus(status);
return new Font(clonedFont, _gdiCharSet, _gdiVerticalFont);
}
private void SetFontFamily(FontFamily family)
{
_fontFamily = family;
// GDI+ creates ref-counted singleton FontFamily objects based on the family name so all managed
// objects with same family name share the underlying GDI+ native pointer. The unmanged object is
// destroyed when its ref-count gets to zero.
// Make sure this.fontFamily is not finalized so the underlying singleton object is kept alive.
GC.SuppressFinalize(_fontFamily);
}
private static bool IsVerticalName(string familyName) => familyName?.Length > 0 && familyName[0] == '@';
private static string StripVerticalName(string familyName)
{
if (familyName?.Length > 1 && familyName[0] == '@')
{
return familyName.Substring(1);
}
return familyName;
}
public void ToLogFont(object logFont)
{
IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
try
{
Graphics graphics = Graphics.FromHdcInternal(screenDC);
try
{
ToLogFont(logFont, graphics);
}
finally
{
graphics.Dispose();
}
}
finally
{
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
}
}
public unsafe void ToLogFont(object logFont, Graphics graphics)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
int status = Gdip.GdipGetLogFontW(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), logFont);
// Prefix the string with '@' this is a gdiVerticalFont.
#pragma warning disable 0618
if (_gdiVerticalFont)
{
// Copy the Unicode contents of the name.
for (int i = 60; i >= 0; i -= 2)
{
Marshal.WriteInt16(logFont,
LogFontNameOffset + i + 2,
Marshal.ReadInt16(logFont, LogFontNameOffset + i));
}
// Prefix the name with an '@' sign.
Marshal.WriteInt16(logFont, LogFontNameOffset, (short)'@');
}
if (Marshal.ReadByte(logFont, LogFontCharSetOffset) == 0)
{
Marshal.WriteByte(logFont, LogFontCharSetOffset, _gdiCharSet);
}
#pragma warning restore 0618
Gdip.CheckStatus(status);
}
/// <summary>
/// Returns a handle to this <see cref='Font'/>.
/// </summary>
public IntPtr ToHfont()
{
var lf = new SafeNativeMethods.LOGFONT();
ToLogFont(lf);
IntPtr handle = IntUnsafeNativeMethods.IntCreateFontIndirect(lf);
if (handle == IntPtr.Zero)
{
throw new Win32Exception();
}
return handle;
}
public float GetHeight()
{
IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
try
{
using (Graphics graphics = Graphics.FromHdcInternal(screenDC))
{
return GetHeight(graphics);
}
}
finally
{
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
}
}
/// <summary>
/// Gets the size, in points, of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public float SizeInPoints
{
get
{
if (Unit == GraphicsUnit.Point)
{
return Size;
}
IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
try
{
using (Graphics graphics = Graphics.FromHdcInternal(screenDC))
{
float pixelsPerPoint = (float)(graphics.DpiY / 72.0);
float lineSpacingInPixels = GetHeight(graphics);
float emHeightInPixels = lineSpacingInPixels * FontFamily.GetEmHeight(Style) / FontFamily.GetLineSpacing(Style);
return emHeightInPixels / pixelsPerPoint;
}
}
finally
{
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Validation
{
public class ExplicitIndexCollectionValidationStrategyTest
{
[Fact]
public void EnumerateElements_List()
{
// Arrange
var model = new List<int>() { 2, 3, 5 };
var metadata = TestModelMetadataProvider.CreateDefaultProvider().GetMetadataForType(typeof(List<int>));
var strategy = new ExplicitIndexCollectionValidationStrategy(new string[] { "zero", "one", "two" });
// Act
var enumerator = strategy.GetChildren(metadata, "prefix", model);
// Assert
Assert.Collection(
BufferEntries(enumerator).OrderBy(e => e.Key),
e =>
{
Assert.Equal("prefix[one]", e.Key);
Assert.Equal(3, e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
},
e =>
{
Assert.Equal("prefix[two]", e.Key);
Assert.Equal(5, e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
},
e =>
{
Assert.Equal("prefix[zero]", e.Key);
Assert.Equal(2, e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
});
}
[Fact]
public void EnumerateElements_Dictionary()
{
// Arrange
var model = new Dictionary<int, string>()
{
{ 2, "two" },
{ 3, "three" },
{ 5, "five" },
};
var metadata = TestModelMetadataProvider.CreateDefaultProvider().GetMetadataForType(typeof(List<int>));
var strategy = new ExplicitIndexCollectionValidationStrategy(new string[] { "zero", "one", "two" });
// Act
var enumerator = strategy.GetChildren(metadata, "prefix", model);
// Assert
Assert.Collection(
BufferEntries(enumerator).OrderBy(e => e.Key),
e =>
{
Assert.Equal("prefix[one]", e.Key);
Assert.Equal(new KeyValuePair<int, string>(3, "three"), e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
},
e =>
{
Assert.Equal("prefix[two]", e.Key);
Assert.Equal(new KeyValuePair<int, string>(5, "five"), e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
},
e =>
{
Assert.Equal("prefix[zero]", e.Key);
Assert.Equal(new KeyValuePair<int, string>(2, "two"), e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
});
}
[Fact]
public void EnumerateElements_TwoEnumerableImplementations()
{
// Arrange
var model = new TwiceEnumerable(new int[] { 2, 3, 5 });
var metadata = TestModelMetadataProvider.CreateDefaultProvider().GetMetadataForType(typeof(TwiceEnumerable));
var strategy = new ExplicitIndexCollectionValidationStrategy(new string[] { "zero", "one", "two" });
// Act
var enumerator = strategy.GetChildren(metadata, "prefix", model);
// Assert
Assert.Collection(
BufferEntries(enumerator).OrderBy(e => e.Key),
e =>
{
Assert.Equal("prefix[one]", e.Key);
Assert.Equal(3, e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
},
e =>
{
Assert.Equal("prefix[two]", e.Key);
Assert.Equal(5, e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
},
e =>
{
Assert.Equal("prefix[zero]", e.Key);
Assert.Equal(2, e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
});
}
[Fact]
public void EnumerateElements_RunOutOfIndices()
{
// Arrange
var model = new List<int>() { 2, 3, 5 };
var metadata = TestModelMetadataProvider.CreateDefaultProvider().GetMetadataForType(typeof(List<int>));
var strategy = new ExplicitIndexCollectionValidationStrategy(new string[] { "zero", "one", });
// Act
var enumerator = strategy.GetChildren(metadata, "prefix", model);
// Assert
Assert.Collection(
BufferEntries(enumerator).OrderBy(e => e.Key),
e =>
{
Assert.Equal("prefix[one]", e.Key);
Assert.Equal(3, e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
},
e =>
{
Assert.Equal("prefix[zero]", e.Key);
Assert.Equal(2, e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
});
}
[Fact]
public void EnumerateElements_RunOutOfElements()
{
// Arrange
var model = new List<int>() { 2, 3, };
var metadata = TestModelMetadataProvider.CreateDefaultProvider().GetMetadataForType(typeof(List<int>));
var strategy = new ExplicitIndexCollectionValidationStrategy(new string[] { "zero", "one", "two" });
// Act
var enumerator = strategy.GetChildren(metadata, "prefix", model);
// Assert
Assert.Collection(
BufferEntries(enumerator).OrderBy(e => e.Key),
e =>
{
Assert.Equal("prefix[one]", e.Key);
Assert.Equal(3, e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
},
e =>
{
Assert.Equal("prefix[zero]", e.Key);
Assert.Equal(2, e.Model);
Assert.Same(metadata.ElementMetadata, e.Metadata);
});
}
// 'int' is chosen by validation because it's declared on the more derived type.
private class TwiceEnumerable : List<string>, IEnumerable<int>
{
private readonly IEnumerable<int> _enumerable;
public TwiceEnumerable(IEnumerable<int> enumerable)
{
_enumerable = enumerable;
}
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
return _enumerable.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new InvalidOperationException();
}
}
private List<ValidationEntry> BufferEntries(IEnumerator<ValidationEntry> enumerator)
{
var entries = new List<ValidationEntry>();
while (enumerator.MoveNext())
{
entries.Add(enumerator.Current);
}
return entries;
}
}
}
| |
// 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 Microsoft.Build.Construction;
using Microsoft.DotNet.Internal.ProjectModel;
using Microsoft.DotNet.Internal.ProjectModel.Graph;
using System.Linq;
using System.IO;
using Newtonsoft.Json.Linq;
using Microsoft.DotNet.Cli.Sln.Internal;
using Microsoft.DotNet.Tools.Common;
using NuGet.Frameworks;
using NuGet.LibraryModel;
namespace Microsoft.DotNet.ProjectJsonMigration
{
internal class ProjectDependencyFinder
{
public IEnumerable<ProjectDependency> ResolveProjectDependencies(
IEnumerable<ProjectContext> projectContexts,
IEnumerable<string> preResolvedProjects = null,
SlnFile solutionFile=null)
{
foreach (var projectContext in projectContexts)
{
foreach (var projectDependency in
ResolveProjectDependencies(projectContext, preResolvedProjects, solutionFile))
{
yield return projectDependency;
}
}
}
public IEnumerable<ProjectDependency> ResolveProjectDependencies(string projectDir,
string xprojFile = null, SlnFile solutionFile = null)
{
var projectContexts = ProjectContext.CreateContextForEachFramework(projectDir);
xprojFile = xprojFile ?? FindXprojFile(projectDir);
ProjectRootElement xproj = null;
if (xprojFile != null)
{
xproj = ProjectRootElement.Open(xprojFile);
}
return ResolveProjectDependencies(
projectContexts,
ResolveXProjProjectDependencyNames(xproj),
solutionFile);
}
public IEnumerable<ProjectDependency> ResolveAllProjectDependenciesForFramework(
ProjectDependency projectToResolve,
NuGetFramework framework,
IEnumerable<string> preResolvedProjects=null,
SlnFile solutionFile=null)
{
var projects = new List<ProjectDependency> { projectToResolve };
var allDependencies = new HashSet<ProjectDependency>();
while (projects.Count > 0)
{
var project = projects.First();
projects.Remove(project);
if (!File.Exists(project.ProjectFilePath))
{
MigrationErrorCodes
.MIGRATE1018(String.Format(LocalizableStrings.MIGRATE1018Arg, project.ProjectFilePath)).Throw();
}
var projectContext =
ProjectContext.CreateContextForEachFramework(project.ProjectFilePath).FirstOrDefault();
if(projectContext == null)
{
continue;
}
var dependencies = ResolveDirectProjectDependenciesForFramework(
projectContext.ProjectFile,
framework,
preResolvedProjects,
solutionFile
);
allDependencies.UnionWith(dependencies);
}
return allDependencies;
}
public IEnumerable<ProjectDependency> ResolveDirectProjectDependenciesForFramework(
Project project,
NuGetFramework framework,
IEnumerable<string> preResolvedProjects=null,
SlnFile solutionFile = null)
{
preResolvedProjects = preResolvedProjects ?? new HashSet<string>();
var possibleProjectDependencies = FindPossibleProjectDependencies(solutionFile, project.ProjectFilePath);
var projectDependencies = new List<ProjectDependency>();
IEnumerable<ProjectLibraryDependency> projectFileDependenciesForFramework;
if (framework == null)
{
projectFileDependenciesForFramework = project.Dependencies;
}
else
{
projectFileDependenciesForFramework = project.GetTargetFramework(framework).Dependencies;
}
foreach (var projectFileDependency in
projectFileDependenciesForFramework.Where(p =>
p.LibraryRange.TypeConstraint == LibraryDependencyTarget.Project ||
p.LibraryRange.TypeConstraint == LibraryDependencyTarget.All))
{
var dependencyName = projectFileDependency.Name;
ProjectDependency projectDependency;
if (preResolvedProjects.Contains(dependencyName))
{
continue;
}
if (!possibleProjectDependencies.TryGetValue(dependencyName, out projectDependency))
{
if (projectFileDependency.LibraryRange.TypeConstraint == LibraryDependencyTarget.Project)
{
MigrationErrorCodes
.MIGRATE1014(String.Format(LocalizableStrings.MIGRATE1014Arg, dependencyName)).Throw();
}
else
{
continue;
}
}
projectDependencies.Add(projectDependency);
}
return projectDependencies;
}
internal IEnumerable<ProjectItemElement> ResolveXProjProjectDependencies(ProjectRootElement xproj)
{
if (xproj == null)
{
MigrationTrace.Instance.WriteLine(String.Format(LocalizableStrings.NoXprojFileGivenError, nameof(ProjectDependencyFinder)));
return Enumerable.Empty<ProjectItemElement>();
}
return xproj.Items
.Where(i => i.ItemType == "ProjectReference")
.Where(p => p.Includes().Any(
include => string.Equals(Path.GetExtension(include), ".csproj", StringComparison.OrdinalIgnoreCase)));
}
internal string FindXprojFile(string projectDirectory)
{
var allXprojFiles = Directory.EnumerateFiles(projectDirectory, "*.xproj", SearchOption.TopDirectoryOnly);
if (allXprojFiles.Count() > 1)
{
MigrationErrorCodes
.MIGRATE1017(String.Format(LocalizableStrings.MultipleXprojFilesError, projectDirectory))
.Throw();
}
return allXprojFiles.FirstOrDefault();
}
private IEnumerable<ProjectDependency> ResolveProjectDependencies(
ProjectContext projectContext,
IEnumerable<string> preResolvedProjects=null,
SlnFile slnFile=null)
{
preResolvedProjects = preResolvedProjects ?? new HashSet<string>();
var projectExports = projectContext.CreateExporter("_").GetDependencies();
var possibleProjectDependencies =
FindPossibleProjectDependencies(slnFile, projectContext.ProjectFile.ProjectFilePath);
var projectDependencies = new List<ProjectDependency>();
foreach (var projectExport in
projectExports.Where(p => p.Library.Identity.Type == LibraryType.Project))
{
var projectExportName = projectExport.Library.Identity.Name;
ProjectDependency projectDependency;
if (preResolvedProjects.Contains(projectExportName))
{
continue;
}
if (!possibleProjectDependencies.TryGetValue(projectExportName, out projectDependency))
{
if (projectExport.Library.Identity.Type.Equals(LibraryType.Project))
{
MigrationErrorCodes
.MIGRATE1014(String.Format(LocalizableStrings.MIGRATE1014Arg, projectExportName)).Throw();
}
else
{
continue;
}
}
projectDependencies.Add(projectDependency);
}
return projectDependencies;
}
private IEnumerable<string> ResolveXProjProjectDependencyNames(ProjectRootElement xproj)
{
var xprojDependencies = ResolveXProjProjectDependencies(xproj).SelectMany(r => r.Includes());
return new HashSet<string>(xprojDependencies.Select(p => Path.GetFileNameWithoutExtension(
PathUtility.GetPathWithDirectorySeparator(p))));
}
private Dictionary<string, ProjectDependency> FindPossibleProjectDependencies(
SlnFile slnFile,
string projectJsonFilePath)
{
var projectRootDirectory = GetRootFromProjectJson(projectJsonFilePath);
var projectSearchPaths = new List<string>();
projectSearchPaths.Add(projectRootDirectory);
var globalPaths = GetGlobalPaths(projectRootDirectory);
projectSearchPaths = globalPaths.Union(projectSearchPaths).ToList();
var solutionPaths = GetSolutionPaths(slnFile);
projectSearchPaths = solutionPaths.Union(projectSearchPaths).ToList();
var projects = new Dictionary<string, ProjectDependency>(StringComparer.Ordinal);
foreach (var project in GetPotentialProjects(projectSearchPaths))
{
if (projects.ContainsKey(project.Name))
{
// Remove the existing project if it doesn't have project.json
// project.json isn't checked until the project is resolved, but here
// we need to check it up front.
var otherProject = projects[project.Name];
if (project.ProjectFilePath != otherProject.ProjectFilePath)
{
var projectExists = File.Exists(project.ProjectFilePath);
var otherExists = File.Exists(otherProject.ProjectFilePath);
if (projectExists != otherExists
&& projectExists
&& !otherExists)
{
// the project currently in the cache does not exist, but this one does
// remove the old project and add the current one
projects[project.Name] = project;
}
}
}
else
{
projects.Add(project.Name, project);
}
}
return projects;
}
/// <summary>
/// Finds the parent directory of the project.json.
/// </summary>
/// <param name="projectJsonPath">Full path to project.json.</param>
private static string GetRootFromProjectJson(string projectJsonPath)
{
if (!string.IsNullOrEmpty(projectJsonPath))
{
var file = new FileInfo(projectJsonPath);
// If for some reason we are at the root of the drive this will be null
// Use the file directory instead.
if (file.Directory.Parent == null)
{
return file.Directory.FullName;
}
else
{
return file.Directory.Parent.FullName;
}
}
return projectJsonPath;
}
/// <summary>
/// Create the list of potential projects from the search paths.
/// </summary>
private static List<ProjectDependency> GetPotentialProjects(
IEnumerable<string> searchPaths)
{
var projects = new List<ProjectDependency>();
// Resolve all of the potential projects
foreach (var searchPath in searchPaths)
{
var directory = new DirectoryInfo(searchPath);
if (!directory.Exists)
{
continue;
}
foreach (var projectDirectory in
Enumerable.Repeat(directory, 1).Union(directory.GetDirectories("*", SearchOption.AllDirectories)))
{
AddIfProjectExists(projects, projectDirectory);
}
}
return projects;
}
private static void AddIfProjectExists(List<ProjectDependency> projects, DirectoryInfo projectDirectory)
{
var projectJSONFilePath = Path.Combine(projectDirectory.FullName, "project.json");
var csProjFilePath = Path.Combine(projectDirectory.FullName, $"{projectDirectory.Name}.csproj");
if (File.Exists(projectJSONFilePath))
{
var project = new ProjectDependency(projectDirectory.Name, projectJSONFilePath);
projects.Add(project);
}
else if (File.Exists(csProjFilePath))
{
var project = new ProjectDependency(projectDirectory.Name, csProjFilePath);
projects.Add(project);
}
}
internal static List<string> GetGlobalPaths(string rootPath)
{
var paths = new List<string>();
var globalJsonRoot = ResolveRootDirectory(rootPath);
GlobalSettings globalSettings;
if (GlobalSettings.TryGetGlobalSettings(globalJsonRoot, out globalSettings))
{
foreach (var sourcePath in globalSettings.ProjectPaths)
{
var path = Path.GetFullPath(Path.Combine(globalJsonRoot, sourcePath));
paths.Add(path);
}
}
return paths;
}
internal static List<string> GetSolutionPaths(SlnFile solutionFile)
{
return (solutionFile == null)
? new List<string>()
: new List<string>(solutionFile.Projects.Select(p =>
Path.Combine(solutionFile.BaseDirectory, Path.GetDirectoryName(p.FilePath))));
}
private static string ResolveRootDirectory(string projectPath)
{
var di = new DirectoryInfo(projectPath);
while (di.Parent != null)
{
var globalJsonPath = Path.Combine(di.FullName, GlobalSettings.GlobalFileName);
if (File.Exists(globalJsonPath))
{
return di.FullName;
}
di = di.Parent;
}
// If we don't find any files then make the project folder the root
return projectPath;
}
private class GlobalSettings
{
public const string GlobalFileName = "global.json";
public IList<string> ProjectPaths { get; private set; }
public string PackagesPath { get; private set; }
public string FilePath { get; private set; }
public string RootPath
{
get { return Path.GetDirectoryName(FilePath); }
}
public static bool TryGetGlobalSettings(string path, out GlobalSettings globalSettings)
{
globalSettings = null;
string globalJsonPath = null;
if (Path.GetFileName(path) == GlobalFileName)
{
globalJsonPath = path;
path = Path.GetDirectoryName(path);
}
else if (!HasGlobalFile(path))
{
return false;
}
else
{
globalJsonPath = Path.Combine(path, GlobalFileName);
}
globalSettings = new GlobalSettings();
try
{
var json = File.ReadAllText(globalJsonPath);
JObject settings = JObject.Parse(json);
var projects = settings["projects"];
var dependencies = settings["dependencies"] as JObject;
globalSettings.ProjectPaths = projects == null ? new string[] { } :
projects.Select(a => a.Value<string>()).ToArray();
globalSettings.PackagesPath = settings.Value<string>("packages");
globalSettings.FilePath = globalJsonPath;
}
catch (Exception ex)
{
throw FileFormatException.Create(ex, globalJsonPath);
}
return true;
}
public static bool HasGlobalFile(string path)
{
var projectPath = Path.Combine(path, GlobalFileName);
return File.Exists(projectPath);
}
}
}
}
| |
/*++
Copyright (c) Microsoft Corporation
Module Name:
_RequestCacheProtocol.cs
Abstract:
The class is a cache protocol engine.
An application protocol such as HttpWebRequest or FtpWebRequest
gets all cache-related answers by talking to this class
Sometime in the future it will become public.
Author:
Alexei Vopilov 21-Dec-2002
Revision History:
Aug 25 2003 - moved into separate file and revised as per Whidbey-M3 spec.
--*/
namespace System.Net.Cache {
using System;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using System.Threading;
using System.Globalization;
//
//
//
internal class RequestCacheProtocol {
private CacheValidationStatus _ProtocolStatus;
private Exception _ProtocolException;
private Stream _ResponseStream;
private long _ResponseStreamLength;
private RequestCacheValidator _Validator;
private RequestCache _RequestCache;
private bool _IsCacheFresh;
private bool _CanTakeNewRequest;
// private string[] _ResponseMetadata;
// private string _CacheRetrieveKey;
// private string _CacheStoreKey;
//
// Public properties
//
internal CacheValidationStatus ProtocolStatus {get {return _ProtocolStatus;}}
internal Exception ProtocolException {get {return _ProtocolException;}}
internal Stream ResponseStream {get {return _ResponseStream;}}
internal long ResponseStreamLength {get {return _ResponseStreamLength;}}
internal RequestCacheValidator Validator {get {return _Validator;}}
internal bool IsCacheFresh {get {return _Validator != null && _Validator.CacheFreshnessStatus == CacheFreshnessStatus.Fresh;}}
// internal string[] ResponseMetadata {get {return _ResponseMetadata;}}
// internal string CacheRetrieveKey {get {return _CacheRetrieveKey;}}
// internal string CacheStoreKey {get {return _CacheStoreKey;}}
//
// Public methods
//
internal RequestCacheProtocol(RequestCache cache, RequestCacheValidator defaultValidator)
{
_RequestCache = cache;
_Validator = defaultValidator;
_CanTakeNewRequest = true;
}
//
internal CacheValidationStatus GetRetrieveStatus (Uri cacheUri, WebRequest request)
{
if (cacheUri == null)
throw new ArgumentNullException("cacheUri");
if (request == null)
throw new ArgumentNullException("request");
if (!_CanTakeNewRequest || _ProtocolStatus == CacheValidationStatus.RetryResponseFromServer)
return CacheValidationStatus.Continue;
_CanTakeNewRequest = false;
// Reset protocol state
_ResponseStream = null;
_ResponseStreamLength = 0L;
_ProtocolStatus = CacheValidationStatus.Continue;
_ProtocolException = null;
if(Logging.On) Logging.Enter(Logging.RequestCache, this, "GetRetrieveStatus", request);
try {
if (request.CachePolicy == null || request.CachePolicy.Level == RequestCacheLevel.BypassCache)
{
_ProtocolStatus = CacheValidationStatus.DoNotUseCache;
return _ProtocolStatus;
}
if (_RequestCache == null || _Validator == null)
{
_ProtocolStatus = CacheValidationStatus.DoNotUseCache;
return _ProtocolStatus;
}
_Validator.FetchRequest(cacheUri, request);
switch(_ProtocolStatus = ValidateRequest())
{
case CacheValidationStatus.Continue: // This is a green light for cache protocol
break;
case CacheValidationStatus.DoNotTakeFromCache: // no cache but response can be cached
case CacheValidationStatus.DoNotUseCache: // ignore cache entirely
break;
case CacheValidationStatus.Fail:
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_fail, "ValidateRequest"));
break;
default:
_ProtocolStatus = CacheValidationStatus.Fail;
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_result, "ValidateRequest", _Validator.ValidationStatus.ToString()));
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_unexpected_status, "ValidateRequest()", _Validator.ValidationStatus.ToString()));
break;
}
if (_ProtocolStatus != CacheValidationStatus.Continue)
return _ProtocolStatus;
//
// Proceed with validation
//
CheckRetrieveBeforeSubmit();
}
catch (Exception e) {
_ProtocolException = e;
_ProtocolStatus = CacheValidationStatus.Fail;
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
throw;
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_object_and_exception, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), (e is WebException? e.Message: e.ToString())));
}
finally {
if(Logging.On) Logging.Exit(Logging.RequestCache, this, "GetRetrieveStatus", "result = " + _ProtocolStatus.ToString());
}
return _ProtocolStatus;
}
//
// This optional method is only for protocols supporting a revalidation concept
// For a retried request this method must be called again.
//
internal CacheValidationStatus GetRevalidateStatus (WebResponse response, Stream responseStream)
{
if (response == null)
throw new ArgumentNullException("response");
if (_ProtocolStatus == CacheValidationStatus.DoNotUseCache)
return CacheValidationStatus.DoNotUseCache;
// If we returned cached response, switch the state to not call cache anymore.
if (_ProtocolStatus == CacheValidationStatus.ReturnCachedResponse)
{
_ProtocolStatus = CacheValidationStatus.DoNotUseCache;
return _ProtocolStatus;
}
try {
if(Logging.On) Logging.Enter(Logging.RequestCache, this, "GetRevalidateStatus", (_Validator == null? null: _Validator.Request));
_Validator.FetchResponse(response);
if (_ProtocolStatus != CacheValidationStatus.Continue && _ProtocolStatus != CacheValidationStatus.RetryResponseFromServer)
{
if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_revalidation_not_needed, "GetRevalidateStatus()"));
return _ProtocolStatus;
}
CheckRetrieveOnResponse(responseStream);
}
finally {
if(Logging.On) Logging.Exit(Logging.RequestCache, this, "GetRevalidateStatus", "result = " + _ProtocolStatus.ToString());
}
return _ProtocolStatus;
}
//
// Returns UpdateResponseInformation if passed response stream has to be replaced (cache is updated in some way)
// Returns Fail if request is to fail
// Any other return value should be ignored
//
internal CacheValidationStatus GetUpdateStatus (WebResponse response, Stream responseStream)
{
if (response == null)
throw new ArgumentNullException("response");
if (_ProtocolStatus == CacheValidationStatus.DoNotUseCache)
return CacheValidationStatus.DoNotUseCache;
try {
if(Logging.On) Logging.Enter(Logging.RequestCache, this, "GetUpdateStatus", null);
if (_Validator.Response == null)
_Validator.FetchResponse(response);
if (_ProtocolStatus == CacheValidationStatus.RemoveFromCache)
{
EnsureCacheRemoval(_Validator.CacheKey);
return _ProtocolStatus;
}
if (_ProtocolStatus != CacheValidationStatus.DoNotTakeFromCache &&
_ProtocolStatus != CacheValidationStatus.ReturnCachedResponse &&
_ProtocolStatus != CacheValidationStatus.CombineCachedAndServerResponse)
{
if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_not_updated_based_on_cache_protocol_status, "GetUpdateStatus()", _ProtocolStatus.ToString()));
return _ProtocolStatus;
}
CheckUpdateOnResponse(responseStream);
}
catch (Exception e) {
_ProtocolException = e;
_ProtocolStatus = CacheValidationStatus.Fail;
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_object_and_exception, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), (e is WebException? e.Message: e.ToString())));
}
finally {
if(Logging.On)Logging.Exit(Logging.RequestCache, this, "GetUpdateStatus", "result = " + _ProtocolStatus.ToString());
}
return _ProtocolStatus;
}
//
// This must be the last call before starting a new request on this protocol instance
//
internal void Reset()
{
_CanTakeNewRequest = true;
}
//
internal void Abort()
{
// if _CanTakeNewRequest==true we should not be holding any cache stream
// Also we check on Abort() reentrancy this way.
if (_CanTakeNewRequest)
return;
// in case of abnormal termination this will release cache entry sooner than does it's finalizer
Stream stream = _ResponseStream;
if (stream != null)
{
try {
if(Logging.On) Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_closing_cache_stream, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), "Abort()", stream.GetType().FullName, _Validator.CacheKey));
ICloseEx closeEx = stream as ICloseEx;
if (closeEx != null)
closeEx.CloseEx(CloseExState.Abort | CloseExState.Silent);
else
stream.Close();
}
catch(Exception e) {
if (NclUtilities.IsFatal(e)) throw;
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_exception_ignored, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), "stream.Close()", e.ToString()));
}
}
Reset();
}
//
// Private methods
//
//
// This method may be invoked as part of the request submission but before issuing a live request
//
private void CheckRetrieveBeforeSubmit() {
GlobalLog.Assert(_ProtocolStatus == CacheValidationStatus.Continue, "CheckRetrieveBeforeSubmit()|Unexpected _ProtocolStatus = {0}", _ProtocolStatus);
try {
while (true)
{
RequestCacheEntry cacheEntry;
if (_Validator.CacheStream != null && _Validator.CacheStream != Stream.Null)
{
// Reset to Initial state
_Validator.CacheStream.Close();
_Validator.CacheStream = Stream.Null;
}
if (_Validator.StrictCacheErrors)
{
_Validator.CacheStream = _RequestCache.Retrieve(_Validator.CacheKey, out cacheEntry);
}
else
{
Stream stream;
_RequestCache.TryRetrieve(_Validator.CacheKey, out cacheEntry, out stream);
_Validator.CacheStream = stream;
}
if (cacheEntry == null)
{
cacheEntry = new RequestCacheEntry();
cacheEntry.IsPrivateEntry = _RequestCache.IsPrivateCache;
_Validator.FetchCacheEntry(cacheEntry);
}
if (_Validator.CacheStream == null)
{
// If entry does not have a stream an empty stream wrapper must be returned.
// A null or Stream.Null value stands for non existent cache entry.
_Validator.CacheStream = Stream.Null;
}
ValidateFreshness(cacheEntry);
_ProtocolStatus = ValidateCache();
// This will tell us what to do next
switch (_ProtocolStatus) {
case CacheValidationStatus.ReturnCachedResponse:
if (_Validator.CacheStream == null || _Validator.CacheStream == Stream.Null)
{
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_no_cache_entry, "ValidateCache()"));
_ProtocolStatus = CacheValidationStatus.Fail;
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_no_stream, _Validator.CacheKey));
break;
}
// Final decision is made, check on a range response from cache
Stream stream = _Validator.CacheStream;
// The entry can now be replaced as we are not going for cache entry metadata-only update
_RequestCache.UnlockEntry(_Validator.CacheStream);
if (_Validator.CacheStreamOffset != 0L || _Validator.CacheStreamLength != _Validator.CacheEntry.StreamSize)
{
stream = new RangeStream(stream, _Validator.CacheStreamOffset, _Validator.CacheStreamLength);
if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_returned_range_cache, "ValidateCache()", _Validator.CacheStreamOffset, _Validator.CacheStreamLength));
}
_ResponseStream = stream;
_ResponseStreamLength = _Validator.CacheStreamLength;
break;
case CacheValidationStatus.Continue:
// copy a cache stream ref
_ResponseStream = _Validator.CacheStream;
break;
case CacheValidationStatus.RetryResponseFromCache:
// loop thought cache retrieve
continue;
case CacheValidationStatus.DoNotTakeFromCache:
case CacheValidationStatus.DoNotUseCache:
break;
case CacheValidationStatus.Fail:
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_fail, "ValidateCache"));
break;
default:
_ProtocolStatus = CacheValidationStatus.Fail;
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_result, "ValidateCache", _Validator.ValidationStatus.ToString()));
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_unexpected_status, "ValidateCache()", _Validator.ValidationStatus.ToString()));
break;
}
break;
}
}
catch (Exception e) {
_ProtocolStatus = CacheValidationStatus.Fail;
_ProtocolException = e;
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_object_and_exception, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), (e is WebException? e.Message: e.ToString())));
}
finally {
// This is to release cache entry on error
if (_ResponseStream == null && _Validator.CacheStream != null && _Validator.CacheStream != Stream.Null)
{
_Validator.CacheStream.Close();
_Validator.CacheStream = Stream.Null;
}
}
}
//
private void CheckRetrieveOnResponse(Stream responseStream) {
GlobalLog.Assert(_ProtocolStatus == CacheValidationStatus.Continue || _ProtocolStatus == CacheValidationStatus.RetryResponseFromServer, "CheckRetrieveOnResponse()|Unexpected _ProtocolStatus = ", _ProtocolStatus);
// if something goes wrong we release cache stream if any exists
bool closeCacheStream = true;
try {
// This will inspect the live response on the correctness matter
switch (_ProtocolStatus = ValidateResponse()) {
case CacheValidationStatus.Continue:
closeCacheStream = false;
// The response looks good
break;
case CacheValidationStatus.RetryResponseFromServer:
// The response is broken will need to retry or give up
closeCacheStream = false;
break;
case CacheValidationStatus.Fail:
_ProtocolStatus = CacheValidationStatus.Fail;
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_fail, "ValidateResponse"));
break;
case CacheValidationStatus.DoNotUseCache:
break;
default:
_ProtocolStatus = CacheValidationStatus.Fail;
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_result, "ValidateResponse", _Validator.ValidationStatus.ToString()));
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_unexpected_status, "ValidateResponse()", _Validator.ValidationStatus.ToString()));
break;
}
}
catch (Exception e) {
closeCacheStream = true;
_ProtocolException = e;
_ProtocolStatus = CacheValidationStatus.Fail;
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_object_and_exception, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), (e is WebException? e.Message: e.ToString())));
}
finally {
// This is to release cache entry in case we are not interested in it
if (closeCacheStream && _ResponseStream != null)
{
_ResponseStream.Close();
_ResponseStream = null;
_Validator.CacheStream = Stream.Null;
}
}
if (_ProtocolStatus != CacheValidationStatus.Continue) {
return;
}
//
// only CacheValidationStatus.Continue goes here with closeCacheStream == false
//
try {
// This will tell us what to do next
// Note this is a second time question to the caching protocol about a cached entry
// Except that we now have live response to consider
//
// The validator can at any time replace the cache stream and update cache Metadata (aka headers).
//
switch (_ProtocolStatus = RevalidateCache()) {
case CacheValidationStatus.DoNotUseCache:
case CacheValidationStatus.RemoveFromCache:
case CacheValidationStatus.DoNotTakeFromCache:
closeCacheStream = true;
break;
case CacheValidationStatus.ReturnCachedResponse:
if (_Validator.CacheStream == null || _Validator.CacheStream == Stream.Null)
{
_ProtocolStatus = CacheValidationStatus.Fail;
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_no_stream, _Validator.CacheKey));
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_null_cached_stream, "RevalidateCache()"));
break;
}
Stream stream = _Validator.CacheStream;
if (_Validator.CacheStreamOffset != 0L || _Validator.CacheStreamLength != _Validator.CacheEntry.StreamSize)
{
stream = new RangeStream(stream, _Validator.CacheStreamOffset, _Validator.CacheStreamLength);
if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_returned_range_cache, "RevalidateCache()", _Validator.CacheStreamOffset, _Validator.CacheStreamLength));
}
_ResponseStream = stream;
_ResponseStreamLength = _Validator.CacheStreamLength;
break;
case CacheValidationStatus.CombineCachedAndServerResponse:
if (_Validator.CacheStream == null || _Validator.CacheStream == Stream.Null)
{
_ProtocolStatus = CacheValidationStatus.Fail;
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_no_stream, _Validator.CacheKey));
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_requested_combined_but_null_cached_stream, "RevalidateCache()"));
break;
}
//
// FTP cannot give the tail of the combined stream at that point
// Consider: Revisit the design of the CacheProtocol class
if (responseStream != null)
{
stream = new CombinedReadStream(_Validator.CacheStream, responseStream);
}
else
{
// So Abort can close the cache stream
stream = _Validator.CacheStream;
}
_ResponseStream = stream;
_ResponseStreamLength = _Validator.CacheStreamLength;
break;
case CacheValidationStatus.Fail:
closeCacheStream = true;
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_fail, "RevalidateCache"));
break;
default:
closeCacheStream = true;
_ProtocolStatus = CacheValidationStatus.Fail;
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_result, "RevalidateCache", _Validator.ValidationStatus.ToString()));
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_unexpected_status, "RevalidateCache()", _Validator.ValidationStatus.ToString()));
break;
}
}
catch (Exception e) {
closeCacheStream = true;
_ProtocolException = e;
_ProtocolStatus = CacheValidationStatus.Fail;
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_object_and_exception, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), (e is WebException? e.Message: e.ToString())));
}
finally {
// This is to release cache entry in case we are not interested in it
if (closeCacheStream && _ResponseStream != null)
{
_ResponseStream.Close();
_ResponseStream = null;
_Validator.CacheStream = Stream.Null;
}
}
}
//
// This will decide on cache update and construct the effective response stream
//
private void CheckUpdateOnResponse(Stream responseStream)
{
if (_Validator.CacheEntry == null)
{
// There was no chance to create an empty entry yet
RequestCacheEntry cacheEntry = new RequestCacheEntry();
cacheEntry.IsPrivateEntry = _RequestCache.IsPrivateCache;
_Validator.FetchCacheEntry(cacheEntry);
}
// With NoCache we may end up storing whole response as a new entry in Cache.
// Otherwise we may end up updating Context+Metadata or just Context
//
// In any case we may end up doing nothing.
//
string retrieveKey = _Validator.CacheKey;
bool unlockEntry = true;
try {
switch (_ProtocolStatus=UpdateCache()) {
case CacheValidationStatus.RemoveFromCache:
EnsureCacheRemoval(retrieveKey);
unlockEntry = false;
break;
case CacheValidationStatus.UpdateResponseInformation:
// NB: Just invoked validator must have updated CacheEntry and transferred
// ONLY allowed headers from the response to the Context.xxxMetadata member
_ResponseStream = new MetadataUpdateStream(
responseStream,
_RequestCache,
_Validator.CacheKey,
_Validator.CacheEntry.ExpiresUtc,
_Validator.CacheEntry.LastModifiedUtc,
_Validator.CacheEntry.LastSynchronizedUtc,
_Validator.CacheEntry.MaxStale,
_Validator.CacheEntry.EntryMetadata,
_Validator.CacheEntry.SystemMetadata,
_Validator.StrictCacheErrors);
//
// This can be looked as a design hole since we have to keep the entry
// locked for the case when we want to update that previously retrieved entry.
// I think RequestCache contract should allow to detect that a new physical cache entry
// does not match to the "entry being updated" and so to should ignore updates on replaced entries.
//
unlockEntry = false;
_ProtocolStatus = CacheValidationStatus.UpdateResponseInformation;
break;
case CacheValidationStatus.CacheResponse:
// NB: Just invoked validator must have updated CacheEntry and transferred
// ONLY allowed headers from the response to the Context.xxxMetadata member
Stream stream;
if (_Validator.StrictCacheErrors)
{stream = _RequestCache.Store(_Validator.CacheKey, _Validator.CacheEntry.StreamSize, _Validator.CacheEntry.ExpiresUtc, _Validator.CacheEntry.LastModifiedUtc, _Validator.CacheEntry.MaxStale, _Validator.CacheEntry.EntryMetadata, _Validator.CacheEntry.SystemMetadata);}
else
{_RequestCache.TryStore(_Validator.CacheKey, _Validator.CacheEntry.StreamSize, _Validator.CacheEntry.ExpiresUtc, _Validator.CacheEntry.LastModifiedUtc, _Validator.CacheEntry.MaxStale, _Validator.CacheEntry.EntryMetadata, _Validator.CacheEntry.SystemMetadata, out stream);}
// Wrap the response stream into forwarding one
if (stream == null) {
_ProtocolStatus = CacheValidationStatus.DoNotUpdateCache;
}
else {
_ResponseStream = new ForwardingReadStream(responseStream, stream, _Validator.CacheStreamOffset, _Validator.StrictCacheErrors);
_ProtocolStatus = CacheValidationStatus.UpdateResponseInformation;
}
break;
case CacheValidationStatus.DoNotUseCache:
case CacheValidationStatus.DoNotUpdateCache:
break;
case CacheValidationStatus.Fail:
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_fail, "UpdateCache"));
break;
default:
_ProtocolStatus = CacheValidationStatus.Fail;
_ProtocolException = new InvalidOperationException(SR.GetString(SR.net_cache_validator_result, "UpdateCache", _Validator.ValidationStatus.ToString()));
if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_unexpected_status, "UpdateCache()", _Validator.ValidationStatus.ToString()));
break;
}
}
finally {
if (unlockEntry)
{
// The entry can now be replaced as we are not going for cache entry metadata-only update
_RequestCache.UnlockEntry(_Validator.CacheStream);
}
}
}
//
private CacheValidationStatus ValidateRequest() {
if(Logging.On) Logging.PrintInfo(Logging.RequestCache,
"Request#" + _Validator.Request.GetHashCode().ToString(NumberFormatInfo.InvariantInfo) +
", Policy = " + _Validator.Request.CachePolicy.ToString() +
", Cache Uri = " + _Validator.Uri);
CacheValidationStatus result = _Validator.ValidateRequest();
_Validator.SetValidationStatus(result);
if(Logging.On) Logging.PrintInfo(Logging.RequestCache, "Selected cache Key = " + _Validator.CacheKey);
return result;
}
//
//
//
private void ValidateFreshness(RequestCacheEntry fetchEntry) {
_Validator.FetchCacheEntry(fetchEntry);
if (_Validator.CacheStream == null || _Validator.CacheStream == Stream.Null) {
if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_entry_not_found_freshness_undefined, "ValidateFreshness()"));
_Validator.SetFreshnessStatus(CacheFreshnessStatus.Undefined);
return;
}
if(Logging.On) {
if (Logging.IsVerbose(Logging.RequestCache)) {
Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_dumping_cache_context));
if (fetchEntry == null) {
Logging.PrintInfo(Logging.RequestCache, "<null>");
}
else {
string[] context = fetchEntry.ToString(Logging.IsVerbose(Logging.RequestCache)).Split(RequestCache.LineSplits);
for (int i = 0; i< context.Length; ++i) {
if (context[i].Length != 0) {
Logging.PrintInfo(Logging.RequestCache, context[i]);
}
}
}
}
}
CacheFreshnessStatus result = _Validator.ValidateFreshness();
_Validator.SetFreshnessStatus(result);
_IsCacheFresh = result == CacheFreshnessStatus.Fresh;
if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_result, "ValidateFreshness()", result.ToString()));
}
//
//
//
private CacheValidationStatus ValidateCache() {
CacheValidationStatus result = _Validator.ValidateCache();
_Validator.SetValidationStatus(result);
if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_result, "ValidateCache()", result.ToString()));
return result;
}
//
private CacheValidationStatus RevalidateCache() {
CacheValidationStatus result = _Validator.RevalidateCache();
_Validator.SetValidationStatus(result);
if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_result, "RevalidateCache()", result.ToString()));
return result;
}
//
private CacheValidationStatus ValidateResponse()
{
CacheValidationStatus result = _Validator.ValidateResponse();
_Validator.SetValidationStatus(result);
if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_result, "ValidateResponse()", result.ToString()));
return result;
}
//
private CacheValidationStatus UpdateCache()
{
CacheValidationStatus result = _Validator.UpdateCache();
_Validator.SetValidationStatus(result);
return result;
}
//
private void EnsureCacheRemoval(string retrieveKey)
{
// The entry can now be replaced as we are not going for cache entry metadata-only update
_RequestCache.UnlockEntry(_Validator.CacheStream);
if (_Validator.StrictCacheErrors)
{_RequestCache.Remove(retrieveKey);}
else
{_RequestCache.TryRemove(retrieveKey);}
// We may need to remove yet another reference from the cache
if (retrieveKey != _Validator.CacheKey)
{
if (_Validator.StrictCacheErrors)
{_RequestCache.Remove(_Validator.CacheKey);}
else
{_RequestCache.TryRemove(_Validator.CacheKey);}
}
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Xunit;
namespace OpenIddict.Server.Tests;
public class OpenIddictServerExtensionsTests
{
[Fact]
public void AddServer_ThrowsAnExceptionForNullBuilder()
{
// Arrange
var builder = (OpenIddictBuilder) null!;
// Act and assert
var exception = Assert.Throws<ArgumentNullException>(() => builder.AddServer());
Assert.Equal("builder", exception.ParamName);
}
[Fact]
public void AddServer_ThrowsAnExceptionForNullConfiguration()
{
// Arrange
var services = new ServiceCollection();
var builder = new OpenIddictBuilder(services);
// Act and assert
var exception = Assert.Throws<ArgumentNullException>(() => builder.AddServer(configuration: null!));
Assert.Equal("configuration", exception.ParamName);
}
[Fact]
public void AddServer_RegistersLoggingServices()
{
// Arrange
var services = new ServiceCollection();
var builder = new OpenIddictBuilder(services);
// Act
builder.AddServer();
// Assert
Assert.Contains(services, service => service.ServiceType == typeof(ILogger<>));
}
[Fact]
public void AddServer_RegistersOptionsServices()
{
// Arrange
var services = new ServiceCollection();
var builder = new OpenIddictBuilder(services);
// Act
builder.AddServer();
// Assert
Assert.Contains(services, service => service.ServiceType == typeof(IOptions<>));
}
[Fact]
public void AddServer_RegistersServerDispatcher()
{
// Arrange
var services = new ServiceCollection();
var builder = new OpenIddictBuilder(services);
// Act
builder.AddServer();
// Assert
Assert.Contains(services, service => service.ServiceType == typeof(IOpenIddictServerDispatcher) &&
service.ImplementationType == typeof(OpenIddictServerDispatcher) &&
service.Lifetime == ServiceLifetime.Scoped);
}
[Fact]
public void AddServer_RegistersServerFactory()
{
// Arrange
var services = new ServiceCollection();
var builder = new OpenIddictBuilder(services);
// Act
builder.AddServer();
// Assert
Assert.Contains(services, service => service.ServiceType == typeof(IOpenIddictServerFactory) &&
service.ImplementationType == typeof(OpenIddictServerFactory) &&
service.Lifetime == ServiceLifetime.Scoped);
}
public static IEnumerable<object[]> DefaultHandlers
=> OpenIddictServerHandlers.DefaultHandlers.Select(descriptor => new object[] { descriptor });
[Theory]
[MemberData(nameof(DefaultHandlers))]
public void AddServer_RegistersDefaultHandler(OpenIddictServerHandlerDescriptor descriptor)
{
// Arrange
var services = new ServiceCollection();
var builder = new OpenIddictBuilder(services);
// Act
builder.AddServer();
// Assert
Assert.Contains(services, service => service.Lifetime == descriptor.ServiceDescriptor.Lifetime &&
service.ServiceType == descriptor.ServiceDescriptor.ServiceType &&
service.ImplementationType == descriptor.ServiceDescriptor.ImplementationType);
}
[Theory]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireAuthorizationStorageEnabled))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireAuthorizationRequest))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireClientIdParameter))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireConfigurationRequest))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireCryptographyRequest))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireDegradedModeDisabled))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireDeviceRequest))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireEndpointPermissionsEnabled))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireGrantTypePermissionsEnabled))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireIntrospectionRequest))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireLogoutRequest))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequirePostLogoutRedirectUriParameter))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireReferenceAccessTokensEnabled))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireReferenceRefreshTokensEnabled))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireRevocationRequest))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireSlidingRefreshTokenExpirationEnabled))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireScopePermissionsEnabled))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireScopeValidationEnabled))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireTokenStorageEnabled))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireTokenRequest))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireUserinfoRequest))]
[InlineData(typeof(OpenIddictServerHandlerFilters.RequireVerificationRequest))]
public void AddServer_RegistersRequiredSingletons(Type type)
{
// Arrange
var services = new ServiceCollection();
var builder = new OpenIddictBuilder(services);
// Act
builder.AddServer();
// Assert
Assert.Contains(services, service => service.ServiceType == type &&
service.ImplementationType == type &&
service.Lifetime == ServiceLifetime.Singleton);
}
[Fact]
public void AddServer_ResolvingProviderThrowsAnExceptionWhenCoreServicesAreNotRegistered()
{
// Arrange
var services = new ServiceCollection();
var builder = new OpenIddictBuilder(services);
// Act
builder.AddServer();
// Assert
var provider = services.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() => provider.GetRequiredService<OpenIddictServerConfiguration>());
Assert.NotNull(exception);
}
[Theory]
[InlineData(typeof(IPostConfigureOptions<OpenIddictServerOptions>), typeof(OpenIddictServerConfiguration))]
public void AddServer_RegistersConfiguration(Type serviceType, Type implementationType)
{
// Arrange
var services = new ServiceCollection();
var builder = new OpenIddictBuilder(services);
// Act
builder.AddServer();
// Assert
Assert.Contains(services, service => service.ServiceType == serviceType &&
service.ImplementationType == implementationType);
}
[Fact]
public void AddServer_CanBeSafelyInvokedMultipleTimes()
{
// Arrange
var services = new ServiceCollection();
var builder = new OpenIddictBuilder(services);
// Act and assert
builder.AddServer();
builder.AddServer();
builder.AddServer();
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace Lucene.Net.Util.Automaton
{
/*
* 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 PrefixTermsEnum = Lucene.Net.Search.PrefixTermsEnum;
using SingleTermsEnum = Lucene.Net.Index.SingleTermsEnum;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
/// <summary>
/// Immutable class holding compiled details for a given
/// <see cref="Automaton"/>. The <see cref="Automaton"/> is deterministic, must not have
/// dead states but is not necessarily minimal.
/// <para/>
/// @lucene.experimental
/// </summary>
public class CompiledAutomaton
{
/// <summary>
/// Automata are compiled into different internal forms for the
/// most efficient execution depending upon the language they accept.
/// </summary>
public enum AUTOMATON_TYPE
{
/// <summary>
/// Automaton that accepts no strings. </summary>
NONE,
/// <summary>
/// Automaton that accepts all possible strings. </summary>
ALL,
/// <summary>
/// Automaton that accepts only a single fixed string. </summary>
SINGLE,
/// <summary>
/// Automaton that matches all strings with a constant prefix. </summary>
PREFIX,
/// <summary>
/// Catch-all for any other automata. </summary>
NORMAL
}
public AUTOMATON_TYPE Type { get; private set; }
/// <summary>
/// For <see cref="AUTOMATON_TYPE.PREFIX"/>, this is the prefix term;
/// for <see cref="AUTOMATON_TYPE.SINGLE"/> this is the singleton term.
/// </summary>
public BytesRef Term { get; private set; }
/// <summary>
/// Matcher for quickly determining if a <see cref="T:byte[]"/> is accepted.
/// only valid for <see cref="AUTOMATON_TYPE.NORMAL"/>.
/// </summary>
public ByteRunAutomaton RunAutomaton { get; private set; }
// TODO: would be nice if these sortedTransitions had "int
// to;" instead of "State to;" somehow:
/// <summary>
/// Two dimensional array of transitions, indexed by state
/// number for traversal. The state numbering is consistent with
/// <see cref="RunAutomaton"/>.
/// <para/>
/// Only valid for <see cref="AUTOMATON_TYPE.NORMAL"/>.
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public Transition[][] SortedTransitions => sortedTransitions;
private readonly Transition[][] sortedTransitions;
/// <summary>
/// Shared common suffix accepted by the automaton. Only valid
/// for <see cref="AUTOMATON_TYPE.NORMAL"/>, and only when the
/// automaton accepts an infinite language.
/// </summary>
public BytesRef CommonSuffixRef { get; private set; }
/// <summary>
/// Indicates if the automaton accepts a finite set of strings.
/// Null if this was not computed.
/// Only valid for <see cref="AUTOMATON_TYPE.NORMAL"/>.
/// </summary>
public bool? Finite { get; private set; }
public CompiledAutomaton(Automaton automaton)
: this(automaton, null, true)
{
}
public CompiledAutomaton(Automaton automaton, bool? finite, bool simplify)
{
if (simplify)
{
// Test whether the automaton is a "simple" form and
// if so, don't create a runAutomaton. Note that on a
// large automaton these tests could be costly:
if (BasicOperations.IsEmpty(automaton))
{
// matches nothing
Type = AUTOMATON_TYPE.NONE;
Term = null;
CommonSuffixRef = null;
RunAutomaton = null;
sortedTransitions = null;
this.Finite = null;
return;
}
else if (BasicOperations.IsTotal(automaton))
{
// matches all possible strings
Type = AUTOMATON_TYPE.ALL;
Term = null;
CommonSuffixRef = null;
RunAutomaton = null;
sortedTransitions = null;
this.Finite = null;
return;
}
else
{
string commonPrefix;
string singleton;
if (automaton.Singleton == null)
{
commonPrefix = SpecialOperations.GetCommonPrefix(automaton);
if (commonPrefix.Length > 0 && BasicOperations.SameLanguage(automaton, BasicAutomata.MakeString(commonPrefix)))
{
singleton = commonPrefix;
}
else
{
singleton = null;
}
}
else
{
commonPrefix = null;
singleton = automaton.Singleton;
}
if (singleton != null)
{
// matches a fixed string in singleton or expanded
// representation
Type = AUTOMATON_TYPE.SINGLE;
Term = new BytesRef(singleton);
CommonSuffixRef = null;
RunAutomaton = null;
sortedTransitions = null;
this.Finite = null;
return;
}
else if (BasicOperations.SameLanguage(automaton, BasicOperations.Concatenate(BasicAutomata.MakeString(commonPrefix), BasicAutomata.MakeAnyString())))
{
// matches a constant prefix
Type = AUTOMATON_TYPE.PREFIX;
Term = new BytesRef(commonPrefix);
CommonSuffixRef = null;
RunAutomaton = null;
sortedTransitions = null;
this.Finite = null;
return;
}
}
}
Type = AUTOMATON_TYPE.NORMAL;
Term = null;
if (finite == null)
{
this.Finite = SpecialOperations.IsFinite(automaton);
}
else
{
this.Finite = finite;
}
Automaton utf8 = (new UTF32ToUTF8()).Convert(automaton);
if (this.Finite == true)
{
CommonSuffixRef = null;
}
else
{
CommonSuffixRef = SpecialOperations.GetCommonSuffixBytesRef(utf8);
}
RunAutomaton = new ByteRunAutomaton(utf8, true);
sortedTransitions = utf8.GetSortedTransitions();
}
//private static final boolean DEBUG = BlockTreeTermsWriter.DEBUG;
private BytesRef AddTail(int state, BytesRef term, int idx, int leadLabel)
{
// Find biggest transition that's < label
// TODO: use binary search here
Transition maxTransition = null;
foreach (Transition transition in sortedTransitions[state])
{
if (transition.min < leadLabel)
{
maxTransition = transition;
}
}
if (Debugging.AssertsEnabled) Debugging.Assert(maxTransition != null);
// Append floorLabel
int floorLabel;
if (maxTransition.max > leadLabel - 1)
{
floorLabel = leadLabel - 1;
}
else
{
floorLabel = maxTransition.max;
}
if (idx >= term.Bytes.Length)
{
term.Grow(1 + idx);
}
//if (DEBUG) System.out.println(" add floorLabel=" + (char) floorLabel + " idx=" + idx);
term.Bytes[idx] = (byte)floorLabel;
state = maxTransition.to.Number;
idx++;
// Push down to last accept state
while (true)
{
Transition[] transitions = sortedTransitions[state];
if (transitions.Length == 0)
{
if (Debugging.AssertsEnabled) Debugging.Assert(RunAutomaton.IsAccept(state));
term.Length = idx;
//if (DEBUG) System.out.println(" return " + term.utf8ToString());
return term;
}
else
{
// We are pushing "top" -- so get last label of
// last transition:
if (Debugging.AssertsEnabled) Debugging.Assert(transitions.Length != 0);
Transition lastTransition = transitions[transitions.Length - 1];
if (idx >= term.Bytes.Length)
{
term.Grow(1 + idx);
}
//if (DEBUG) System.out.println(" push maxLabel=" + (char) lastTransition.max + " idx=" + idx);
term.Bytes[idx] = (byte)lastTransition.max;
state = lastTransition.to.Number;
idx++;
}
}
}
// TODO: should this take startTerm too? this way
// Terms.intersect could forward to this method if type !=
// NORMAL:
public virtual TermsEnum GetTermsEnum(Terms terms)
{
return Type switch
{
AUTOMATON_TYPE.NONE => TermsEnum.EMPTY,
AUTOMATON_TYPE.ALL => terms.GetEnumerator(),
AUTOMATON_TYPE.SINGLE => new SingleTermsEnum(terms.GetEnumerator(), Term),
AUTOMATON_TYPE.PREFIX => new PrefixTermsEnum(terms.GetEnumerator(), Term),// TODO: this is very likely faster than .intersect,
// but we should test and maybe cutover
AUTOMATON_TYPE.NORMAL => terms.Intersect(this, null),
_ => throw new Exception("unhandled case"),// unreachable
};
}
/// <summary>
/// Finds largest term accepted by this Automaton, that's
/// <= the provided input term. The result is placed in
/// output; it's fine for output and input to point to
/// the same <see cref="BytesRef"/>. The returned result is either the
/// provided output, or <c>null</c> if there is no floor term
/// (ie, the provided input term is before the first term
/// accepted by this <see cref="Automaton"/>).
/// </summary>
public virtual BytesRef Floor(BytesRef input, BytesRef output)
{
output.Offset = 0;
//if (DEBUG) System.out.println("CA.floor input=" + input.utf8ToString());
int state = RunAutomaton.InitialState;
// Special case empty string:
if (input.Length == 0)
{
if (RunAutomaton.IsAccept(state))
{
output.Length = 0;
return output;
}
else
{
return null;
}
}
IList<int> stack = new List<int>();
int idx = 0;
while (true)
{
int label = ((sbyte)input.Bytes[input.Offset + idx]) & 0xff;
int nextState = RunAutomaton.Step(state, label);
//if (DEBUG) System.out.println(" cycle label=" + (char) label + " nextState=" + nextState);
if (idx == input.Length - 1)
{
if (nextState != -1 && RunAutomaton.IsAccept(nextState))
{
// Input string is accepted
if (idx >= output.Bytes.Length)
{
output.Grow(1 + idx);
}
output.Bytes[idx] = (byte)label;
output.Length = input.Length;
//if (DEBUG) System.out.println(" input is accepted; return term=" + output.utf8ToString());
return output;
}
else
{
nextState = -1;
}
}
if (nextState == -1)
{
// Pop back to a state that has a transition
// <= our label:
while (true)
{
Transition[] transitions = sortedTransitions[state];
if (transitions.Length == 0)
{
if (Debugging.AssertsEnabled) Debugging.Assert(RunAutomaton.IsAccept(state));
output.Length = idx;
//if (DEBUG) System.out.println(" return " + output.utf8ToString());
return output;
}
else if (label - 1 < transitions[0].min)
{
if (RunAutomaton.IsAccept(state))
{
output.Length = idx;
//if (DEBUG) System.out.println(" return " + output.utf8ToString());
return output;
}
// pop
if (stack.Count == 0)
{
//if (DEBUG) System.out.println(" pop ord=" + idx + " return null");
return null;
}
else
{
state = stack[stack.Count - 1];
stack.RemoveAt(stack.Count - 1);
idx--;
//if (DEBUG) System.out.println(" pop ord=" + (idx+1) + " label=" + (char) label + " first trans.min=" + (char) transitions[0].min);
label = input.Bytes[input.Offset + idx] & 0xff;
}
}
else
{
//if (DEBUG) System.out.println(" stop pop ord=" + idx + " first trans.min=" + (char) transitions[0].min);
break;
}
}
//if (DEBUG) System.out.println(" label=" + (char) label + " idx=" + idx);
return AddTail(state, output, idx, label);
}
else
{
if (idx >= output.Bytes.Length)
{
output.Grow(1 + idx);
}
output.Bytes[idx] = (byte)label;
stack.Add(state);
state = nextState;
idx++;
}
}
}
public virtual string ToDot()
{
StringBuilder b = new StringBuilder("digraph CompiledAutomaton {\n");
b.Append(" rankdir = LR;\n");
int initial = RunAutomaton.InitialState;
for (int i = 0; i < sortedTransitions.Length; i++)
{
b.Append(" ").Append(i);
if (RunAutomaton.IsAccept(i))
{
b.Append(" [shape=doublecircle,label=\"\"];\n");
}
else
{
b.Append(" [shape=circle,label=\"\"];\n");
}
if (i == initial)
{
b.Append(" initial [shape=plaintext,label=\"\"];\n");
b.Append(" initial -> ").Append(i).Append("\n");
}
for (int j = 0; j < sortedTransitions[i].Length; j++)
{
b.Append(" ").Append(i);
sortedTransitions[i][j].AppendDot(b);
}
}
return b.Append("}\n").ToString();
}
public override int GetHashCode()
{
const int prime = 31;
int result = 1;
result = prime * result + ((RunAutomaton == null) ? 0 : RunAutomaton.GetHashCode());
result = prime * result + ((Term == null) ? 0 : Term.GetHashCode());
result = prime * result + Type.GetHashCode(); //((Type == null) ? 0 : Type.GetHashCode()); // LUCENENET NOTE: Enum cannot be null in .NET
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
CompiledAutomaton other = (CompiledAutomaton)obj;
if (Type != other.Type)
{
return false;
}
if (Type == AUTOMATON_TYPE.SINGLE || Type == AUTOMATON_TYPE.PREFIX)
{
if (!Term.Equals(other.Term))
{
return false;
}
}
else if (Type == AUTOMATON_TYPE.NORMAL)
{
if (!RunAutomaton.Equals(other.RunAutomaton))
{
return false;
}
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using NinthChevron.Data;
using NinthChevron.Data.Entity;
using NinthChevron.Helpers;
using NinthChevron.ComponentModel.DataAnnotations;
using NinthChevron.Data.SqlServer.Test.AdventureWorks2012;
using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.HumanResourcesSchema;
using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.PersonSchema;
using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.ProductionSchema;
using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.PurchasingSchema;
namespace NinthChevron.Data.SqlServer.Test.AdventureWorks2012.SalesSchema
{
[Table("CountryRegionCurrency", "Sales", "AdventureWorks2012")]
public partial class CountryRegionCurrency : Entity<CountryRegionCurrency>
{
static CountryRegionCurrency()
{
Join<CountryRegion>(t => t.CountryRegionCodeCountryRegion, (t, f) => t.CountryRegionCode == f.CountryRegionCode); // Relation
Join<Currency>(t => t.CurrencyCodeCurrency, (t, f) => t.CurrencyCode == f.CurrencyCode); // Relation
}
[NotifyPropertyChanged, Column("CountryRegionCode", true, false, false)]
public string CountryRegionCode { get; set; }
[NotifyPropertyChanged, Column("CurrencyCode", true, false, false)]
public string CurrencyCode { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public CountryRegion CountryRegionCodeCountryRegion { get; set; }
[InnerJoinColumn]
public Currency CurrencyCodeCurrency { get; set; }
}
[Table("CreditCard", "Sales", "AdventureWorks2012")]
public partial class CreditCard : Entity<CreditCard>
{
static CreditCard()
{
Join<PersonCreditCard>(t => t.CreditCardPersonCreditCard, (t, f) => t.CreditCardID == f.CreditCardID); // Reverse Relation
Join<SalesOrderHeader>(t => t.CreditCardSalesOrderHeader, (t, f) => t.CreditCardID == f.CreditCardID); // Reverse Relation
}
[NotifyPropertyChanged, Column("CreditCardID", true, true, false)]
public int CreditCardID
{
get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); }
set { this.EntityIdentity = (int)value; }
}
[NotifyPropertyChanged, Column("CardType", false, false, false)]
public string CardType { get; set; }
[NotifyPropertyChanged, Column("CardNumber", false, false, false)]
public string CardNumber { get; set; }
[NotifyPropertyChanged, Column("ExpMonth", false, false, false)]
public byte ExpMonth { get; set; }
[NotifyPropertyChanged, Column("ExpYear", false, false, false)]
public short ExpYear { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public PersonCreditCard CreditCardPersonCreditCard { get; set; }
[InnerJoinColumn]
public SalesOrderHeader CreditCardSalesOrderHeader { get; set; }
}
[Table("Currency", "Sales", "AdventureWorks2012")]
public partial class Currency : Entity<Currency>
{
static Currency()
{
Join<CountryRegionCurrency>(t => t.CurrencyCodeCountryRegionCurrency, (t, f) => t.CurrencyCode == f.CurrencyCode); // Reverse Relation
Join<CurrencyRate>(t => t.FromCurrencyCodeCurrencyRate, (t, f) => t.CurrencyCode == f.FromCurrencyCode); // Reverse Relation
Join<CurrencyRate>(t => t.ToCurrencyCodeCurrencyRate, (t, f) => t.CurrencyCode == f.ToCurrencyCode); // Reverse Relation
}
[NotifyPropertyChanged, Column("CurrencyCode", true, false, false)]
public string CurrencyCode { get; set; }
[NotifyPropertyChanged, Column("Name", false, false, false)]
public string Name { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public CountryRegionCurrency CurrencyCodeCountryRegionCurrency { get; set; }
[InnerJoinColumn]
public CurrencyRate FromCurrencyCodeCurrencyRate { get; set; }
[InnerJoinColumn]
public CurrencyRate ToCurrencyCodeCurrencyRate { get; set; }
}
[Table("CurrencyRate", "Sales", "AdventureWorks2012")]
public partial class CurrencyRate : Entity<CurrencyRate>
{
static CurrencyRate()
{
Join<Currency>(t => t.FromCurrencyCodeCurrency, (t, f) => t.FromCurrencyCode == f.CurrencyCode); // Relation
Join<Currency>(t => t.ToCurrencyCodeCurrency, (t, f) => t.ToCurrencyCode == f.CurrencyCode); // Relation
Join<SalesOrderHeader>(t => t.CurrencyRateSalesOrderHeader, (t, f) => t.CurrencyRateID == f.CurrencyRateID); // Reverse Relation
}
[NotifyPropertyChanged, Column("CurrencyRateID", true, true, false)]
public int CurrencyRateID
{
get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); }
set { this.EntityIdentity = (int)value; }
}
[NotifyPropertyChanged, Column("CurrencyRateDate", false, false, false)]
public System.DateTime CurrencyRateDate { get; set; }
[NotifyPropertyChanged, Column("FromCurrencyCode", true, false, false)]
public string FromCurrencyCode { get; set; }
[NotifyPropertyChanged, Column("ToCurrencyCode", true, false, false)]
public string ToCurrencyCode { get; set; }
[NotifyPropertyChanged, Column("AverageRate", false, false, false)]
public object AverageRate { get; set; }
[NotifyPropertyChanged, Column("EndOfDayRate", false, false, false)]
public object EndOfDayRate { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public Currency FromCurrencyCodeCurrency { get; set; }
[InnerJoinColumn]
public Currency ToCurrencyCodeCurrency { get; set; }
[InnerJoinColumn]
public SalesOrderHeader CurrencyRateSalesOrderHeader { get; set; }
}
[Table("Customer", "Sales", "AdventureWorks2012")]
public partial class Customer : Entity<Customer>
{
static Customer()
{
Join<Person>(t => t.PersonPerson, (t, f) => t.PersonID == f.BusinessEntityID); // Relation
Join<SalesOrderHeader>(t => t.CustomerSalesOrderHeader, (t, f) => t.CustomerID == f.CustomerID); // Reverse Relation
Join<SalesTerritory>(t => t.TerritorySalesTerritory, (t, f) => t.TerritoryID == f.TerritoryID); // Relation
Join<Store>(t => t.StoreStore, (t, f) => t.StoreID == f.BusinessEntityID); // Relation
}
[NotifyPropertyChanged, Column("CustomerID", true, true, false)]
public int CustomerID
{
get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); }
set { this.EntityIdentity = (int)value; }
}
[NotifyPropertyChanged, Column("PersonID", true, false, true)]
public System.Nullable<int> PersonID { get; set; }
[NotifyPropertyChanged, Column("StoreID", true, false, true)]
public System.Nullable<int> StoreID { get; set; }
[NotifyPropertyChanged, Column("TerritoryID", true, false, true)]
public System.Nullable<int> TerritoryID { get; set; }
[NotifyPropertyChanged, Column("AccountNumber", false, false, false)]
public string AccountNumber { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public Person PersonPerson { get; set; }
[InnerJoinColumn]
public SalesOrderHeader CustomerSalesOrderHeader { get; set; }
[InnerJoinColumn]
public SalesTerritory TerritorySalesTerritory { get; set; }
[InnerJoinColumn]
public Store StoreStore { get; set; }
}
[Table("PersonCreditCard", "Sales", "AdventureWorks2012")]
public partial class PersonCreditCard : Entity<PersonCreditCard>
{
static PersonCreditCard()
{
Join<Person>(t => t.BusinessEntityPerson, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation
Join<CreditCard>(t => t.CreditCardCreditCard, (t, f) => t.CreditCardID == f.CreditCardID); // Relation
}
[NotifyPropertyChanged, Column("BusinessEntityID", true, false, false)]
public int BusinessEntityID { get; set; }
[NotifyPropertyChanged, Column("CreditCardID", true, false, false)]
public int CreditCardID { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public Person BusinessEntityPerson { get; set; }
[InnerJoinColumn]
public CreditCard CreditCardCreditCard { get; set; }
}
[Table("SalesOrderDetail", "Sales", "AdventureWorks2012")]
public partial class SalesOrderDetail : Entity<SalesOrderDetail>
{
static SalesOrderDetail()
{
Join<SalesOrderHeader>(t => t.SalesOrderSalesOrderHeader, (t, f) => t.SalesOrderID == f.SalesOrderID); // Relation
Join<SpecialOfferProduct>(t => t.ProductSpecialOfferProduct, (t, f) => t.ProductID == f.SpecialOfferID); // Relation
Join<SpecialOfferProduct>(t => t.SpecialOfferSpecialOfferProduct, (t, f) => t.SpecialOfferID == f.SpecialOfferID); // Relation
Join<SpecialOfferProduct>(t => t.SpecialOfferSpecialOfferProduct, (t, f) => t.SpecialOfferID == f.ProductID); // Relation
Join<SpecialOfferProduct>(t => t.ProductSpecialOfferProduct, (t, f) => t.ProductID == f.ProductID); // Relation
}
[NotifyPropertyChanged, Column("SalesOrderID", true, false, false)]
public int SalesOrderID { get; set; }
[NotifyPropertyChanged, Column("SalesOrderDetailID", true, true, false)]
public int SalesOrderDetailID
{
get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); }
set { this.EntityIdentity = (int)value; }
}
[NotifyPropertyChanged, Column("CarrierTrackingNumber", false, false, true)]
public string CarrierTrackingNumber { get; set; }
[NotifyPropertyChanged, Column("OrderQty", true, false, false)]
public short OrderQty { get; set; }
[NotifyPropertyChanged, Column("ProductID", true, false, false)]
public int ProductID { get; set; }
[NotifyPropertyChanged, Column("SpecialOfferID", true, false, false)]
public int SpecialOfferID { get; set; }
[NotifyPropertyChanged, Column("UnitPrice", true, false, false)]
public object UnitPrice { get; set; }
[NotifyPropertyChanged, Column("UnitPriceDiscount", true, false, false)]
public object UnitPriceDiscount { get; set; }
[NotifyPropertyChanged, Column("LineTotal", false, false, false)]
public object LineTotal { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public SalesOrderHeader SalesOrderSalesOrderHeader { get; set; }
[InnerJoinColumn]
public SpecialOfferProduct ProductSpecialOfferProduct { get; set; }
[InnerJoinColumn]
public SpecialOfferProduct SpecialOfferSpecialOfferProduct { get; set; }
[InnerJoinColumn]
public SpecialOfferProduct SpecialOfferSpecialOfferProduct { get; set; }
[InnerJoinColumn]
public SpecialOfferProduct ProductSpecialOfferProduct { get; set; }
}
[Table("SalesOrderHeader", "Sales", "AdventureWorks2012")]
public partial class SalesOrderHeader : Entity<SalesOrderHeader>
{
static SalesOrderHeader()
{
Join<Address>(t => t.BillToAddressAddress, (t, f) => t.BillToAddressID == f.AddressID); // Relation
Join<Address>(t => t.ShipToAddressAddress, (t, f) => t.ShipToAddressID == f.AddressID); // Relation
Join<ShipMethod>(t => t.ShipMethodShipMethod, (t, f) => t.ShipMethodID == f.ShipMethodID); // Relation
Join<CreditCard>(t => t.CreditCardCreditCard, (t, f) => t.CreditCardID == f.CreditCardID); // Relation
Join<CurrencyRate>(t => t.CurrencyRateCurrencyRate, (t, f) => t.CurrencyRateID == f.CurrencyRateID); // Relation
Join<Customer>(t => t.CustomerCustomer, (t, f) => t.CustomerID == f.CustomerID); // Relation
Join<SalesOrderHeaderSalesReason>(t => t.SalesOrderSalesOrderHeaderSalesReason, (t, f) => t.SalesOrderID == f.SalesOrderID); // Reverse Relation
Join<SalesOrderDetail>(t => t.SalesOrderSalesOrderDetail, (t, f) => t.SalesOrderID == f.SalesOrderID); // Reverse Relation
Join<SalesPerson>(t => t.SalesPersonSalesPerson, (t, f) => t.SalesPersonID == f.BusinessEntityID); // Relation
Join<SalesTerritory>(t => t.TerritorySalesTerritory, (t, f) => t.TerritoryID == f.TerritoryID); // Relation
}
[NotifyPropertyChanged, Column("SalesOrderID", true, true, false)]
public int SalesOrderID
{
get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); }
set { this.EntityIdentity = (int)value; }
}
[NotifyPropertyChanged, Column("RevisionNumber", false, false, false)]
public byte RevisionNumber { get; set; }
[NotifyPropertyChanged, Column("OrderDate", true, false, false)]
public System.DateTime OrderDate { get; set; }
[NotifyPropertyChanged, Column("DueDate", true, false, false)]
public System.DateTime DueDate { get; set; }
[NotifyPropertyChanged, Column("ShipDate", true, false, true)]
public System.Nullable<System.DateTime> ShipDate { get; set; }
[NotifyPropertyChanged, Column("Status", true, false, false)]
public byte Status { get; set; }
[NotifyPropertyChanged, Column("OnlineOrderFlag", false, false, false)]
public bool OnlineOrderFlag { get; set; }
[NotifyPropertyChanged, Column("SalesOrderNumber", false, false, false)]
public string SalesOrderNumber { get; set; }
[NotifyPropertyChanged, Column("PurchaseOrderNumber", false, false, true)]
public string PurchaseOrderNumber { get; set; }
[NotifyPropertyChanged, Column("AccountNumber", false, false, true)]
public string AccountNumber { get; set; }
[NotifyPropertyChanged, Column("CustomerID", true, false, false)]
public int CustomerID { get; set; }
[NotifyPropertyChanged, Column("SalesPersonID", true, false, true)]
public System.Nullable<int> SalesPersonID { get; set; }
[NotifyPropertyChanged, Column("TerritoryID", true, false, true)]
public System.Nullable<int> TerritoryID { get; set; }
[NotifyPropertyChanged, Column("BillToAddressID", true, false, false)]
public int BillToAddressID { get; set; }
[NotifyPropertyChanged, Column("ShipToAddressID", true, false, false)]
public int ShipToAddressID { get; set; }
[NotifyPropertyChanged, Column("ShipMethodID", true, false, false)]
public int ShipMethodID { get; set; }
[NotifyPropertyChanged, Column("CreditCardID", true, false, true)]
public System.Nullable<int> CreditCardID { get; set; }
[NotifyPropertyChanged, Column("CreditCardApprovalCode", false, false, true)]
public string CreditCardApprovalCode { get; set; }
[NotifyPropertyChanged, Column("CurrencyRateID", true, false, true)]
public System.Nullable<int> CurrencyRateID { get; set; }
[NotifyPropertyChanged, Column("SubTotal", true, false, false)]
public object SubTotal { get; set; }
[NotifyPropertyChanged, Column("TaxAmt", true, false, false)]
public object TaxAmt { get; set; }
[NotifyPropertyChanged, Column("Freight", true, false, false)]
public object Freight { get; set; }
[NotifyPropertyChanged, Column("TotalDue", false, false, false)]
public object TotalDue { get; set; }
[NotifyPropertyChanged, Column("Comment", false, false, true)]
public string Comment { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public Address BillToAddressAddress { get; set; }
[InnerJoinColumn]
public Address ShipToAddressAddress { get; set; }
[InnerJoinColumn]
public ShipMethod ShipMethodShipMethod { get; set; }
[InnerJoinColumn]
public CreditCard CreditCardCreditCard { get; set; }
[InnerJoinColumn]
public CurrencyRate CurrencyRateCurrencyRate { get; set; }
[InnerJoinColumn]
public Customer CustomerCustomer { get; set; }
[InnerJoinColumn]
public SalesOrderHeaderSalesReason SalesOrderSalesOrderHeaderSalesReason { get; set; }
[InnerJoinColumn]
public SalesOrderDetail SalesOrderSalesOrderDetail { get; set; }
[InnerJoinColumn]
public SalesPerson SalesPersonSalesPerson { get; set; }
[InnerJoinColumn]
public SalesTerritory TerritorySalesTerritory { get; set; }
}
[Table("SalesOrderHeaderSalesReason", "Sales", "AdventureWorks2012")]
public partial class SalesOrderHeaderSalesReason : Entity<SalesOrderHeaderSalesReason>
{
static SalesOrderHeaderSalesReason()
{
Join<SalesOrderHeader>(t => t.SalesOrderSalesOrderHeader, (t, f) => t.SalesOrderID == f.SalesOrderID); // Relation
Join<SalesReason>(t => t.SalesReasonSalesReason, (t, f) => t.SalesReasonID == f.SalesReasonID); // Relation
}
[NotifyPropertyChanged, Column("SalesOrderID", true, false, false)]
public int SalesOrderID { get; set; }
[NotifyPropertyChanged, Column("SalesReasonID", true, false, false)]
public int SalesReasonID { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public SalesOrderHeader SalesOrderSalesOrderHeader { get; set; }
[InnerJoinColumn]
public SalesReason SalesReasonSalesReason { get; set; }
}
[Table("SalesPerson", "Sales", "AdventureWorks2012")]
public partial class SalesPerson : Entity<SalesPerson>
{
static SalesPerson()
{
Join<Employee>(t => t.BusinessEntityEmployee, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation
Join<SalesOrderHeader>(t => t.SalesPersonSalesOrderHeader, (t, f) => t.BusinessEntityID == f.SalesPersonID); // Reverse Relation
Join<SalesTerritoryHistory>(t => t.BusinessEntitySalesTerritoryHistory, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Reverse Relation
Join<SalesPersonQuotaHistory>(t => t.BusinessEntitySalesPersonQuotaHistory, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Reverse Relation
Join<Store>(t => t.SalesPersonStore, (t, f) => t.BusinessEntityID == f.SalesPersonID); // Reverse Relation
Join<SalesTerritory>(t => t.TerritorySalesTerritory, (t, f) => t.TerritoryID == f.TerritoryID); // Relation
}
[NotifyPropertyChanged, Column("BusinessEntityID", true, false, false)]
public int BusinessEntityID { get; set; }
[NotifyPropertyChanged, Column("TerritoryID", true, false, true)]
public System.Nullable<int> TerritoryID { get; set; }
[NotifyPropertyChanged, Column("SalesQuota", true, false, true)]
public object SalesQuota { get; set; }
[NotifyPropertyChanged, Column("Bonus", true, false, false)]
public object Bonus { get; set; }
[NotifyPropertyChanged, Column("CommissionPct", true, false, false)]
public object CommissionPct { get; set; }
[NotifyPropertyChanged, Column("SalesYTD", true, false, false)]
public object SalesYTD { get; set; }
[NotifyPropertyChanged, Column("SalesLastYear", true, false, false)]
public object SalesLastYear { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public Employee BusinessEntityEmployee { get; set; }
[InnerJoinColumn]
public SalesOrderHeader SalesPersonSalesOrderHeader { get; set; }
[InnerJoinColumn]
public SalesTerritoryHistory BusinessEntitySalesTerritoryHistory { get; set; }
[InnerJoinColumn]
public SalesPersonQuotaHistory BusinessEntitySalesPersonQuotaHistory { get; set; }
[InnerJoinColumn]
public Store SalesPersonStore { get; set; }
[InnerJoinColumn]
public SalesTerritory TerritorySalesTerritory { get; set; }
}
[Table("SalesPersonQuotaHistory", "Sales", "AdventureWorks2012")]
public partial class SalesPersonQuotaHistory : Entity<SalesPersonQuotaHistory>
{
static SalesPersonQuotaHistory()
{
Join<SalesPerson>(t => t.BusinessEntitySalesPerson, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation
}
[NotifyPropertyChanged, Column("BusinessEntityID", true, false, false)]
public int BusinessEntityID { get; set; }
[NotifyPropertyChanged, Column("QuotaDate", true, false, false)]
public System.DateTime QuotaDate { get; set; }
[NotifyPropertyChanged, Column("SalesQuota", true, false, false)]
public object SalesQuota { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public SalesPerson BusinessEntitySalesPerson { get; set; }
}
[Table("SalesReason", "Sales", "AdventureWorks2012")]
public partial class SalesReason : Entity<SalesReason>
{
static SalesReason()
{
Join<SalesOrderHeaderSalesReason>(t => t.SalesReasonSalesOrderHeaderSalesReason, (t, f) => t.SalesReasonID == f.SalesReasonID); // Reverse Relation
}
[NotifyPropertyChanged, Column("SalesReasonID", true, true, false)]
public int SalesReasonID
{
get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); }
set { this.EntityIdentity = (int)value; }
}
[NotifyPropertyChanged, Column("Name", false, false, false)]
public string Name { get; set; }
[NotifyPropertyChanged, Column("ReasonType", false, false, false)]
public string ReasonType { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public SalesOrderHeaderSalesReason SalesReasonSalesOrderHeaderSalesReason { get; set; }
}
[Table("SalesTaxRate", "Sales", "AdventureWorks2012")]
public partial class SalesTaxRate : Entity<SalesTaxRate>
{
static SalesTaxRate()
{
Join<StateProvince>(t => t.StateProvinceStateProvince, (t, f) => t.StateProvinceID == f.StateProvinceID); // Relation
}
[NotifyPropertyChanged, Column("SalesTaxRateID", true, true, false)]
public int SalesTaxRateID
{
get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); }
set { this.EntityIdentity = (int)value; }
}
[NotifyPropertyChanged, Column("StateProvinceID", true, false, false)]
public int StateProvinceID { get; set; }
[NotifyPropertyChanged, Column("TaxType", true, false, false)]
public byte TaxType { get; set; }
[NotifyPropertyChanged, Column("TaxRate", false, false, false)]
public object TaxRate { get; set; }
[NotifyPropertyChanged, Column("Name", false, false, false)]
public string Name { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public StateProvince StateProvinceStateProvince { get; set; }
}
[Table("SalesTerritory", "Sales", "AdventureWorks2012")]
public partial class SalesTerritory : Entity<SalesTerritory>
{
static SalesTerritory()
{
Join<CountryRegion>(t => t.CountryRegionCodeCountryRegion, (t, f) => t.CountryRegionCode == f.CountryRegionCode); // Relation
Join<SalesOrderHeader>(t => t.TerritorySalesOrderHeader, (t, f) => t.TerritoryID == f.TerritoryID); // Reverse Relation
Join<Customer>(t => t.TerritoryCustomer, (t, f) => t.TerritoryID == f.TerritoryID); // Reverse Relation
Join<StateProvince>(t => t.TerritoryStateProvince, (t, f) => t.TerritoryID == f.TerritoryID); // Reverse Relation
Join<SalesPerson>(t => t.TerritorySalesPerson, (t, f) => t.TerritoryID == f.TerritoryID); // Reverse Relation
Join<SalesTerritoryHistory>(t => t.TerritorySalesTerritoryHistory, (t, f) => t.TerritoryID == f.TerritoryID); // Reverse Relation
}
[NotifyPropertyChanged, Column("TerritoryID", true, true, false)]
public int TerritoryID
{
get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); }
set { this.EntityIdentity = (int)value; }
}
[NotifyPropertyChanged, Column("Name", false, false, false)]
public string Name { get; set; }
[NotifyPropertyChanged, Column("CountryRegionCode", true, false, false)]
public string CountryRegionCode { get; set; }
[NotifyPropertyChanged, Column("Group", false, false, false)]
public string Group { get; set; }
[NotifyPropertyChanged, Column("SalesYTD", true, false, false)]
public object SalesYTD { get; set; }
[NotifyPropertyChanged, Column("SalesLastYear", true, false, false)]
public object SalesLastYear { get; set; }
[NotifyPropertyChanged, Column("CostYTD", true, false, false)]
public object CostYTD { get; set; }
[NotifyPropertyChanged, Column("CostLastYear", true, false, false)]
public object CostLastYear { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public CountryRegion CountryRegionCodeCountryRegion { get; set; }
[InnerJoinColumn]
public SalesOrderHeader TerritorySalesOrderHeader { get; set; }
[InnerJoinColumn]
public Customer TerritoryCustomer { get; set; }
[InnerJoinColumn]
public StateProvince TerritoryStateProvince { get; set; }
[InnerJoinColumn]
public SalesPerson TerritorySalesPerson { get; set; }
[InnerJoinColumn]
public SalesTerritoryHistory TerritorySalesTerritoryHistory { get; set; }
}
[Table("SalesTerritoryHistory", "Sales", "AdventureWorks2012")]
public partial class SalesTerritoryHistory : Entity<SalesTerritoryHistory>
{
static SalesTerritoryHistory()
{
Join<SalesPerson>(t => t.BusinessEntitySalesPerson, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation
Join<SalesTerritory>(t => t.TerritorySalesTerritory, (t, f) => t.TerritoryID == f.TerritoryID); // Relation
}
[NotifyPropertyChanged, Column("BusinessEntityID", true, false, false)]
public int BusinessEntityID { get; set; }
[NotifyPropertyChanged, Column("TerritoryID", true, false, false)]
public int TerritoryID { get; set; }
[NotifyPropertyChanged, Column("StartDate", true, false, false)]
public System.DateTime StartDate { get; set; }
[NotifyPropertyChanged, Column("EndDate", true, false, true)]
public System.Nullable<System.DateTime> EndDate { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public SalesPerson BusinessEntitySalesPerson { get; set; }
[InnerJoinColumn]
public SalesTerritory TerritorySalesTerritory { get; set; }
}
[Table("ShoppingCartItem", "Sales", "AdventureWorks2012")]
public partial class ShoppingCartItem : Entity<ShoppingCartItem>
{
static ShoppingCartItem()
{
Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation
}
[NotifyPropertyChanged, Column("ShoppingCartItemID", true, true, false)]
public int ShoppingCartItemID
{
get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); }
set { this.EntityIdentity = (int)value; }
}
[NotifyPropertyChanged, Column("ShoppingCartID", false, false, false)]
public string ShoppingCartID { get; set; }
[NotifyPropertyChanged, Column("Quantity", true, false, false)]
public int Quantity { get; set; }
[NotifyPropertyChanged, Column("ProductID", true, false, false)]
public int ProductID { get; set; }
[NotifyPropertyChanged, Column("DateCreated", false, false, false)]
public System.DateTime DateCreated { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public Product ProductProduct { get; set; }
}
[Table("SpecialOffer", "Sales", "AdventureWorks2012")]
public partial class SpecialOffer : Entity<SpecialOffer>
{
static SpecialOffer()
{
Join<SpecialOfferProduct>(t => t.SpecialOfferSpecialOfferProduct, (t, f) => t.SpecialOfferID == f.SpecialOfferID); // Reverse Relation
}
[NotifyPropertyChanged, Column("SpecialOfferID", true, true, false)]
public int SpecialOfferID
{
get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); }
set { this.EntityIdentity = (int)value; }
}
[NotifyPropertyChanged, Column("Description", false, false, false)]
public string Description { get; set; }
[NotifyPropertyChanged, Column("DiscountPct", true, false, false)]
public object DiscountPct { get; set; }
[NotifyPropertyChanged, Column("Type", false, false, false)]
public string Type { get; set; }
[NotifyPropertyChanged, Column("Category", false, false, false)]
public string Category { get; set; }
[NotifyPropertyChanged, Column("StartDate", true, false, false)]
public System.DateTime StartDate { get; set; }
[NotifyPropertyChanged, Column("EndDate", true, false, false)]
public System.DateTime EndDate { get; set; }
[NotifyPropertyChanged, Column("MinQty", true, false, false)]
public int MinQty { get; set; }
[NotifyPropertyChanged, Column("MaxQty", true, false, true)]
public System.Nullable<int> MaxQty { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public SpecialOfferProduct SpecialOfferSpecialOfferProduct { get; set; }
}
[Table("SpecialOfferProduct", "Sales", "AdventureWorks2012")]
public partial class SpecialOfferProduct : Entity<SpecialOfferProduct>
{
static SpecialOfferProduct()
{
Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation
Join<SpecialOffer>(t => t.SpecialOfferSpecialOffer, (t, f) => t.SpecialOfferID == f.SpecialOfferID); // Relation
Join<SalesOrderDetail>(t => t.ProductSalesOrderDetail, (t, f) => t.SpecialOfferID == f.ProductID); // Reverse Relation
Join<SalesOrderDetail>(t => t.SpecialOfferSalesOrderDetail, (t, f) => t.SpecialOfferID == f.SpecialOfferID); // Reverse Relation
Join<SalesOrderDetail>(t => t.SpecialOfferSalesOrderDetail, (t, f) => t.ProductID == f.SpecialOfferID); // Reverse Relation
Join<SalesOrderDetail>(t => t.ProductSalesOrderDetail, (t, f) => t.ProductID == f.ProductID); // Reverse Relation
}
[NotifyPropertyChanged, Column("SpecialOfferID", true, false, false)]
public int SpecialOfferID { get; set; }
[NotifyPropertyChanged, Column("ProductID", true, false, false)]
public int ProductID { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public Product ProductProduct { get; set; }
[InnerJoinColumn]
public SpecialOffer SpecialOfferSpecialOffer { get; set; }
[InnerJoinColumn]
public SalesOrderDetail ProductSalesOrderDetail { get; set; }
[InnerJoinColumn]
public SalesOrderDetail SpecialOfferSalesOrderDetail { get; set; }
[InnerJoinColumn]
public SalesOrderDetail SpecialOfferSalesOrderDetail { get; set; }
[InnerJoinColumn]
public SalesOrderDetail ProductSalesOrderDetail { get; set; }
}
[Table("Store", "Sales", "AdventureWorks2012")]
public partial class Store : Entity<Store>
{
static Store()
{
Join<BusinessEntity>(t => t.BusinessEntityBusinessEntity, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation
Join<SalesPerson>(t => t.SalesPersonSalesPerson, (t, f) => t.SalesPersonID == f.BusinessEntityID); // Relation
Join<Customer>(t => t.StoreCustomer, (t, f) => t.BusinessEntityID == f.StoreID); // Reverse Relation
}
[NotifyPropertyChanged, Column("BusinessEntityID", true, false, false)]
public int BusinessEntityID { get; set; }
[NotifyPropertyChanged, Column("Name", false, false, false)]
public string Name { get; set; }
[NotifyPropertyChanged, Column("SalesPersonID", true, false, true)]
public System.Nullable<int> SalesPersonID { get; set; }
[NotifyPropertyChanged, Column("Demographics", false, false, true)]
public object Demographics { get; set; }
[NotifyPropertyChanged, Column("rowguid", false, false, false)]
public System.Guid Rowguid { get; set; }
[NotifyPropertyChanged, Column("ModifiedDate", false, false, false)]
public System.DateTime ModifiedDate { get; set; }
[InnerJoinColumn]
public BusinessEntity BusinessEntityBusinessEntity { get; set; }
[InnerJoinColumn]
public SalesPerson SalesPersonSalesPerson { get; set; }
[InnerJoinColumn]
public Customer StoreCustomer { get; set; }
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D03Level11ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="D03Level11ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D02Level1"/> collection.
/// </remarks>
[Serializable]
public partial class D03Level11ReChild : BusinessBase<D03Level11ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_Child_Name, "Level_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1 Child Name.</value>
public string Level_1_1_Child_Name
{
get { return GetProperty(Level_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D03Level11ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D03Level11ReChild"/> object.</returns>
internal static D03Level11ReChild NewD03Level11ReChild()
{
return DataPortal.CreateChild<D03Level11ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="D03Level11ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="cParentID2">The CParentID2 parameter of the D03Level11ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="D03Level11ReChild"/> object.</returns>
internal static D03Level11ReChild GetD03Level11ReChild(int cParentID2)
{
return DataPortal.FetchChild<D03Level11ReChild>(cParentID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D03Level11ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private D03Level11ReChild()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D03Level11ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D03Level11ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="cParentID2">The CParent ID2.</param>
protected void Child_Fetch(int cParentID2)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetD03Level11ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CParentID2", cParentID2).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, cParentID2);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
BusinessRules.CheckRules();
}
}
/// <summary>
/// Loads a <see cref="D03Level11ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_Child_NameProperty, dr.GetString("Level_1_1_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D03Level11ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D02Level1 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddD03Level11ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_Child_Name", ReadProperty(Level_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D03Level11ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(D02Level1 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateD03Level11ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_Child_Name", ReadProperty(Level_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="D03Level11ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(D02Level1 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteD03Level11ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <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);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NodaTime.TimeZones;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NodaTime.TimeZones.IO;
using NodaTime.TimeZones.Cldr;
namespace NodaTime.TzdbCompiler.Tzdb
{
/// <summary>
/// Writes time zone data to a stream in nzd format.
/// </summary>
/// <remarks>
/// <para>The file format consists of four bytes indicating the file format version/type (mostly for
/// future expansion), followed by a number of fields. Each field is identified by a <see cref="TzdbStreamFieldId"/>.
/// The fields are always written in order, and the format of a field consists of its field ID, a 7-bit-encoded
/// integer with the size of the data, and then the data itself.
/// </para>
/// <para>
/// The version number does not need to be increased if new fields are added, as the reader will simply ignore
/// unknown fields. It only needs to be increased for incompatible changes such as a different time zone format,
/// or if old fields are removed.
/// </para>
/// </remarks>
internal sealed class TzdbStreamWriter
{
private const int Version = 0;
public void Write(
TzdbDatabase database,
WindowsZones cldrWindowsZones,
IDictionary<string, string> additionalWindowsNameToIdMappings,
Stream stream)
{
FieldCollection fields = new FieldCollection();
var zones = database.GenerateDateTimeZones().ToList();
var stringPool = CreateOptimizedStringPool(zones, database.ZoneLocations, database.Zone1970Locations, cldrWindowsZones);
// First assemble the fields (writing to the string pool as we go)
foreach (var zone in zones)
{
var zoneField = fields.AddField(TzdbStreamFieldId.TimeZone, stringPool);
WriteZone(zone, zoneField.Writer);
}
fields.AddField(TzdbStreamFieldId.TzdbVersion, null).Writer.WriteString(database.Version);
// Normalize the aliases
var timeZoneMap = new Dictionary<string, string>();
foreach (var key in database.Aliases.Keys)
{
var value = database.Aliases[key];
while (database.Aliases.ContainsKey(value))
{
value = database.Aliases[value];
}
timeZoneMap.Add(key, value);
}
fields.AddField(TzdbStreamFieldId.TzdbIdMap, stringPool).Writer.WriteDictionary(timeZoneMap);
// Windows mappings
cldrWindowsZones.Write(fields.AddField(TzdbStreamFieldId.CldrSupplementalWindowsZones, stringPool).Writer);
// Additional names from Windows Standard Name to canonical ID, used in Noda Time 1.x BclDateTimeZone, when we
// didn't have access to TimeZoneInfo.Id.
fields.AddField(TzdbStreamFieldId.WindowsAdditionalStandardNameToIdMapping, stringPool).Writer.WriteDictionary
(additionalWindowsNameToIdMappings.ToDictionary(pair => pair.Key, pair => cldrWindowsZones.PrimaryMapping[pair.Value]));
// Zone locations, if any.
var zoneLocations = database.ZoneLocations;
if (zoneLocations != null)
{
var field = fields.AddField(TzdbStreamFieldId.ZoneLocations, stringPool);
field.Writer.WriteCount(zoneLocations.Count);
foreach (var zoneLocation in zoneLocations)
{
zoneLocation.Write(field.Writer);
}
}
// Zone 1970 locations, if any.
var zone1970Locations = database.Zone1970Locations;
if (zone1970Locations != null)
{
var field = fields.AddField(TzdbStreamFieldId.Zone1970Locations, stringPool);
field.Writer.WriteCount(zone1970Locations.Count);
foreach (var zoneLocation in zone1970Locations)
{
zoneLocation.Write(field.Writer);
}
}
var stringPoolField = fields.AddField(TzdbStreamFieldId.StringPool, null);
stringPoolField.Writer.WriteCount(stringPool.Count);
foreach (string value in stringPool)
{
stringPoolField.Writer.WriteString(value);
}
// Now write all the fields out, in the right order.
new BinaryWriter(stream).Write(Version);
fields.WriteTo(stream);
}
private static void WriteZone(DateTimeZone zone, IDateTimeZoneWriter writer)
{
writer.WriteString(zone.Id);
// For cached zones, simply uncache first.
var cachedZone = zone as CachedDateTimeZone;
if (cachedZone != null)
{
zone = cachedZone.TimeZone;
}
var fixedZone = zone as FixedDateTimeZone;
if (fixedZone != null)
{
writer.WriteByte((byte) DateTimeZoneWriter.DateTimeZoneType.Fixed);
fixedZone.Write(writer);
}
else
{
var precalculatedZone = zone as PrecalculatedDateTimeZone;
if (precalculatedZone != null)
{
writer.WriteByte((byte) DateTimeZoneWriter.DateTimeZoneType.Precalculated);
precalculatedZone.Write(writer);
}
else
{
throw new ArgumentException("Unserializable DateTimeZone type " + zone.GetType());
}
}
}
/// <summary>
/// Creates a string pool which contains the most commonly-used strings within the given set
/// of zones first. This will allow them to be more efficiently represented when we write them out for real.
/// </summary>
private static List<string> CreateOptimizedStringPool(
IEnumerable<DateTimeZone> zones,
IEnumerable<TzdbZoneLocation>? zoneLocations,
IEnumerable<TzdbZone1970Location>? zone1970Locations,
WindowsZones cldrWindowsZones)
{
var optimizingWriter = new StringPoolOptimizingFakeWriter();
foreach (var zone in zones)
{
optimizingWriter.WriteString(zone.Id);
WriteZone(zone, optimizingWriter);
}
if (zoneLocations != null)
{
foreach (var location in zoneLocations)
{
location.Write(optimizingWriter);
}
}
if (zone1970Locations != null)
{
foreach (var location in zone1970Locations)
{
location.Write(optimizingWriter);
}
}
cldrWindowsZones.Write(optimizingWriter);
return optimizingWriter.CreatePool();
}
/// <summary>
/// Writer which only cares about strings. It builds a complete list of all strings written for the given
/// zones, then creates a distinct list in most-prevalent-first order. This allows the most frequently-written
/// strings to be the ones which are cheapest to write.
/// </summary>
private class StringPoolOptimizingFakeWriter : IDateTimeZoneWriter
{
private readonly List<string> allStrings = new List<string>();
public List<string> CreatePool() => allStrings.GroupBy(x => x)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.ToList();
public void WriteString(string value)
{
allStrings.Add(value);
}
public void WriteMilliseconds(int millis) { }
public void WriteOffset(Offset offset) {}
public void WriteCount(int count) { }
public void WriteByte(byte value) { }
public void WriteSignedCount(int count) { }
public void WriteZoneIntervalTransition(Instant? previous, Instant value) {}
public void WriteDictionary(IDictionary<string, string> dictionary)
{
foreach (var entry in dictionary)
{
WriteString(entry.Key);
WriteString(entry.Value);
}
}
}
/// <summary>
/// The data for a field, including the field number itself.
/// </summary>
private class FieldData
{
private readonly MemoryStream stream;
internal FieldData(TzdbStreamFieldId fieldId, IList<string>? stringPool)
{
this.FieldId = fieldId;
this.stream = new MemoryStream();
this.Writer = new DateTimeZoneWriter(stream, stringPool);
}
internal IDateTimeZoneWriter Writer { get; }
internal TzdbStreamFieldId FieldId { get; }
internal void WriteTo(Stream output)
{
output.WriteByte((byte)FieldId);
int length = (int) stream.Length;
// We've got a 7-bit-encoding routine... might as well use it.
new DateTimeZoneWriter(output, null).WriteCount(length);
stream.WriteTo(output);
}
}
private class FieldCollection
{
private readonly List<FieldData> fields = new List<FieldData>();
internal FieldData AddField(TzdbStreamFieldId fieldNumber, IList<string>? stringPool)
{
FieldData ret = new FieldData(fieldNumber, stringPool);
fields.Add(ret);
return ret;
}
internal void WriteTo(Stream stream)
{
foreach (var field in fields.OrderBy(field => field.FieldId))
{
field.WriteTo(stream);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public class WinHttpHandlerTest
{
private const string FakeProxy = "http://proxy.contoso.com";
private readonly ITestOutputHelper _output;
public WinHttpHandlerTest(ITestOutputHelper output)
{
_output = output;
TestControl.ResetAll();
}
[Fact]
public void Ctor_ExpectedDefaultPropertyValues()
{
var handler = new WinHttpHandler();
Assert.Equal(SslProtocolSupport.DefaultSslProtocols, handler.SslProtocols);
Assert.Equal(true, handler.AutomaticRedirection);
Assert.Equal(50, handler.MaxAutomaticRedirections);
Assert.Equal(DecompressionMethods.Deflate | DecompressionMethods.GZip, handler.AutomaticDecompression);
Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy);
Assert.Equal(null, handler.CookieContainer);
Assert.Equal(null, handler.ServerCertificateValidationCallback);
Assert.Equal(false, handler.CheckCertificateRevocationList);
Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOption);
X509Certificate2Collection certs = handler.ClientCertificates;
Assert.True(certs.Count == 0);
Assert.Equal(false, handler.PreAuthenticate);
Assert.Equal(null, handler.ServerCredentials);
Assert.Equal(WindowsProxyUsePolicy.UseWinHttpProxy, handler.WindowsProxyUsePolicy);
Assert.Equal(CredentialCache.DefaultCredentials, handler.DefaultProxyCredentials);
Assert.Equal(null, handler.Proxy);
Assert.Equal(Int32.MaxValue, handler.MaxConnectionsPerServer);
Assert.Equal(TimeSpan.FromSeconds(60), handler.ConnectTimeout);
Assert.Equal(TimeSpan.FromSeconds(30), handler.SendTimeout);
Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveHeadersTimeout);
Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveDataTimeout);
Assert.Equal(64 * 1024, handler.MaxResponseHeadersLength);
Assert.Equal(64 * 1024, handler.MaxResponseDrainSize);
}
[Fact]
public void AutomaticRedirection_SetFalseAndGet_ValueIsFalse()
{
var handler = new WinHttpHandler();
handler.AutomaticRedirection = false;
Assert.False(handler.AutomaticRedirection);
}
[Fact]
public void AutomaticRedirection_SetTrue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.AutomaticRedirection = true; });
Assert.Equal(
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP,
APICallHistory.WinHttpOptionRedirectPolicy);
}
[Fact]
public void AutomaticRedirection_SetFalse_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.AutomaticRedirection = false; });
Assert.Equal(
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER,
APICallHistory.WinHttpOptionRedirectPolicy);
}
[Fact]
public void CheckCertificateRevocationList_SetTrue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = true; });
Assert.True(APICallHistory.WinHttpOptionEnableSslRevocation.Value);
}
[Fact]
public void CheckCertificateRevocationList_SetFalse_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = false; });
Assert.Equal(false, APICallHistory.WinHttpOptionEnableSslRevocation.HasValue);
}
[Fact]
public void ConnectTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ConnectTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ConnectTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ConnectTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ConnectTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ConnectTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ConnectTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ConnectTimeout = Timeout.InfiniteTimeSpan;
}
[Fact]
public void CookieContainer_WhenCreated_ReturnsNull()
{
var handler = new WinHttpHandler();
Assert.Null(handler.CookieContainer);
}
[Fact]
public async void CookieUsePolicy_UseSpecifiedCookieContainerAndNullContainer_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
Assert.Null(handler.CookieContainer);
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public void CookieUsePolicy_SetUsingInvalidEnum_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.CookieUsePolicy = (CookieUsePolicy)100; });
}
[Fact]
public void CookieUsePolicy_WhenCreated_ReturnsUseInternalCookieStoreOnly()
{
var handler = new WinHttpHandler();
Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy);
}
[Fact]
public void CookieUsePolicy_SetIgnoreCookies_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies;
}
[Fact]
public void CookieUsePolicy_SetUseInternalCookieStoreOnly_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
}
[Fact]
public void CookieUsePolicy_SetUseSpecifiedCookieContainer_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
}
[Fact]
public void CookieUsePolicy_SetIgnoreCookies_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies; });
Assert.True(APICallHistory.WinHttpOptionDisableCookies.Value);
}
[Fact]
public void CookieUsePolicy_SetUseInternalCookieStoreOnly_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; });
Assert.Equal(false, APICallHistory.WinHttpOptionDisableCookies.HasValue);
}
[Fact]
public void CookieUsePolicy_SetUseSpecifiedCookieContainerAndContainer_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate {
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
handler.CookieContainer = new CookieContainer();
});
Assert.Equal(true, APICallHistory.WinHttpOptionDisableCookies.HasValue);
}
[Fact]
public void WindowsProxyUsePolicy_SetUsingInvalidEnum_ThrowArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.WindowsProxyUsePolicy = (WindowsProxyUsePolicy)100; });
}
[Fact]
public void WindowsProxyUsePolicy_SetDoNotUseProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseWinHttpProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseWinWinInetProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseCustomProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
}
[Fact]
public async Task WindowsProxyUsePolicy_UseNonNullProxyAndIncorrectWindowsProxyUsePolicy_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
handler.Proxy = new CustomProxy(false);
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public async Task WindowsProxyUsePolicy_UseCustomProxyAndNullProxy_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = null;
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public void MaxAutomaticRedirections_SetZero_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = 0; });
}
[Fact]
public void MaxAutomaticRedirections_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = -1; });
}
[Fact]
public void MaxAutomaticRedirections_SetValidValue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
int redirections = 35;
SendRequestHelper.Send(handler, delegate { handler.MaxAutomaticRedirections = redirections; });
Assert.Equal((uint)redirections, APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects);
}
[Fact]
public void MaxConnectionsPerServer_SetZero_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = 0; });
}
[Fact]
public void MaxConnectionsPerServer_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = -1; });
}
[Fact]
public void MaxConnectionsPerServer_SetPositiveValue_Success()
{
var handler = new WinHttpHandler();
handler.MaxConnectionsPerServer = 1;
}
[Fact]
public void ReceiveDataTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveDataTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ReceiveDataTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveDataTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ReceiveDataTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ReceiveDataTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ReceiveDataTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ReceiveDataTimeout = Timeout.InfiniteTimeSpan;
}
[Fact]
public void ReceiveHeadersTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ReceiveHeadersTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ReceiveHeadersTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ReceiveHeadersTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ConnectTimeout = Timeout.InfiniteTimeSpan;
}
[Theory]
[ClassData(typeof(SslProtocolSupport.UnsupportedSslProtocolsTestData))]
public void SslProtocols_SetUsingUnsupported_Throws(SslProtocols protocol)
{
var handler = new WinHttpHandler();
Assert.Throws<NotSupportedException>(() => { handler.SslProtocols = protocol; });
}
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public void SslProtocols_SetUsingSupported_Success(SslProtocols protocol)
{
var handler = new WinHttpHandler();
handler.SslProtocols = protocol;
}
[Fact]
public void SslProtocols_SetUsingNone_Throws()
{
var handler = new WinHttpHandler();
Assert.Throws<NotSupportedException>(() => { handler.SslProtocols = SslProtocols.None; });
}
[Fact]
public void SslProtocols_SetUsingInvalidEnum_Throws()
{
var handler = new WinHttpHandler();
Assert.Throws<NotSupportedException>(() => { handler.SslProtocols = (SslProtocols)4096; });
}
[Fact]
public void SslProtocols_SetUsingValidEnums_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.SslProtocols =
SslProtocols.Tls |
SslProtocols.Tls11 |
SslProtocols.Tls12;
});
uint expectedProtocols =
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 |
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 |
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
Assert.Equal(expectedProtocols, APICallHistory.WinHttpOptionSecureProtocols);
}
[Fact]
public async Task GetAsync_MultipleRequestsReusingSameClient_Success()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
for (int i = 0; i < 3; i++)
{
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
HttpResponseMessage response = await client.GetAsync(TestServer.FakeServerEndpoint);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
client.Dispose();
}
[Fact]
public async Task SendAsync_ReadFromStreamingServer_PartialDataRead()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
TestServer.DataAvailablePercentage = 0.25;
int bytesRead;
byte[] buffer = new byte[TestServer.ExpectedResponseBody.Length];
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var stream = await response.Content.ReadAsStreamAsync();
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
_output.WriteLine("bytesRead={0}", bytesRead);
}
client.Dispose();
Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length");
}
[Fact]
public async Task SendAsync_ReadAllDataFromStreamingServer_AllDataRead()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
TestServer.DataAvailablePercentage = 0.25;
int totalBytesRead = 0;
int bytesRead;
byte[] buffer = new byte[TestServer.ExpectedResponseBody.Length];
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var stream = await response.Content.ReadAsStreamAsync();
do
{
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
_output.WriteLine("bytesRead={0}", bytesRead);
totalBytesRead += bytesRead;
} while (bytesRead != 0);
}
client.Dispose();
Assert.Equal(buffer.Length, totalBytesRead);
}
[Fact]
public async Task SendAsync_PostContentWithContentLengthAndChunkedEncodingHeaders_Success()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
client.DefaultRequestHeaders.TransferEncodingChunked = true;
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var content = new StringContent(TestServer.ExpectedResponseBody);
Assert.True(content.Headers.ContentLength.HasValue);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
}
[Fact]
public async Task SendAsync_PostNoContentObjectWithChunkedEncodingHeader_ExpectInvalidOperationException()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
client.DefaultRequestHeaders.TransferEncodingChunked = true;
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsDeflateCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
TestServer.SetResponse(DecompressionMethods.Deflate, TestServer.ExpectedResponseBody);
});
Assert.Null(response.Content.Headers.ContentLength);
string responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(0, response.Content.Headers.ContentEncoding.Count);
Assert.Equal(TestServer.ExpectedResponseBody, responseBody);
}
[Fact]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsGZipCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
TestServer.SetResponse(DecompressionMethods.GZip, TestServer.ExpectedResponseBody);
});
Assert.Null(response.Content.Headers.ContentLength);
string responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(0, response.Content.Headers.ContentEncoding.Count);
Assert.Equal(TestServer.ExpectedResponseBody, responseBody);
}
[Fact]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsNotCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.NotNull(response.Content.Headers.ContentLength);
string responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(TestServer.ExpectedResponseBody, responseBody);
}
[Fact]
public void SendAsync_AutomaticProxySupportAndUseWinInetSettings_ExpectedWinHttpSessionProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSetting_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithEmptySettings_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithManualSettingsOnly_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.Proxy = FakeProxy;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithMissingRegistrySettings_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.RegistryKeyMissing = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectButPACFileNotDetectedOnNetwork_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
TestControl.PACFileNotDetectedOnNetwork = true;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Null(APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSettingAndManualSettingButPACFileNotFoundOnNetwork_ExpectedWinHttpProxySettings()
{
const string manualProxy = FakeProxy;
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
FakeRegistry.WinInetProxySettings.Proxy = manualProxy;
TestControl.PACFileNotDetectedOnNetwork = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
// Both AutoDetect and manual proxy are specified. If AutoDetect fails to find
// the PAC file on the network, then we should fall back to manual setting.
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
Assert.Equal(manualProxy, APICallHistory.RequestProxySettings.Proxy);
}
[Fact]
public void SendAsync_UseNoProxy_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy; });
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public void SendAsync_UseCustomProxyWithNoBypass_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
var customProxy = new CustomProxy(false);
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = customProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
Assert.Equal(FakeProxy, APICallHistory.RequestProxySettings.Proxy);
}
[Fact]
public void SendAsync_UseCustomProxyWithBypass_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
var customProxy = new CustomProxy(true);
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = customProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_AutomaticProxySupportAndUseDefaultWebProxy_ExpectedWinHttpSessionProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = new FakeDefaultWebProxy();
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public async Task SendAsync_SlowPostRequestWithTimedCancellation_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
TestControl.WinHttpReceiveResponse.Delay = 5000;
CancellationTokenSource cts = new CancellationTokenSource(50);
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
var content = new StringContent(new String('a', 1000));
request.Content = content;
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
[Fact]
public async Task SendAsync_SlowGetRequestWithTimedCancellation_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
TestControl.WinHttpReceiveResponse.Delay = 5000;
CancellationTokenSource cts = new CancellationTokenSource(50);
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
[Fact]
public async Task SendAsync_RequestWithCanceledToken_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
CancellationTokenSource cts = new CancellationTokenSource();
cts.Cancel();
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
[Fact]
public async Task SendAsync_WinHttpOpenReturnsError_ExpectHttpRequestException()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
TestControl.WinHttpOpen.ErrorWithApiCall = true;
Exception ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request));
Assert.Equal(typeof(WinHttpException), ex.InnerException.GetType());
}
[Fact]
public void SendAsync_MultipleCallsWithDispose_NoHandleLeaksManuallyVerifiedUsingLogging()
{
WinHttpHandler handler;
HttpResponseMessage response;
for (int i = 0; i < 50; i++)
{
handler = new WinHttpHandler();
response = SendRequestHelper.Send(handler, () => { });
response.Dispose();
handler.Dispose();
}
}
[Fact]
public void SendAsync_MultipleCallsWithoutDispose_NoHandleLeaksManuallyVerifiedUsingLogging()
{
WinHttpHandler handler;
HttpResponseMessage response;
for (int i = 0; i < 50; i++)
{
handler = new WinHttpHandler();
response = SendRequestHelper.Send(handler, () => { });
}
}
public class CustomProxy : IWebProxy
{
private const string DefaultDomain = "domain";
private const string DefaultUsername = "username";
private const string DefaultPassword = "password";
private bool bypassAll;
private NetworkCredential networkCredential;
public CustomProxy(bool bypassAll)
{
this.bypassAll = bypassAll;
this.networkCredential = new NetworkCredential(CustomProxy.DefaultUsername, CustomProxy.DefaultPassword, CustomProxy.DefaultDomain);
}
public string UsernameWithDomain
{
get
{
return CustomProxy.DefaultDomain + "\\" + CustomProxy.DefaultUsername;
}
}
public string Password
{
get
{
return CustomProxy.DefaultPassword;
}
}
public NetworkCredential NetworkCredential
{
get
{
return this.networkCredential;
}
}
ICredentials IWebProxy.Credentials
{
get
{
return this.networkCredential;
}
set
{
}
}
Uri IWebProxy.GetProxy(Uri destination)
{
return new Uri(FakeProxy);
}
bool IWebProxy.IsBypassed(Uri host)
{
return this.bypassAll;
}
}
public class FakeDefaultWebProxy : IWebProxy
{
private ICredentials _credentials = null;
public FakeDefaultWebProxy()
{
}
public ICredentials Credentials
{
get
{
return _credentials;
}
set
{
_credentials = value;
}
}
// This is a sentinel object representing the internal default system proxy that a developer would
// use when accessing the System.Net.WebRequest.DefaultWebProxy property (from the System.Net.Requests
// package). It can't support the GetProxy or IsBypassed methods. WinHttpHandler will handle this
// exception and use the appropriate system default proxy.
public Uri GetProxy(Uri destination)
{
throw new PlatformNotSupportedException();
}
public bool IsBypassed(Uri host)
{
throw new PlatformNotSupportedException();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Linq;
using System.Net.Test.Common;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
[PlatformSpecific(TestPlatforms.Windows)] // NegotiateStream only supports client-side functionality on Unix
public abstract class NegotiateStreamStreamToStreamTest
{
private const int PartialBytesToRead = 5;
private static readonly byte[] s_sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
private const int MaxWriteDataSize = 63 * 1024; // NegoState.MaxWriteDataSize
private static string s_longString = new string('A', MaxWriteDataSize) + 'Z';
private static readonly byte[] s_longMsg = Encoding.ASCII.GetBytes(s_longString);
protected abstract Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName);
protected abstract Task AuthenticateAsServerAsync(NegotiateStream server);
[Fact]
public async Task NegotiateStream_StreamToStream_Authentication_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(false, serverIdentity.IsAuthenticated);
Assert.Equal("", serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[Fact]
public async Task NegotiateStream_StreamToStream_Authentication_TargetName_Success()
{
string targetName = "testTargetName";
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Assert.False(client.IsMutuallyAuthenticated);
Assert.False(server.IsMutuallyAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, targetName);
auth[1] = AuthenticateAsServerAsync(server);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Core difference in behavior: https://github.com/dotnet/corefx/issues/5241")]
public async Task NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails()
{
string targetName = "testTargetName";
// Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a
// NetworkCredential object with empty user, password and domain.
NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", "");
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials);
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials);
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, emptyNetworkCredential, targetName);
auth[1] = AuthenticateAsServerAsync(server);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
// TODO #5241: Behavior difference:
Assert.Equal(false, clientIdentity.IsAuthenticated);
// On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertHasName(clientIdentity, new SecurityIdentifier(WellKnownSidType.AnonymousSid, null).Translate(typeof(NTAccount)).Value);
}
}
[Fact]
public async Task NegotiateStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[s_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
int bytesRead = 0;
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
client.Write(s_sampleMsg, 0, s_sampleMsg.Length);
server.Read(recvBuf, 0, s_sampleMsg.Length);
Assert.True(s_sampleMsg.SequenceEqual(recvBuf));
client.Write(s_sampleMsg, 0, s_sampleMsg.Length);
// Test partial sync read.
bytesRead = server.Read(recvBuf, 0, PartialBytesToRead);
Assert.Equal(PartialBytesToRead, bytesRead);
bytesRead = server.Read(recvBuf, PartialBytesToRead, s_sampleMsg.Length - PartialBytesToRead);
Assert.Equal(s_sampleMsg.Length - PartialBytesToRead, bytesRead);
Assert.True(s_sampleMsg.SequenceEqual(recvBuf));
}
}
[Fact]
public async Task NegotiateStream_StreamToStream_Successive_ClientWrite_Async_Success()
{
byte[] recvBuf = new byte[s_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
int bytesRead = 0;
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
auth[0] = client.WriteAsync(s_sampleMsg, 0, s_sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, s_sampleMsg.Length);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
Assert.True(s_sampleMsg.SequenceEqual(recvBuf));
await client.WriteAsync(s_sampleMsg, 0, s_sampleMsg.Length);
// Test partial async read.
bytesRead = await server.ReadAsync(recvBuf, 0, PartialBytesToRead);
Assert.Equal(PartialBytesToRead, bytesRead);
bytesRead = await server.ReadAsync(recvBuf, PartialBytesToRead, s_sampleMsg.Length - PartialBytesToRead);
Assert.Equal(s_sampleMsg.Length - PartialBytesToRead, bytesRead);
Assert.True(s_sampleMsg.SequenceEqual(recvBuf));
}
}
[Fact]
public async Task NegotiateStream_ReadWriteLongMsgSync_Success()
{
byte[] recvBuf = new byte[s_longMsg.Length];
var network = new VirtualNetwork();
int bytesRead = 0;
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty),
server.AuthenticateAsServerAsync());
client.Write(s_longMsg, 0, s_longMsg.Length);
while (bytesRead < s_longMsg.Length)
{
bytesRead += server.Read(recvBuf, bytesRead, s_longMsg.Length - bytesRead);
}
Assert.True(s_longMsg.SequenceEqual(recvBuf));
}
}
[Fact]
public async Task NegotiateStream_ReadWriteLongMsgAsync_Success()
{
byte[] recvBuf = new byte[s_longMsg.Length];
var network = new VirtualNetwork();
int bytesRead = 0;
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty),
server.AuthenticateAsServerAsync());
await client.WriteAsync(s_longMsg, 0, s_longMsg.Length);
while (bytesRead < s_longMsg.Length)
{
bytesRead += await server.ReadAsync(recvBuf, bytesRead, s_longMsg.Length - bytesRead);
}
Assert.True(s_longMsg.SequenceEqual(recvBuf));
}
}
[Fact]
public void NegotiateStream_StreamToStream_Flush_Propagated()
{
VirtualNetwork network = new VirtualNetwork();
using (var stream = new VirtualNetworkStream(network, isServer: false))
using (var negotiateStream = new NegotiateStream(stream))
{
Assert.False(stream.HasBeenSyncFlushed);
negotiateStream.Flush();
Assert.True(stream.HasBeenSyncFlushed);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Relies on FlushAsync override not available in desktop")]
public void NegotiateStream_StreamToStream_FlushAsync_Propagated()
{
VirtualNetwork network = new VirtualNetwork();
using (var stream = new VirtualNetworkStream(network, isServer: false))
using (var negotiateStream = new NegotiateStream(stream))
{
Task task = negotiateStream.FlushAsync();
Assert.False(task.IsCompleted);
stream.CompleteAsyncFlush();
Assert.True(task.IsCompleted);
}
}
}
public sealed class NegotiateStreamStreamToStreamTest_Async : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
client.AuthenticateAsClientAsync(credential, targetName);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
server.AuthenticateAsServerAsync();
}
public sealed class NegotiateStreamStreamToStreamTest_Async_TestOverloadNullBinding : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
client.AuthenticateAsClientAsync(credential, null, targetName);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
server.AuthenticateAsServerAsync(null);
}
public sealed class NegotiateStreamStreamToStreamTest_Async_TestOverloadProtectionLevel : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
client.AuthenticateAsClientAsync(credential, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
server.AuthenticateAsServerAsync((NetworkCredential)CredentialCache.DefaultCredentials, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
public sealed class NegotiateStreamStreamToStreamTest_Async_TestOverloadAllParameters : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
client.AuthenticateAsClientAsync(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
server.AuthenticateAsServerAsync((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
public sealed class NegotiateStreamStreamToStreamTest_BeginEnd : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
Task.Factory.FromAsync(client.BeginAuthenticateAsClient, client.EndAuthenticateAsClient, credential, targetName, null);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
Task.Factory.FromAsync(server.BeginAuthenticateAsServer, server.EndAuthenticateAsServer, null);
}
public sealed class NegotiateStreamStreamToStreamTest_Sync : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
Task.Run(() => client.AuthenticateAsClient(credential, targetName));
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
Task.Run(() => server.AuthenticateAsServer());
}
public sealed class NegotiateStreamStreamToStreamTest_Sync_TestOverloadNullBinding : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
Task.Run(() => client.AuthenticateAsClient(credential, null, targetName));
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
Task.Run(() => server.AuthenticateAsServer(null));
}
public sealed class NegotiateStreamStreamToStreamTest_Sync_TestOverloadAllParameters : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
Task.Run(() => client.AuthenticateAsClient(credential, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification));
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
Task.Run(() => server.AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification));
}
}
| |
using System;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Windows.Storage;
using Windows.Storage.Streams;
namespace WinIRC.Utils
{
public enum StorageType
{
Roaming, Local, Temporary
}
public class ObjectStorageHelper<T>
{
private ApplicationData appData = Windows.Storage.ApplicationData.Current;
private XmlSerializer serializer;
private StorageType storageType;
private string FileName(T Obj, string Handle)
{
/*
* When I first started writing this class I thought I would only be storing objects that could be serialized as XML
* and hence I put a .xml suffix on the filename. I now realise the folly of doing this as I may want to, in the future,
* store objects that cannot be serialized as XML (e.g. Media objects) and instead use some alternative method that does
* not involve serialization.
* I had a choice between supporting backward compatibility or dropping the .xml suffix. I opted for the latter.
*/
var str = String.Concat(Handle, String.Format("{0}", Obj.GetType().ToString()));
return str;
//return String.Format("{0}.xml", Obj.GetType().FullName).Replace("'","").Replace(",","").Replace(".","").Replace("&","");
}
/// <summary>
/// Generic class to simplify the storage and retrieval of data to/from Windows.Storage.ApplicationData
/// </summary>
/// <param name="StorageType"></param>
public ObjectStorageHelper(StorageType StorageType)
{
serializer = new XmlSerializer(typeof(T));
storageType = StorageType;
}
/// <summary>
/// Delete a stored instance of T from Windows.Storage.ApplicationData
/// </summary>
/// <returns></returns>
public async Task DeleteAsync()
{
string fileName = FileName(Activator.CreateInstance<T>(), String.Empty);
await DeleteAsync(fileName);
}
/// <summary>
/// Delete a stored instance of T with a specified handle from Windows.Storage.ApplicationData.
/// Specification of a handle supports storage and deletion of different instances of T.
/// </summary>
/// <param name="Handle">User-defined handle for the stored object</param>
public async Task DeleteAsync(string Handle)
{
if (Handle == null)
throw new ArgumentNullException("Handle");
string fileName = FileName(Activator.CreateInstance<T>(), Handle);
try
{
StorageFolder folder = GetFolder(storageType);
var file = await GetFileIfExistsAsync(folder, fileName);
if (file != null)
{
await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Store an instance of T to Windows.Storage.ApplicationData with a specified handle.
/// Specification of a handle supports storage and deletion of different instances of T.
/// </summary>
/// <param name="Obj">Object to be saved</param>
/// <param name="Handle">User-defined handle for the stored object</param>
public async Task SaveAsync(T Obj, string Handle)
{
if (Obj == null)
throw new ArgumentNullException("Obj");
if (Handle == null)
throw new ArgumentNullException("Handle");
StorageFile file = null;
string fileName = Handle;
StorageFolder folder = GetFolder(storageType);
file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite);
using (Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result)
{
serializer.Serialize(outStream, Obj);
await outStream.FlushAsync();
}
}
/// <summary>
/// Store an instance of T to Windows.Storage.ApplicationData with a specified handle.
/// Specification of a handle supports storage and deletion of different instances of T.
/// </summary>
/// <param name="Obj">Object to be saved</param>
/// <param name="Handle">User-defined handle for the stored object</param>
public async Task MigrateAsync(T Obj, string Handle)
{
if (Obj == null)
throw new ArgumentNullException("Obj");
if (Handle == null)
throw new ArgumentNullException("Handle");
StorageFile file = null;
string fileName = Handle;
StorageFolder folder = GetFolder(storageType);
file = await folder.CreateFileAsync(fileName, CreationCollisionOption.FailIfExists);
IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite);
using (Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result)
{
serializer.Serialize(outStream, Obj);
await outStream.FlushAsync();
}
}
/// <summary>
/// Save an instance of T to Windows.Storage.ApplicationData.
/// </summary>
/// <param name="Obj">Object to be saved</param>
/// <param name="Handle">User-defined handle for the stored object</param>
public async Task SaveAsync(T Obj)
{
string fileName = FileName(Obj, String.Empty);
await SaveAsync(Obj, fileName);
}
/// <summary>
/// Retrieve a stored instance of T with a specified handle from Windows.Storage.ApplicationData.
/// Specification of a handle supports storage and deletion of different instances of T.
/// </summary>
/// <param name="Handle">User-defined handle for the stored object</param>
public async Task<T> LoadAsync(string Handle)
{
if (Handle == null)
throw new ArgumentNullException("Handle");
string fileName;
if (Handle == FileName(Activator.CreateInstance<T>(), String.Empty))
fileName = FileName(Activator.CreateInstance<T>(), Handle);
else
fileName = Handle;
try
{
StorageFile file = null;
StorageFolder folder = GetFolder(storageType);
file = await folder.GetFileAsync(fileName);
IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
using (Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result)
{
return (T)serializer.Deserialize(inStream);
}
}
catch (FileNotFoundException)
{
//file not existing is perfectly valid so simply return the default
return default(T);
//Interesting thread here: How to detect if a file exists (http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/1eb71a80-c59c-4146-aeb6-fefd69f4b4bb)
//throw;
}
catch (Exception)
{
//Unable to load contents of file
throw;
}
}
/// <summary>
/// Retrieve a stored instance of T from Windows.Storage.ApplicationData.
/// </summary>
public async Task<T> LoadAsync()
{
string fileName = FileName(Activator.CreateInstance<T>(), String.Empty);
return await LoadAsync(fileName);
}
public StorageFolder GetFolder(StorageType storageType)
{
StorageFolder folder;
switch (storageType)
{
case StorageType.Roaming:
folder = appData.RoamingFolder;
break;
case StorageType.Local:
folder = appData.LocalFolder;
break;
case StorageType.Temporary:
folder = appData.TemporaryFolder;
break;
default:
throw new Exception(String.Format("Unknown StorageType: {0}", storageType));
}
return folder;
}
public async Task<StorageFile> GetFileIfExistsAsync(StorageFolder folder, string fileName)
{
try
{
return await folder.GetFileAsync(fileName);
}
catch
{
return null;
}
}
public async Task<Boolean> FileExists(StorageFolder folder, string fileName)
{
try
{
await folder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Xml.Tests
{
public static class NextSiblingTests
{
[Fact]
public static void OnTextNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text<child1/></root>");
Assert.Equal(XmlNodeType.Text, xmlDocument.DocumentElement.ChildNodes[0].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0].NextSibling, xmlDocument.DocumentElement.ChildNodes[1]);
}
[Fact]
public static void OnTextNodeSplit()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text</root>");
var textNode = (XmlText)xmlDocument.DocumentElement.FirstChild;
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Null(textNode.NextSibling);
var split = textNode.SplitText(4);
Assert.Equal(2, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(split, textNode.NextSibling);
Assert.Null(split.NextSibling);
}
[Fact]
public static void OnCommentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><!--some text--><child1/></root>");
Assert.Equal(XmlNodeType.Comment, xmlDocument.DocumentElement.ChildNodes[0].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0].NextSibling, xmlDocument.DocumentElement.ChildNodes[1]);
}
[Fact]
public static void SiblingOfLastChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text<child1/><child2/></root>");
Assert.Null(xmlDocument.DocumentElement.LastChild.NextSibling);
}
[Fact]
public static void OnCDataNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><![CDATA[ <opentag> without an </endtag> and & <! are all ok here ]]><child1/></root>");
Assert.Equal(XmlNodeType.CDATA, xmlDocument.DocumentElement.ChildNodes[0].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0].NextSibling, xmlDocument.DocumentElement.ChildNodes[1]);
}
[Fact]
public static void OnDocumentFragment()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/>some text<child2/><child3/></root>");
var documentFragment = xmlDocument.CreateDocumentFragment();
documentFragment.AppendChild(xmlDocument.DocumentElement);
Assert.Null(documentFragment.NextSibling);
}
[Fact]
public static void OnDocumentElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/><?PI pi info?>");
var piInfo = xmlDocument.ChildNodes[1];
Assert.Equal(XmlNodeType.ProcessingInstruction, piInfo.NodeType);
Assert.Equal(piInfo, xmlDocument.DocumentElement.NextSibling);
}
[Fact]
public static void OnAttributeNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr1='test' attr2='test2' />");
var attr1 = xmlDocument.DocumentElement.Attributes[0];
Assert.Equal("attr1", attr1.Name);
Assert.Null(attr1.NextSibling);
}
[Fact]
public static void OnAttributeNodeWithChildren()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr1='test' attr2='test2'><child1/><child2/><child3/></root>");
var node = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Equal("child3", node.Name);
Assert.Null(node.NextSibling);
}
[Fact]
public static void ElementOneChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child/></root>");
Assert.Null(xmlDocument.DocumentElement.ChildNodes[0].NextSibling);
}
[Fact]
public static void OnAllSiblings()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3 attr='1'/>Some Text<child4/><!-- comment --><?PI processing info?></root>");
var count = xmlDocument.DocumentElement.ChildNodes.Count;
var previousNode = xmlDocument.DocumentElement.ChildNodes[0];
for (var idx = 1; idx < count; idx++)
{
var currentNode = xmlDocument.DocumentElement.ChildNodes[idx];
Assert.Equal(previousNode.NextSibling, currentNode);
previousNode = currentNode;
}
Assert.Null(previousNode.NextSibling);
}
[Fact]
public static void RemoveChildCheckSibling()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
Assert.Equal("child1", child1.Name);
Assert.Equal("child2", child2.Name);
Assert.Equal(child2, child1.NextSibling);
xmlDocument.DocumentElement.RemoveChild(child1);
Assert.Null(child1.NextSibling);
}
[Fact]
public static void ReplaceChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
var child3 = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Equal(child2, child1.NextSibling);
Assert.Equal(child3, child2.NextSibling);
Assert.Null(child3.NextSibling);
xmlDocument.DocumentElement.RemoveChild(child2);
Assert.Equal(child3, child1.NextSibling);
Assert.Null(child2.NextSibling);
Assert.Null(child3.NextSibling);
}
[Fact]
public static void InsertChildAfter()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.NextSibling);
xmlDocument.DocumentElement.InsertAfter(newNode, child1);
Assert.Equal(newNode, child1.NextSibling);
Assert.Null(newNode.NextSibling);
}
[Fact]
public static void AppendChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.NextSibling);
xmlDocument.DocumentElement.AppendChild(newNode);
Assert.Equal(newNode, child1.NextSibling);
Assert.Null(newNode.NextSibling);
}
[Fact]
public static void NewlyCreatedElement()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateElement("element");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedAttribute()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateAttribute("attribute");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedTextNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateTextNode("textnode");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedCDataNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateCDataSection("cdata section");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedProcessingInstruction()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateProcessingInstruction("PI", "data");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedComment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateComment("comment");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedDocumentFragment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateDocumentFragment();
Assert.Null(node.NextSibling);
}
[Fact]
public static void FirstChildNextSibling()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[1], xmlDocument.DocumentElement.FirstChild.NextSibling);
}
}
}
| |
using Signum.Engine.Linq;
using Signum.Entities;
using Signum.Entities.DynamicQuery;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
using Signum.Utilities.Reflection;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Signum.Engine.DynamicQuery
{
public class ExpressionContainer
{
public Polymorphic<Dictionary<string, ExtensionInfo>> RegisteredExtensions =
new Polymorphic<Dictionary<string, ExtensionInfo>>(PolymorphicMerger.InheritDictionaryInterfaces, null);
public Dictionary<PropertyRoute, IExtensionDictionaryInfo> RegisteredExtensionsDictionaries =
new Dictionary<PropertyRoute, IExtensionDictionaryInfo>();
internal Expression BuildExtension(Type parentType, string key, Expression parentExpression)
{
LambdaExpression lambda = RegisteredExtensions.GetValue(parentType)[key].Lambda;
return ExpressionReplacer.Replace(Expression.Invoke(lambda, parentExpression));
}
public IEnumerable<QueryToken> GetExtensions(QueryToken parent)
{
var parentType = parent.Type.CleanType().UnNullify();
var dic = RegisteredExtensions.TryGetValue(parentType);
IEnumerable<QueryToken> extensionsTokens = dic == null ? Enumerable.Empty<QueryToken>() :
dic.Values.Where(ei => ei.Inherit || ei.SourceType == parentType).Select(v => v.CreateToken(parent));
var pr = parentType.IsEntity() && !parentType.IsAbstract ? PropertyRoute.Root(parentType) :
parentType.IsEmbeddedEntity() ? parent.GetPropertyRoute() : null;
var edi = pr == null ? null : RegisteredExtensionsDictionaries.TryGetC(pr);
IEnumerable<QueryToken> dicExtensionsTokens = edi == null ? Enumerable.Empty<QueryToken>() :
edi.GetAllTokens(parent);
return extensionsTokens.Concat(dicExtensionsTokens);
}
public ExtensionInfo Register<E, S>(Expression<Func<E, S>> lambdaToMethodOrProperty, Func<string>? niceName = null)
{
using (HeavyProfiler.LogNoStackTrace("RegisterExpression"))
{
if (lambdaToMethodOrProperty.Body.NodeType == ExpressionType.Call)
{
var mi = ReflectionTools.GetMethodInfo(lambdaToMethodOrProperty);
AssertExtensionMethod(mi);
return Register<E, S>(lambdaToMethodOrProperty, niceName ?? (() => mi.Name.NiceName()), mi.Name);
}
else if (lambdaToMethodOrProperty.Body.NodeType == ExpressionType.MemberAccess)
{
var pi = ReflectionTools.GetPropertyInfo(lambdaToMethodOrProperty);
return Register<E, S>(lambdaToMethodOrProperty, niceName ?? (() => pi.NiceName()), pi.Name);
}
else throw new InvalidOperationException("argument 'lambdaToMethodOrProperty' should be a simple lambda calling a method or property: {0}".FormatWith(lambdaToMethodOrProperty.ToString()));
}
}
private static void AssertExtensionMethod(MethodInfo mi)
{
var assembly = mi.DeclaringType!.Assembly;
if (assembly == typeof(Enumerable).Assembly ||
assembly == typeof(Csv).Assembly ||
assembly == typeof(Lite).Assembly)
throw new InvalidOperationException("The parameter 'lambdaToMethod' should be an expression calling a expression method");
}
public ExtensionInfo Register<E, S>(Expression<Func<E, S>> extensionLambda, Func<string> niceName, string key, bool replace = false)
{
var extension = new ExtensionInfo(typeof(E), extensionLambda, typeof(S), key, niceName);
return Register(extension);
}
public ExtensionInfo Register(ExtensionInfo extension, bool replace = false)
{
var dic = RegisteredExtensions.GetOrAddDefinition(extension.SourceType);
if (replace)
dic[extension.Key] = extension;
else
dic.Add(extension.Key, extension);
RegisteredExtensions.ClearCache();
return extension;
}
public ExtensionDictionaryInfo<T, KVP, K, V> RegisterDictionary<T, KVP, K, V>(
Expression<Func<T, IEnumerable<KVP>>> collectionSelector,
Expression<Func<KVP, K>> keySelector,
Expression<Func<KVP, V>> valueSelector,
ResetLazy<HashSet<K>>? allKeys = null)
where T : Entity
where K : notnull
{
var mei = new ExtensionDictionaryInfo<T, KVP, K, V>(collectionSelector, keySelector, valueSelector,
allKeys ?? GetAllKeysLazy<T, KVP, K>(collectionSelector, keySelector));
RegisteredExtensionsDictionaries.Add(PropertyRoute.Root(typeof(T)), mei);
return mei;
}
public ExtensionDictionaryInfo<M, KVP, K, V> RegisterDictionaryInEmbedded<T, M, KVP, K, V>(
Expression<Func<T, M>> embeddedSelector,
Expression<Func<M, IEnumerable<KVP>>> collectionSelector,
Expression<Func<KVP, K>> keySelector,
Expression<Func<KVP, V>> valueSelector,
ResetLazy<HashSet<K>>? allKeys = null)
where T : Entity
where M : ModifiableEntity
where K : notnull
{
var mei = new ExtensionDictionaryInfo<M, KVP, K, V>(collectionSelector, keySelector, valueSelector,
allKeys ?? GetAllKeysLazy<T, KVP, K>(CombineSelectors(embeddedSelector, collectionSelector), keySelector));
RegisteredExtensionsDictionaries.Add(PropertyRoute.Construct(embeddedSelector), mei);
return mei;
}
private Expression<Func<T, IEnumerable<KVP>>> CombineSelectors<T, M, KVP>(Expression<Func<T, M>> embeddedSelector, Expression<Func<M, IEnumerable<KVP>>> collectionSelector)
where T : Entity
where M : ModifiableEntity
{
Expression<Func<T, IEnumerable<KVP>>> result = e => collectionSelector.Evaluate(embeddedSelector.Evaluate(e));
return (Expression<Func<T, IEnumerable<KVP>>>)ExpressionCleaner.Clean(result)!;
}
private ResetLazy<HashSet<K>> GetAllKeysLazy<T, KVP, K>(Expression<Func<T, IEnumerable<KVP>>> collectionSelector, Expression<Func<KVP, K>> keySelector)
where T : Entity
{
if (typeof(K).IsEnum)
return new ResetLazy<HashSet<K>>(() => EnumExtensions.GetValues<K>().ToHashSet());
if (typeof(K).IsLite())
return GlobalLazy.WithoutInvalidations(() => Database.RetrieveAllLite(typeof(K).CleanType()).Cast<K>().ToHashSet());
if (collectionSelector.Body.Type.IsMList())
{
var lambda = Expression.Lambda<Func<T, MList<KVP>>>(collectionSelector.Body, collectionSelector.Parameters);
return GlobalLazy.WithoutInvalidations(() => Database.MListQuery(lambda).Select(kvp => keySelector.Evaluate(kvp.Element)).Distinct().ToHashSet());
}
else
{
return GlobalLazy.WithoutInvalidations(() => Database.Query<T>().SelectMany(collectionSelector).Select(keySelector).Distinct().ToHashSet());
}
}
}
public interface IExtensionDictionaryInfo
{
IEnumerable<QueryToken> GetAllTokens(QueryToken parent);
}
public class ExtensionDictionaryInfo<T, KVP, K, V> : IExtensionDictionaryInfo
where K : notnull
{
public ResetLazy<HashSet<K>> AllKeys;
public Expression<Func<T, IEnumerable<KVP>>> CollectionSelector { get; set; }
public Expression<Func<KVP, K>> KeySelector { get; set; }
public Expression<Func<KVP, V>> ValueSelector { get; set; }
readonly ConcurrentDictionary<QueryToken, ExtensionRouteInfo> metas = new ConcurrentDictionary<QueryToken, ExtensionRouteInfo>();
public ExtensionDictionaryInfo(
Expression<Func<T, IEnumerable<KVP>>> collectionSelector,
Expression<Func<KVP, K>> keySelector,
Expression<Func<KVP, V>> valueSelector,
ResetLazy<HashSet<K>> allKeys)
{
CollectionSelector = collectionSelector;
KeySelector = keySelector;
ValueSelector = valueSelector;
AllKeys = allKeys;
}
public IEnumerable<QueryToken> GetAllTokens(QueryToken parent)
{
var info = metas.GetOrAdd(parent, qt =>
{
Expression<Func<T, V>> lambda = t => ValueSelector.Evaluate(CollectionSelector.Evaluate(t).SingleOrDefaultEx()!);
Expression e = MetadataVisitor.JustVisit(lambda, MetaExpression.FromToken(qt, typeof(T)));
var result = new ExtensionRouteInfo();
if (e is MetaExpression me && me.Meta is CleanMeta cm && cm.PropertyRoutes.Any())
{
var cleanType = me!.Type.CleanType();
result.PropertyRoute = cm.PropertyRoutes.Only();
result.Implementations = me.Meta.Implementations;
result.Format = ColumnDescriptionFactory.GetFormat(cm.PropertyRoutes);
result.Unit = ColumnDescriptionFactory.GetUnit(cm.PropertyRoutes);
}
return result;
});
return AllKeys.Value.Select(key => new ExtensionDictionaryToken<T, K, V>(parent,
key: key,
unit: info.Unit,
format: info.Format,
implementations: info.Implementations,
propertyRoute: info.PropertyRoute,
lambda: t => ValueSelector.Evaluate(CollectionSelector.Evaluate(t).SingleOrDefaultEx(kvp => KeySelector.Evaluate(kvp).Equals(key))!)
));
}
}
public class ExtensionInfo
{
ConcurrentDictionary<QueryToken, ExtensionRouteInfo> metas = new ConcurrentDictionary<QueryToken, ExtensionRouteInfo>();
public ExtensionInfo(Type sourceType, LambdaExpression lambda, Type type, string key, Func<string> niceName)
{
this.Type = type;
this.SourceType = sourceType;
this.Key = key;
this.Lambda = lambda;
this.IsProjection = type != typeof(string) && type.ElementType() != null;
this.NiceName = niceName;
}
public readonly Type Type;
public readonly Type SourceType;
public readonly string Key;
public bool IsProjection;
public bool Inherit = true;
public Implementations? ForceImplementations;
public PropertyRoute? ForcePropertyRoute;
public string? ForceFormat;
public string? ForceUnit;
public Func<string?>? ForceIsAllowed;
internal readonly LambdaExpression Lambda;
public Func<string> NiceName;
protected internal virtual ExtensionToken CreateToken(QueryToken parent)
{
var info = metas.GetOrAdd(parent, qt =>
{
Expression e = MetadataVisitor.JustVisit(Lambda, MetaExpression.FromToken(qt, SourceType));
MetaExpression? me;
if (this.IsProjection)
{
var mpe = e as MetaProjectorExpression;
if (mpe == null)
mpe = MetadataVisitor.AsProjection(e);
me = mpe == null ? null : mpe.Projector as MetaExpression;
}
else
{
me = e as MetaExpression;
}
var result = new ExtensionRouteInfo();
if (me != null && me.Meta is CleanMeta cleanMeta && cleanMeta.PropertyRoutes.Any())
{
result.PropertyRoute = cleanMeta.PropertyRoutes.Only();
result.Implementations = me.Meta.Implementations;
result.Format = ColumnDescriptionFactory.GetFormat(cleanMeta.PropertyRoutes);
result.Unit = ColumnDescriptionFactory.GetUnit(cleanMeta.PropertyRoutes);
}
else if (me?.Meta is DirtyMeta dirtyMeta)
{
result.PropertyRoute = dirtyMeta.CleanMetas.Select(cm => cm.PropertyRoutes.Only()).Distinct().Only();
var metaImps = dirtyMeta.CleanMetas.Select(cm => cm.Implementations).Distinct().Only();
if (metaImps.HasValue && metaImps.Value.Types.All(t => t.IsAssignableFrom(Type)))
{
result.Implementations = metaImps;
}
result.Format = dirtyMeta.CleanMetas.Select(cm => ColumnDescriptionFactory.GetFormat(cm.PropertyRoutes)).Distinct().Only();
result.Unit = dirtyMeta.CleanMetas.Select(cm => ColumnDescriptionFactory.GetUnit(cm.PropertyRoutes)).Distinct().Only();
}
result.IsAllowed = () => me?.Meta.IsAllowed();
if (ForcePropertyRoute != null)
result.PropertyRoute = ForcePropertyRoute!;
if (ForceImplementations != null)
result.Implementations = ForceImplementations;
if (ForceFormat != null)
result.Format = ForceFormat;
if (ForceUnit != null)
result.Unit = ForceUnit;
if (ForceIsAllowed != null)
result.IsAllowed = ForceIsAllowed!;
return result;
});
return new ExtensionToken(parent, Key, Type, IsProjection, info.Unit, info.Format,
info.Implementations, info.IsAllowed(), info.PropertyRoute, displayName: NiceName());
}
}
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
public class ExtensionRouteInfo
{
public string? Format;
public string? Unit;
public Implementations? Implementations;
public Func<string?> IsAllowed;
public PropertyRoute? PropertyRoute;
}
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace HoDashboard.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//
// OpenTemplate
// Copyright (c) 2006
// by OpenArrow Software ( http://www.openarrow.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using OpenArrow.Templating.Directives;
using OpenArrow.Utils;
using OpenArrow.Reporting;
using OpenArrow.Templating.Properties;
using System.Security.Permissions;
namespace OpenArrow.Templating.Parsing
{
/// <summary>
/// A Template Parser that expects ASP.Net style syntax
/// </summary>
/// <remarks>
/// <para>
/// The ASP.Net Template Syntax is, as one would expect, derived from the syntax used to create ASP.Net Pages and Controls.
/// The syntax is simple and if you already know how to use ASP.Net, you don't have much to learn!
/// </para>
/// <para>
/// First, there are 1 or more lines of "Directives"
/// (<see cref="OpenArrow.Templating.Directives.IDirective"/>) which provide metadata describing the template and the form
/// of the generated code. The remainder of the template consists of "Segments" which come in two forms: "Literal Segments",
/// and "Code Segments". A Literal Segment is dumped as-is into the output when the template is run, literal segments are any text
/// that is not surrounded by '<%' and '%>'. A Code Segment is code that is executed when the template is run. Code
/// Segments must make calls to the <see cref="TextWriter"/> object called "output" that automatically exists in all templates in
/// order to display text. Code Segments come in a few sub types as well, as described below:
/// <list type="table">
/// <listheader>
/// <term>Name (Delimiters)</term>
/// <description>Purpose</description>
/// </listheader>
/// <item>
/// <term>Output Segment (<%= %>)</term>
/// <description>
/// Code in these segments are wrapped in calls to "output.WriteLine()" to aid the developer.
/// The contents of an Output Segment must be an expression of type String
/// </description>
/// </item>
/// <item>
/// <term>Declaration Segment (<%! %>)</term>
/// <description>
/// Code in these segments are placed in the body of the class
/// (rather than in the <see cref="OpenArrow.Templating.ITemplate.Render(TextWriter, IProgressReporter)"/> method). The contents of a Declaration
/// Segment must be one or more Type Members (Properties, Fields, Methods, etc.).
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>Here is a short example for using template parsers and generators:</para>
/// <example language="C#">
/// <code>
/// using System;
/// using System.IO;
///
/// using OpenArrow.Templating.Parsing;
/// using OpenArrow.Templating.Compilation;
///
/// public class MyQuickGenerator()
/// {
/// public static void Main(string[] args)
/// {
/// // Create the parser and generator
/// ITemplateParser parser = new ASPNetStyleTemplateParser();
/// ITemplateGenerator generator = new StandardTemplateGenerator();
///
/// // Open a file stream and stream reader for the template
/// FileStream stream = new FileStream("MyTemplate.template", FileAccess.Read);
/// StreamReader reader = new StreamReader(stream);
///
/// // Parse the template
/// TemplateParserResults parserResults = parser.Parse(reader);
///
/// // Check for problems
/// if(!parserResults.Success)
/// {
/// Console.WriteLine("Errors Occurred!");
/// return;
/// }
///
/// // Generate a CodeCompileUnit from the template
/// TemplateGeneratorResults generatorResults = generator.Generate(parserResults.Output, "MyTemplate.template");
///
/// // Check for problems
/// if(!parserResults.Success)
/// {
/// Console.WriteLine("Errors Occurred!");
/// return;
/// }
///
/// // Do what you want with the Compile Unit now!
/// }
/// }
/// </code>
/// </example>
/// <example language="VB">Coming Soon!</example>
/// <example language="C++">Sorry, no C++ examples are available. Use the C# example as a basis.</example>
/// </remarks>
public class AspNetStyleTemplateParser : ITemplateParser
{
/// <summary>
/// Constructs a new <see cref="AspNetStyleTemplateParser"/> objects.
/// </summary>
public AspNetStyleTemplateParser() { }
#region ITemplateParser Members
/// <summary>
/// Parses the specified template source file
/// <seealso cref="OpenArrow.Templating.Parsing.ITemplateParser"/>
/// </summary>
/// <param name="input">The input reader to read the template from</param>
/// <returns>The results of the parsing operation</returns>
/// <exception cref="OpenArrow.Templating.ActionProblemsException">A large number of errors occurred in the operation and it had to be aborted</exception>
/// <exception cref="System.IO.IOException">An I/O error occurs</exception>
/// <exception cref="ArgumentNullException"><paramref name="input"/> is <see langword="null"/></exception>
public TemplateParserResults Parse(TextReader input)
{
return Parse(input, new NullProgressReporter());
}
/// <summary>
/// Parses the specified template source file
/// <seealso cref="OpenArrow.Templating.Parsing.ITemplateParser"/>
/// </summary>
/// <remarks>This method reports its progress to a given progress reporter</remarks>
/// <param name="input">The input reader to read the template from</param>
/// <param name="reporter">The progress reporter to report to</param>
/// <returns>The results of the parsing operation</returns>
/// <exception cref="OpenArrow.Templating.ActionProblemsException">A large number of errors occurred in the operation and it had to be aborted</exception>
/// <exception cref="System.IO.IOException">An I/O error occurs</exception>
/// <exception cref="ArgumentNullException"><paramref name="input"/> is <see langword="null"/></exception>
public TemplateParserResults Parse(TextReader input, IProgressReporter reporter)
{
if (input == null)
throw new ArgumentNullException(String.Format(Resources.Exception_ArgIsNull, "input"), "input");
if (reporter == null)
reporter = new NullProgressReporter();
TemplateParserResults results = new TemplateParserResults();
ParsedTemplate template = new ParsedTemplate();
//int lineNo = 1;
//string line = null;
//using (reporter.StartTask(Resources.Task_ParsingDirectives))
//{
// while ((line = input.ReadLine()) != null)
// {
// // State Changes
// if (!line.StartsWith("<%@"))
// break; // Finished reading the directives
// ReadDirective(line, lineNo, results.Problems, template, reporter);
// lineNo++;
// }
//}
//if (template.TemplateDirective == null)
// results.Problems.Add(Problem.Error_TemplateDirectiveNotFound());
using (reporter.StartTask(Resources.Task_ParsingSegments))
{
// Parse out the segments
//TextReader reader = new ChainedTextReader(new TextReader[] { new StringReader(line + '\n'), input });
template.Segments.AddRange(ParseSegments(input /*reader*/, lineNo, reporter));
}
results.Output = template;
results.Success = (results.Problems.ErrorCount == 0);
return results;
}
#endregion
#region Private Methods
private static List<Segment> ParseSegments(TextReader reader, int lineNo, IProgressReporter reporter)
{
bool inCode = false;
int currentStartLine = lineNo;
List<Segment> segments = new List<Segment>();
StringBuilder currentSegment = new StringBuilder();
// Start char-by-char parsing
int i = -1;
reporter.StartTask(Resources.Task_ParsingLiteralSegment);
while ((i = reader.Read()) != -1)
{
char c = (char)i;
if ((!inCode) && (c == '<') && (reader.Peek() == (int)'%'))
{
// Add the new segment
AddSegment(segments, currentSegment, true, currentStartLine, lineNo);
currentSegment = new StringBuilder();
currentStartLine = lineNo;
// Consume the '%'
reader.Read();
// Move to "code-mode"
inCode = true;
reporter.EndTask();
reporter.StartTask(Resources.Task_ParsingCodeSegment);
// Read the next char
continue;
}
else if ((inCode) && (c == '%') && (reader.Peek() == (int)'>'))
{
// Add the new segment
AddSegment(segments, currentSegment, false, currentStartLine, lineNo);
currentSegment = new StringBuilder();
currentStartLine = lineNo;
// Consume the '>'
reader.Read();
// Move to "literal-mode"
inCode = false;
reporter.EndTask();
reporter.StartTask(Resources.Task_ParsingLiteralSegment);
// Read the next char
continue;
}
// TODO: Remove Hard-Coded Line endings
if (c == '\r') // Mac and Windows (\r and \r\n respectively)
{
lineNo++;
if (reader.Peek() == (int)'\n')
reader.Read(); // Consume the extra \n on Windows
c = '\n';
}
else if (c == '\n') // Unix (\n)
{
lineNo++;
}
currentSegment.Append(c);
}
AddSegment(segments, currentSegment, inCode, currentStartLine, lineNo);
reporter.EndTask();
return segments;
}
private static void AddSegment(List<Segment> segments, StringBuilder currentSegment, bool isLiteral,
int startLine, int endLine)
{
string segmentContent = currentSegment.ToString();
if (segmentContent.Length > 0)
segments.Add(new Segment(isLiteral, segmentContent, startLine, endLine));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)")]
private static void ReadDirective(string line, int lineNo, ProblemCollection problems, ParsedTemplate template, IProgressReporter reporter)
{
// Sample Directive: '<%@ Directive Attribute="Value" Attribute="Value" %>'
string directiveContent = StringUtils.StripOuter(line, 3, 2).Trim();
// Take character until the first whitespace
int curIndex = 0;
string directiveName = StringUtils.TakeUntil(directiveContent, curIndex, delegate(char c) { return Char.IsWhiteSpace(c); }, out curIndex);
int invalidIndex = directiveName.IndexOfAny(new char[] { '=', '"', '\'' });
if (invalidIndex != -1)
{
problems.Add(Problem.Error_InvalidCharacterInDirectiveName(directiveName[invalidIndex], lineNo, invalidIndex + 1));
return;
}
using (reporter.StartTask(String.Format(Resources.Task_ParsingDirective, directiveName)))
{
// Read Attributes
NameValueCollection attributes = new NameValueCollection();
while (curIndex < line.Length)
{
}
IDirective directive = DirectiveManager.BuildDirective(directiveName, attributes, lineNo, problems, reporter);
TemplateDirective templateDir = directive as TemplateDirective;
if (templateDir != null)
template.TemplateDirective = templateDir;
else
template.Directives.Add(directive);
}
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Text;
namespace LumiSoft.Net.Mime
{
/// <summary>
/// Provides mime related utility methods.
/// </summary>
[Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")]
public class MimeUtils
{
#region static method ParseDate
// TODO get rid of this method, only IMAP uses it
/// <summary>
/// Parses rfc 2822 datetime.
/// </summary>
/// <param name="date">Date string.</param>
/// <returns></returns>
public static DateTime ParseDate(string date)
{
/* Rfc 2822 3.3. Date and Time Specification.
date-time = [ day-of-week "," ] date FWS time [CFWS]
date = day month year
time = hour ":" minute [ ":" second ] FWS zone
*/
/* IMAP date format.
date-time = date FWS time [CFWS]
date = day-month-year
time = hour ":" minute [ ":" second ] FWS zone
*/
// zone = (( "+" / "-" ) 4DIGIT)
//--- Replace timezone constants -------//
/*
UT -0000
GMT -0000
EDT -0400
EST -0500
CDT -0500
CST -0600
MDT -0600
MST -0700
PDT -0700
PST -0800
BST +0100 British Summer Time
*/
date = date.ToLower();
date = date.Replace("ut","-0000");
date = date.Replace("gmt","-0000");
date = date.Replace("edt","-0400");
date = date.Replace("est","-0500");
date = date.Replace("cdt","-0500");
date = date.Replace("cst","-0600");
date = date.Replace("mdt","-0600");
date = date.Replace("mst","-0700");
date = date.Replace("pdt","-0700");
date = date.Replace("pst","-0800");
date = date.Replace("bst","+0100");
//----------------------------------------//
//--- Replace month constants ---//
date = date.Replace("jan","01");
date = date.Replace("feb","02");
date = date.Replace("mar","03");
date = date.Replace("apr","04");
date = date.Replace("may","05");
date = date.Replace("jun","06");
date = date.Replace("jul","07");
date = date.Replace("aug","08");
date = date.Replace("sep","09");
date = date.Replace("oct","10");
date = date.Replace("nov","11");
date = date.Replace("dec","12");
//-------------------------------//
// If date contains optional "day-of-week,", remove it
if(date.IndexOf(',') > -1){
date = date.Substring(date.IndexOf(',') + 1);
}
// Remove () from date. "Mon, 13 Oct 2003 20:50:57 +0300 (EEST)"
if(date.IndexOf(" (") > -1){
date = date.Substring(0,date.IndexOf(" ("));
}
int year = 1900;
int month = 1;
int day = 1;
int hour = -1;
int minute = -1;
int second = -1;
int zoneMinutes = -1;
StringReader s = new StringReader(date);
//--- Pase date --------------------------------------------------------------------//
try{
day = Convert.ToInt32(s.ReadWord(true,new char[]{'.','-',' '},true));
}
catch{
throw new Exception("Invalid date value '" + date + "', invalid day value !");
}
try{
month = Convert.ToInt32(s.ReadWord(true,new char[]{'.','-',' '},true));
}
catch{
throw new Exception("Invalid date value '" + date + "', invalid month value !");
}
try{
year = Convert.ToInt32(s.ReadWord(true,new char[]{'.','-',' '},true));
}
catch{
throw new Exception("Invalid date value '" + date + "', invalid year value !");
}
//----------------------------------------------------------------------------------//
//--- Parse time -------------------------------------------------------------------//
// Time is optional, so parse it if its included.
if(s.Available > 0){
try{
hour = Convert.ToInt32(s.ReadWord(true,new char[]{':'},true));
}
catch{
throw new Exception("Invalid date value '" + date + "', invalid hour value !");
}
try{
minute = Convert.ToInt32(s.ReadWord(true,new char[]{':'},false));
}
catch{
throw new Exception("Invalid date value '" + date + "', invalid minute value !");
}
s.ReadToFirstChar();
if(s.StartsWith(":")){
s.ReadSpecifiedLength(1);
try{
string secondString = s.ReadWord(true,new char[]{' '},true);
// Milli seconds specified, remove them.
if(secondString.IndexOf('.') > -1){
secondString = secondString.Substring(0,secondString.IndexOf('.'));
}
second = Convert.ToInt32(secondString);
}
catch{
throw new Exception("Invalid date value '" + date + "', invalid second value !");
}
}
s.ReadToFirstChar();
if(s.Available > 3){
string timezone = s.SourceString.Replace(":","");
if(timezone.StartsWith("+") || timezone.StartsWith("-")){
bool utc_add_time = timezone.StartsWith("+");
// Remove +/- sign
timezone = timezone.Substring(1);
// padd time zone to 4 symbol. For example 200, will be 0200.
while(timezone.Length < 4){
timezone = "0" + timezone;
}
try{
// time zone format hours|minutes
int h = Convert.ToInt32(timezone.Substring(0,2));
int m = Convert.ToInt32(timezone.Substring(2));
if(utc_add_time){
zoneMinutes = 0 - ((h * 60) + m);
}
else{
zoneMinutes = (h * 60) + m;
}
}
catch{ // Just skip time zone, if can't parse
}
}
}
}
//---------------------------------------------------------------------------------//
// Convert time to UTC
if(hour != -1 && minute != -1 && second != -1){
DateTime d = new DateTime(year,month,day,hour,minute,second).AddMinutes(zoneMinutes);
return new DateTime(d.Year,d.Month,d.Day,d.Hour,d.Minute,d.Second,DateTimeKind.Utc).ToLocalTime();
}
else{
return new DateTime(year,month,day);
}
}
#endregion
#region static method DateTimeToRfc2822
/// <summary>
/// Converts date to rfc 2822 date time string.
/// </summary>
/// <param name="dateTime">Date time value.</param>
/// <returns></returns>
public static string DateTimeToRfc2822(DateTime dateTime)
{
return dateTime.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo);
}
#endregion
#region static method ParseHeaders
/// <summary>
/// Parses headers from message or mime entry.
/// </summary>
/// <param name="entryStrm">Stream from where to read headers.</param>
/// <returns>Returns header lines.</returns>
public static string ParseHeaders(Stream entryStrm)
{
/* Rfc 2822 3.1. GENERAL DESCRIPTION
A message consists of header fields and, optionally, a body.
The body is simply a sequence of lines containing ASCII charac-
ters. It is separated from the headers by a null line (i.e., a
line with nothing preceding the CRLF).
*/
byte[] crlf = new byte[]{(byte)'\r',(byte)'\n'};
MemoryStream msHeaders = new MemoryStream();
StreamLineReader r = new StreamLineReader(entryStrm);
byte[] lineData = r.ReadLine();
while(lineData != null){
if(lineData.Length == 0){
break;
}
msHeaders.Write(lineData,0,lineData.Length);
msHeaders.Write(crlf,0,crlf.Length);
lineData = r.ReadLine();
}
return System.Text.Encoding.Default.GetString(msHeaders.ToArray());
}
#endregion
#region static method ParseHeaderField
/// <summary>
/// Parse header specified header field value.
///
/// Use this method only if you need to get only one header field, otherwise use
/// MimeParser.ParseHeaderField(string fieldName,string headers).
/// This avoid parsing headers multiple times.
/// </summary>
/// <param name="fieldName">Header field which to parse. Eg. Subject: .</param>
/// <param name="entryStrm">Stream from where to read headers.</param>
/// <returns></returns>
public static string ParseHeaderField(string fieldName,Stream entryStrm)
{
return ParseHeaderField(fieldName,ParseHeaders(entryStrm));
}
/// <summary>
/// Parse header specified header field value.
/// </summary>
/// <param name="fieldName">Header field which to parse. Eg. Subject: .</param>
/// <param name="headers">Full headers string. Use MimeParser.ParseHeaders() to get this value.</param>
public static string ParseHeaderField(string fieldName,string headers)
{
/* Rfc 2822 2.2 Header Fields
Header fields are lines composed of a field name, followed by a colon
(":"), followed by a field body, and terminated by CRLF. A field
name MUST be composed of printable US-ASCII characters (i.e.,
characters that have values between 33 and 126, inclusive), except
colon. A field body may be composed of any US-ASCII characters,
except for CR and LF. However, a field body may contain CRLF when
used in header "folding" and "unfolding" as described in section
2.2.3. All field bodies MUST conform to the syntax described in
sections 3 and 4 of this standard.
Rfc 2822 2.2.3 (Multiline header fields)
The process of moving from this folded multiple-line representation
of a header field to its single line representation is called
"unfolding". Unfolding is accomplished by simply removing any CRLF
that is immediately followed by WSP. Each header field should be
treated in its unfolded form for further syntactic and semantic
evaluation.
Example:
Subject: aaaaa<CRLF>
<TAB or SP>aaaaa<CRLF>
*/
using(TextReader r = new StreamReader(new MemoryStream(System.Text.Encoding.Default.GetBytes(headers)))){
string line = r.ReadLine();
while(line != null){
// Find line where field begins
if(line.ToUpper().StartsWith(fieldName.ToUpper())){
// Remove field name and start reading value
string fieldValue = line.Substring(fieldName.Length).Trim();
// see if multi line value. See commnt above.
line = r.ReadLine();
while(line != null && (line.StartsWith("\t") || line.StartsWith(" "))){
fieldValue += line;
line = r.ReadLine();
}
return fieldValue;
}
line = r.ReadLine();
}
}
return "";
}
#endregion
#region static function ParseHeaderFiledParameter
/// <summary>
/// Parses header field parameter value.
/// For example: CONTENT-TYPE: application\octet-stream; name="yourFileName.xxx",
/// fieldName="CONTENT-TYPE:" and subFieldName="name".
/// </summary>
/// <param name="fieldName">Main header field name.</param>
/// <param name="parameterName">Header field's parameter name.</param>
/// <param name="headers">Full headrs string.</param>
/// <returns></returns>
public static string ParseHeaderFiledParameter(string fieldName,string parameterName,string headers)
{
string mainFiled = ParseHeaderField(fieldName,headers);
// Parse sub field value
if(mainFiled.Length > 0){
int index = mainFiled.ToUpper().IndexOf(parameterName.ToUpper());
if(index > -1){
mainFiled = mainFiled.Substring(index + parameterName.Length + 1); // Remove "subFieldName="
// subFieldName value may be in "" and without
if(mainFiled.StartsWith("\"")){
return mainFiled.Substring(1,mainFiled.IndexOf("\"",1) - 1);
}
// value without ""
else{
int endIndex = mainFiled.Length;
if(mainFiled.IndexOf(" ") > -1){
endIndex = mainFiled.IndexOf(" ");
}
return mainFiled.Substring(0,endIndex);
}
}
}
return "";
}
#endregion
#region static method ParseMediaType
/// <summary>
/// Parses MediaType_enum from <b>Content-Type:</b> header field value.
/// </summary>
/// <param name="headerFieldValue"><b>Content-Type:</b> header field value. This value can be null, then MediaType_enum.NotSpecified.</param>
/// <returns></returns>
public static MediaType_enum ParseMediaType(string headerFieldValue)
{
if(headerFieldValue == null){
return MediaType_enum.NotSpecified;
}
string contentType = TextUtils.SplitString(headerFieldValue,';')[0].ToLower();
//--- Text/xxx --------------------------------//
if(contentType.IndexOf("text/plain") > -1){
return MediaType_enum.Text_plain;
}
else if(contentType.IndexOf("text/html") > -1){
return MediaType_enum.Text_html;
}
else if(contentType.IndexOf("text/xml") > -1){
return MediaType_enum.Text_xml;
}
else if(contentType.IndexOf("text/rtf") > -1){
return MediaType_enum.Text_rtf;
}
else if(contentType.IndexOf("text") > -1){
return MediaType_enum.Text;
}
//---------------------------------------------//
//--- Image/xxx -------------------------------//
else if(contentType.IndexOf("image/gif") > -1){
return MediaType_enum.Image_gif;
}
else if(contentType.IndexOf("image/tiff") > -1){
return MediaType_enum.Image_tiff;
}
else if(contentType.IndexOf("image/jpeg") > -1){
return MediaType_enum.Image_jpeg;
}
else if(contentType.IndexOf("image") > -1){
return MediaType_enum.Image;
}
//---------------------------------------------//
//--- Audio/xxx -------------------------------//
else if(contentType.IndexOf("audio") > -1){
return MediaType_enum.Audio;
}
//---------------------------------------------//
//--- Video/xxx -------------------------------//
else if(contentType.IndexOf("video") > -1){
return MediaType_enum.Video;
}
//---------------------------------------------//
//--- Application/xxx -------------------------//
else if(contentType.IndexOf("application/octet-stream") > -1){
return MediaType_enum.Application_octet_stream;
}
else if(contentType.IndexOf("application") > -1){
return MediaType_enum.Application;
}
//---------------------------------------------//
//--- Multipart/xxx ---------------------------//
else if(contentType.IndexOf("multipart/mixed") > -1){
return MediaType_enum.Multipart_mixed;
}
else if(contentType.IndexOf("multipart/alternative") > -1){
return MediaType_enum.Multipart_alternative;
}
else if(contentType.IndexOf("multipart/parallel") > -1){
return MediaType_enum.Multipart_parallel;
}
else if(contentType.IndexOf("multipart/related") > -1){
return MediaType_enum.Multipart_related;
}
else if(contentType.IndexOf("multipart/signed") > -1){
return MediaType_enum.Multipart_signed;
}
else if(contentType.IndexOf("multipart") > -1){
return MediaType_enum.Multipart;
}
//---------------------------------------------//
//--- Message/xxx -----------------------------//
else if(contentType.IndexOf("message/rfc822") > -1){
return MediaType_enum.Message_rfc822;
}
else if(contentType.IndexOf("message") > -1){
return MediaType_enum.Message;
}
//---------------------------------------------//
else{
return MediaType_enum.Unknown;
}
}
#endregion
#region static method MediaTypeToString
/// <summary>
/// Converts MediaType_enum to string. NOTE: Returns null for MediaType_enum.NotSpecified.
/// </summary>
/// <param name="mediaType">MediaType_enum value to convert.</param>
/// <returns></returns>
public static string MediaTypeToString(MediaType_enum mediaType)
{
//--- Text/xxx --------------------------------//
if(mediaType == MediaType_enum.Text_plain){
return "text/plain";
}
else if(mediaType == MediaType_enum.Text_html){
return "text/html";
}
else if(mediaType == MediaType_enum.Text_xml){
return "text/xml";
}
else if(mediaType == MediaType_enum.Text_rtf){
return "text/rtf";
}
else if(mediaType == MediaType_enum.Text){
return "text";
}
//---------------------------------------------//
//--- Image/xxx -------------------------------//
else if(mediaType == MediaType_enum.Image_gif){
return "image/gif";
}
else if(mediaType == MediaType_enum.Image_tiff){
return "image/tiff";
}
else if(mediaType == MediaType_enum.Image_jpeg){
return "image/jpeg";
}
else if(mediaType == MediaType_enum.Image){
return "image";
}
//---------------------------------------------//
//--- Audio/xxx -------------------------------//
else if(mediaType == MediaType_enum.Audio){
return "audio";
}
//---------------------------------------------//
//--- Video/xxx -------------------------------//
else if(mediaType == MediaType_enum.Video){
return "video";
}
//---------------------------------------------//
//--- Application/xxx -------------------------//
else if(mediaType == MediaType_enum.Application_octet_stream){
return "application/octet-stream";
}
else if(mediaType == MediaType_enum.Application){
return "application";
}
//---------------------------------------------//
//--- Multipart/xxx ---------------------------//
else if(mediaType == MediaType_enum.Multipart_mixed){
return "multipart/mixed";
}
else if(mediaType == MediaType_enum.Multipart_alternative){
return "multipart/alternative";
}
else if(mediaType == MediaType_enum.Multipart_parallel){
return "multipart/parallel";
}
else if(mediaType == MediaType_enum.Multipart_related){
return "multipart/related";
}
else if(mediaType == MediaType_enum.Multipart_signed){
return "multipart/signed";
}
else if(mediaType == MediaType_enum.Multipart){
return "multipart";
}
//---------------------------------------------//
//--- Message/xxx -----------------------------//
else if(mediaType == MediaType_enum.Message_rfc822){
return "message/rfc822";
}
else if(mediaType == MediaType_enum.Message){
return "message";
}
//---------------------------------------------//
else if(mediaType == MediaType_enum.Unknown){
return "unknown";
}
else{
return null;
}
}
#endregion
#region static method ParseContentTransferEncoding
/// <summary>
/// Parses ContentTransferEncoding_enum from <b>Content-Transfer-Encoding:</b> header field value.
/// </summary>
/// <param name="headerFieldValue"><b>Content-Transfer-Encoding:</b> header field value. This value can be null, then ContentTransferEncoding_enum.NotSpecified.</param>
/// <returns></returns>
public static ContentTransferEncoding_enum ParseContentTransferEncoding(string headerFieldValue)
{
if(headerFieldValue == null){
return ContentTransferEncoding_enum.NotSpecified;
}
string encoding = headerFieldValue.ToLower();
if(encoding == "7bit"){
return ContentTransferEncoding_enum._7bit;
}
else if(encoding == "quoted-printable"){
return ContentTransferEncoding_enum.QuotedPrintable;
}
else if(encoding == "base64"){
return ContentTransferEncoding_enum.Base64;
}
else if(encoding == "8bit"){
return ContentTransferEncoding_enum._8bit;
}
else if(encoding == "binary"){
return ContentTransferEncoding_enum.Binary;
}
else{
return ContentTransferEncoding_enum.Unknown;
}
}
#endregion
#region static method ContentTransferEncodingToString
/// <summary>
/// Converts ContentTransferEncoding_enum to string. NOTE: Returns null for ContentTransferEncoding_enum.NotSpecified.
/// </summary>
/// <param name="encoding">ContentTransferEncoding_enum value to convert.</param>
/// <returns></returns>
public static string ContentTransferEncodingToString(ContentTransferEncoding_enum encoding)
{
if(encoding == ContentTransferEncoding_enum._7bit){
return "7bit";
}
else if(encoding == ContentTransferEncoding_enum.QuotedPrintable){
return "quoted-printable";
}
else if(encoding == ContentTransferEncoding_enum.Base64){
return "base64";
}
else if(encoding == ContentTransferEncoding_enum._8bit){
return "8bit";
}
else if(encoding == ContentTransferEncoding_enum.Binary){
return "binary";
}
else if(encoding == ContentTransferEncoding_enum.Unknown){
return "unknown";
}
else{
return null;
}
}
#endregion
#region static method ParseContentDisposition
/// <summary>
/// Parses ContentDisposition_enum from <b>Content-Disposition:</b> header field value.
/// </summary>
/// <param name="headerFieldValue"><b>Content-Disposition:</b> header field value. This value can be null, then ContentDisposition_enum.NotSpecified.</param>
/// <returns></returns>
public static ContentDisposition_enum ParseContentDisposition(string headerFieldValue)
{
if(headerFieldValue == null){
return ContentDisposition_enum.NotSpecified;
}
string disposition = headerFieldValue.ToLower();
if(disposition.IndexOf("attachment") > -1){
return ContentDisposition_enum.Attachment;
}
else if(disposition.IndexOf("inline") > -1){
return ContentDisposition_enum.Inline;
}
else{
return ContentDisposition_enum.Unknown;
}
}
#endregion
#region static method ContentDispositionToString
/// <summary>
/// Converts ContentDisposition_enum to string. NOTE: Returns null for ContentDisposition_enum.NotSpecified.
/// </summary>
/// <param name="disposition">ContentDisposition_enum value to convert.</param>
/// <returns></returns>
public static string ContentDispositionToString(ContentDisposition_enum disposition)
{
if(disposition == ContentDisposition_enum.Attachment){
return "attachment";
}
else if(disposition == ContentDisposition_enum.Inline){
return "inline";
}
else if(disposition == ContentDisposition_enum.Unknown){
return "unknown";
}
else{
return null;
}
}
#endregion
#region static method EncodeWord
/// <summary>
/// Encodes specified text as "encoded-word" if encode is required. For more information see RFC 2047.
/// </summary>
/// <param name="text">Text to encode.</param>
/// <returns>Returns encoded word.</returns>
public static string EncodeWord(string text)
{
if(text == null){
return null;
}
if(Core.IsAscii(text)){
return text;
}
/* RFC 2047 2. Syntax of encoded-words.
An 'encoded-word' is defined by the following ABNF grammar. The
notation of RFC 822 is used, with the exception that white space
characters MUST NOT appear between components of an 'encoded-word'.
encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
charset = token ; see section 3
encoding = token ; see section 4
token = 1*<Any CHAR except SPACE, CTLs, and especials>
especials = "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / "
<"> / "/" / "[" / "]" / "?" / "." / "="
encoded-text = 1*<Any printable ASCII character other than "?" or SPACE>
; (but see "Use of encoded-words in message headers", section 5)
Both 'encoding' and 'charset' names are case-independent. Thus the
charset name "ISO-8859-1" is equivalent to "iso-8859-1", and the
encoding named "Q" may be spelled either "Q" or "q".
An 'encoded-word' may not be more than 75 characters long, including
'charset', 'encoding', 'encoded-text', and delimiters. If it is
desirable to encode more text than will fit in an 'encoded-word' of
75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may
be used.
IMPORTANT: 'encoded-word's are designed to be recognized as 'atom's
by an RFC 822 parser. As a consequence, unencoded white space
characters (such as SPACE and HTAB) are FORBIDDEN within an
'encoded-word'. For example, the character sequence
=?iso-8859-1?q?this is some text?=
would be parsed as four 'atom's, rather than as a single 'atom' (by
an RFC 822 parser) or 'encoded-word' (by a parser which understands
'encoded-words'). The correct way to encode the string "this is some
text" is to encode the SPACE characters as well, e.g.
=?iso-8859-1?q?this=20is=20some=20text?=
*/
/*
char[] especials = new char[]{'(',')','<','>','@',',',';',':','"','/','[',']','?','.','='};
// See if need to enode.
if(!Core.IsAscii(text)){
}*/
return Core.CanonicalEncode(text,"utf-8");
}
#endregion
#region static method DecodeWords
/// <summary>
/// Decodes "encoded-word"'s from the specified text. For more information see RFC 2047.
/// </summary>
/// <param name="text">Text to decode.</param>
/// <returns>Returns decoded text.</returns>
public static string DecodeWords(string text)
{
if(text == null){
return null;
}
/* RFC 2047 2. Syntax of encoded-words.
An 'encoded-word' is defined by the following ABNF grammar. The
notation of RFC 822 is used, with the exception that white space
characters MUST NOT appear between components of an 'encoded-word'.
encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
charset = token ; see section 3
encoding = token ; see section 4
token = 1*<Any CHAR except SPACE, CTLs, and especials>
especials = "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / "
<"> / "/" / "[" / "]" / "?" / "." / "="
encoded-text = 1*<Any printable ASCII character other than "?" or SPACE>
; (but see "Use of encoded-words in message headers", section 5)
Both 'encoding' and 'charset' names are case-independent. Thus the
charset name "ISO-8859-1" is equivalent to "iso-8859-1", and the
encoding named "Q" may be spelled either "Q" or "q".
An 'encoded-word' may not be more than 75 characters long, including
'charset', 'encoding', 'encoded-text', and delimiters. If it is
desirable to encode more text than will fit in an 'encoded-word' of
75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may
be used.
IMPORTANT: 'encoded-word's are designed to be recognized as 'atom's
by an RFC 822 parser. As a consequence, unencoded white space
characters (such as SPACE and HTAB) are FORBIDDEN within an
'encoded-word'. For example, the character sequence
=?iso-8859-1?q?this is some text?=
would be parsed as four 'atom's, rather than as a single 'atom' (by
an RFC 822 parser) or 'encoded-word' (by a parser which understands
'encoded-words'). The correct way to encode the string "this is some
text" is to encode the SPACE characters as well, e.g.
=?iso-8859-1?q?this=20is=20some=20text?=
*/
StringReader r = new StringReader(text);
StringBuilder retVal = new StringBuilder();
// We need to loop all words, if encoded word, decode it, othwerwise just append to return value.
bool lastIsEncodedWord = false;
while(r.Available > 0){
string whiteSpaces = r.ReadToFirstChar();
// Probably is encoded-word, we try to parse it.
if(r.StartsWith("=?") && r.SourceString.IndexOf("?=") > -1){
StringBuilder encodedWord = new StringBuilder();
string decodedWord = null;
try{
// NOTE: We can't read encoded word and then split !!!, we need to read each part.
// Remove =?
encodedWord.Append(r.ReadSpecifiedLength(2));
// Read charset
string charset = r.QuotedReadToDelimiter('?');
encodedWord.Append(charset + "?");
// Read encoding
string encoding = r.QuotedReadToDelimiter('?');
encodedWord.Append(encoding + "?");
// Read text
string encodedText = r.QuotedReadToDelimiter('?');
encodedWord.Append(encodedText + "?");
// We must have remaining '=' here
if(r.StartsWith("=")){
encodedWord.Append(r.ReadSpecifiedLength(1));
Encoding c = Encoding.GetEncoding(charset);
if(encoding.ToLower() == "q"){
decodedWord = Core.QDecode(c,encodedText);
}
else if(encoding.ToLower() == "b"){
decodedWord = c.GetString(Core.Base64Decode(Encoding.Default.GetBytes(encodedText)));
}
}
}
catch{
// Not encoded-word or contains unknwon charset/encoding, so leave
// encoded-word as is.
}
/* RFC 2047 6.2.
When displaying a particular header field that contains multiple
'encoded-word's, any 'linear-white-space' that separates a pair of
adjacent 'encoded-word's is ignored. (This is to allow the use of
multiple 'encoded-word's to represent long strings of unencoded text,
without having to separate 'encoded-word's where spaces occur in the
unencoded text.)
*/
if(!lastIsEncodedWord){
retVal.Append(whiteSpaces);
}
// Decoding failed for that encoded-word, leave encoded-word as is.
if(decodedWord == null){
retVal.Append(encodedWord.ToString());
}
// We deocded encoded-word successfully.
else{
retVal.Append(decodedWord);
}
lastIsEncodedWord = true;
}
// Normal word.
else if(r.StartsWithWord()){
retVal.Append(whiteSpaces + r.ReadWord(false));
lastIsEncodedWord = false;
}
// We have some separator or parenthesize.
else{
retVal.Append(whiteSpaces + r.ReadSpecifiedLength(1));
}
}
return retVal.ToString();
}
#endregion
#region static method EncodeHeaderField
/// <summary>
/// Encodes header field with quoted-printable encoding, if value contains ANSI or UNICODE chars.
/// </summary>
/// <param name="text">Text to encode.</param>
/// <returns></returns>
public static string EncodeHeaderField(string text)
{
if(Core.IsAscii(text)){
return text;
}
// First try to encode quoted strings("unicode-text") only, if no
// quoted strings, encode full text.
if(text.IndexOf("\"") > -1){
string retVal = text;
int offset = 0;
while(offset < retVal.Length - 1){
int quoteStartIndex = retVal.IndexOf("\"",offset);
// There is no more qouted strings, but there are some text left
if(quoteStartIndex == -1){
break;
}
int quoteEndIndex = retVal.IndexOf("\"",quoteStartIndex + 1);
// If there isn't closing quote, encode full text
if(quoteEndIndex == -1){
break;
}
string leftPart = retVal.Substring(0,quoteStartIndex);
string rightPart = retVal.Substring(quoteEndIndex + 1);
string quotedString = retVal.Substring(quoteStartIndex + 1,quoteEndIndex - quoteStartIndex - 1);
// Encode only not ASCII text
if(!Core.IsAscii(quotedString)){
string quotedStringCEncoded = Core.CanonicalEncode(quotedString,"utf-8");
retVal = leftPart + "\"" + quotedStringCEncoded + "\"" + rightPart;
offset += quoteEndIndex + 1 + quotedStringCEncoded.Length - quotedString.Length;
}
else{
offset += quoteEndIndex + 1;
}
}
// See if all encoded ok, if not encode all text
if(Core.IsAscii(retVal)){
return retVal;
}
else{
// REMOVE ME:(12.10.2006) Fixed, return Core.CanonicalEncode(retVal,"utf-8");
return Core.CanonicalEncode(text,"utf-8");
}
}
return Core.CanonicalEncode(text,"utf-8");
}
#endregion
#region static method CreateMessageID
/// <summary>
/// Creates Rfc 2822 3.6.4 message-id. Syntax: '<' id-left '@' id-right '>'.
/// </summary>
/// <returns></returns>
public static string CreateMessageID()
{
return "<" + Guid.NewGuid().ToString().Replace("-","") + "@" + Guid.NewGuid().ToString().Replace("-","") + ">";
}
#endregion
#region static method FoldData
/// <summary>
/// Folds long data line to folded lines.
/// </summary>
/// <param name="data">Data to fold.</param>
/// <returns></returns>
public static string FoldData(string data)
{
/* Folding rules:
*) Line may not be bigger than 76 chars.
*) If possible fold between TAB or SP
*) If no fold point, just fold from char 76
*/
// Data line too big, we need to fold data.
if(data.Length > 76){
int startPosition = 0;
int lastPossibleFoldPos = -1;
StringBuilder retVal = new StringBuilder();
for(int i=0;i<data.Length;i++){
char c = data[i];
// We have possible fold point
if(c == ' ' || c == '\t'){
lastPossibleFoldPos = i;
}
// End of data reached
if(i == (data.Length - 1)){
retVal.Append(data.Substring(startPosition));
}
// We need to fold
else if((i - startPosition) >= 76){
// There wasn't any good fold point(word is bigger than line), just fold from current position.
if(lastPossibleFoldPos == -1){
lastPossibleFoldPos = i;
}
retVal.Append(data.Substring(startPosition,lastPossibleFoldPos - startPosition) + "\r\n\t");
i = lastPossibleFoldPos;
lastPossibleFoldPos = -1;
startPosition = i;
}
}
return retVal.ToString();
}
else{
return data;
}
}
#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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
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 ToImmutableSortedSetTest()
{
var set = new[] { 1, 2, 2 }.ToImmutableSortedSet();
Assert.Same(Comparer<int>.Default, set.KeyComparer);
Assert.Equal(2, set.Count);
}
[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>(() => set[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => 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);
}
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 file="oledbconnectionstring.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.OleDb {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Microsoft.Win32;
using System.Runtime.Versioning;
internal struct SchemaSupport {
internal Guid _schemaRowset;
internal int _restrictions;
}
internal sealed class OleDbConnectionString : DbConnectionOptions {
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
internal static class KEY {
internal const string Asynchronous_Processing = "asynchronous processing";
internal const string Connect_Timeout = "connect timeout";
internal const string Data_Provider = "data provider";
internal const string Data_Source = "data source";
internal const string Extended_Properties = "extended properties";
internal const string File_Name = "file name";
internal const string Initial_Catalog = "initial catalog";
internal const string Ole_DB_Services = "ole db services";
internal const string Persist_Security_Info = "persist security info";
internal const string Prompt = "prompt";
internal const string Provider = "provider";
internal const string RemoteProvider = "remote provider";
internal const string WindowHandle = "window handle";
}
// registry key and dword value entry for udl pooling
private static class UDL {
internal const string Header = "\xfeff[oledb]\r\n; Everything after this line is an OLE DB initstring\r\n";
internal const string Location = "SOFTWARE\\Microsoft\\DataAccess\\Udl Pooling";
internal const string Pooling = "Cache Size";
static internal volatile bool _PoolSizeInit;
static internal int _PoolSize;
static internal volatile Dictionary<string,string> _Pool;
static internal object _PoolLock = new object();
}
private static class VALUES {
internal const string NoPrompt = "noprompt";
}
// set during ctor
internal readonly bool PossiblePrompt;
internal readonly string ActualConnectionString; // cached value passed to GetDataSource
private readonly string _expandedConnectionString;
internal SchemaSupport[] _schemaSupport;
internal int _sqlSupport;
internal bool _supportMultipleResults;
internal bool _supportIRow;
internal bool _hasSqlSupport;
internal bool _hasSupportMultipleResults, _hasSupportIRow;
private int _oledbServices;
// these are cached delegates (per unique connectionstring)
internal UnsafeNativeMethods.IUnknownQueryInterface DangerousDataSourceIUnknownQueryInterface;
internal UnsafeNativeMethods.IDBInitializeInitialize DangerousIDBInitializeInitialize;
internal UnsafeNativeMethods.IDBCreateSessionCreateSession DangerousIDBCreateSessionCreateSession;
internal UnsafeNativeMethods.IDBCreateCommandCreateCommand DangerousIDBCreateCommandCreateCommand;
// since IDBCreateCommand interface may not be supported for a particular provider (only IOpenRowset)
// we cache that fact rather than call QueryInterface on every call to Open
internal bool HaveQueriedForCreateCommand;
// SxS: if user specifies a value for "File Name=" (UDL) in connection string, OleDbConnectionString will load the connection string
// from the UDL file. The UDL file is opened as FileMode.Open, FileAccess.Read, FileShare.Read, allowing concurrent access to it.
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal OleDbConnectionString(string connectionString, bool validate) : base(connectionString) {
string prompt = this[KEY.Prompt];
PossiblePrompt = ((!ADP.IsEmpty(prompt) && (0 != String.Compare(prompt, VALUES.NoPrompt, StringComparison.OrdinalIgnoreCase)))
|| !ADP.IsEmpty(this[KEY.WindowHandle]));
if (!IsEmpty) {
string udlConnectionString = null;
if (!validate) {
int position = 0;
string udlFileName = null;
_expandedConnectionString = ExpandDataDirectories(ref udlFileName, ref position);
if (!ADP.IsEmpty(udlFileName)) { // fail via new FileStream vs. GetFullPath
udlFileName = ADP.GetFullPath(udlFileName); // MDAC 82833
}
if (null != udlFileName) {
udlConnectionString = LoadStringFromStorage(udlFileName);
if (!ADP.IsEmpty(udlConnectionString)) {
_expandedConnectionString = _expandedConnectionString.Substring(0, position) + udlConnectionString + ';' + _expandedConnectionString.Substring(position);
}
}
}
if (validate || ADP.IsEmpty(udlConnectionString)) {
ActualConnectionString = ValidateConnectionString(connectionString);
}
}
}
internal int ConnectTimeout {
get { return base.ConvertValueToInt32(KEY.Connect_Timeout, ADP.DefaultConnectionTimeout); }
}
internal string DataSource {
get { return base.ConvertValueToString(KEY.Data_Source, ADP.StrEmpty); }
}
internal string InitialCatalog {
get { return base.ConvertValueToString(KEY.Initial_Catalog, ADP.StrEmpty); }
}
internal string Provider {
get {
Debug.Assert(!ADP.IsEmpty(this[KEY.Provider]), "no Provider");
return this[KEY.Provider];
}
}
internal int OleDbServices {
get {
return _oledbServices;
}
}
internal SchemaSupport[] SchemaSupport { // OleDbConnection.GetSchemaRowsetInformation
get { return _schemaSupport; }
set { _schemaSupport = value; }
}
protected internal override System.Security.PermissionSet CreatePermissionSet() {
System.Security.PermissionSet permissionSet;
if (PossiblePrompt) {
permissionSet = new NamedPermissionSet("FullTrust");
}
else {
permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None);
permissionSet.AddPermission(new OleDbPermission(this));
}
return permissionSet;
}
protected internal override string Expand() {
if (null != _expandedConnectionString) {
return _expandedConnectionString;
}
else {
return base.Expand();
}
}
internal int GetSqlSupport(OleDbConnection connection) {
int sqlSupport = _sqlSupport;
if (!_hasSqlSupport) {
object value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_SQLSUPPORT);
if (value is Int32) { // not OleDbPropertyStatus
sqlSupport = (int) value;
}
_sqlSupport = sqlSupport;
_hasSqlSupport = true;
}
return sqlSupport;
}
internal bool GetSupportIRow(OleDbConnection connection, OleDbCommand command) {
bool supportIRow = _supportIRow;
if (!_hasSupportIRow) {
object value = command.GetPropertyValue(OleDbPropertySetGuid.Rowset, ODB.DBPROP_IRow);
// SQLOLEDB always returns VARIANT_FALSE for DBPROP_IROW, so base the answer on existance
supportIRow = !(value is OleDbPropertyStatus);
_supportIRow = supportIRow;
_hasSupportIRow = true;
}
return supportIRow;
}
internal bool GetSupportMultipleResults(OleDbConnection connection) {
bool supportMultipleResults = _supportMultipleResults;
if (!_hasSupportMultipleResults) {
object value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_MULTIPLERESULTS);
if (value is Int32) {// not OleDbPropertyStatus
supportMultipleResults = (ODB.DBPROPVAL_MR_NOTSUPPORTED != (int) value);
}
_supportMultipleResults = supportMultipleResults;
_hasSupportMultipleResults = true;
}
return supportMultipleResults;
}
static private int UdlPoolSize { // MDAC 69925
// SxS: UdpPoolSize reads registry value to get the pool size
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
get {
int poolsize = UDL._PoolSize;
if (!UDL._PoolSizeInit) {
object value = ADP.LocalMachineRegistryValue(UDL.Location, UDL.Pooling);
if (value is Int32) {
poolsize = (int) value;
poolsize = ((0 < poolsize) ? poolsize : 0);
UDL._PoolSize = poolsize;
}
UDL._PoolSizeInit = true;
}
return poolsize;
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
static private string LoadStringFromStorage(string udlfilename) {
string udlConnectionString = null;
Dictionary<string,string> udlcache = UDL._Pool;
if ((null == udlcache) || !udlcache.TryGetValue(udlfilename, out udlConnectionString)) {
udlConnectionString = LoadStringFromFileStorage(udlfilename);
if (null != udlConnectionString) {
Debug.Assert(!ADP.IsEmpty(udlfilename), "empty filename didn't fail");
if (0 < UdlPoolSize) {
Debug.Assert(udlfilename == ADP.GetFullPath(udlfilename), "only cache full path filenames"); // MDAC 82833
if (null == udlcache) {
udlcache = new Dictionary<string,string>();
udlcache[udlfilename] = udlConnectionString;
lock(UDL._PoolLock) {
if (null != UDL._Pool) {
udlcache = UDL._Pool;
}
else {
UDL._Pool = udlcache;
udlcache = null;
}
}
}
if (null != udlcache) {
lock(udlcache) {
udlcache[udlfilename] = udlConnectionString;
}
}
}
}
}
return udlConnectionString;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
static private string LoadStringFromFileStorage(string udlfilename) {
// Microsoft Data Link File Format
// The first two lines of a .udl file must have exactly the following contents in order to work properly:
// [oledb]
// ; Everything after this line is an OLE DB initstring
//
string connectionString = null;
Exception failure = null;
try {
int hdrlength = ADP.CharSize*UDL.Header.Length;
using(FileStream fstream = new FileStream(udlfilename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
long length = fstream.Length;
if (length < hdrlength || (0 != length%ADP.CharSize)) {
failure = ADP.InvalidUDL();
}
else {
byte[] bytes = new Byte[hdrlength];
int count = fstream.Read(bytes, 0, bytes.Length);
if (count < hdrlength) {
failure = ADP.InvalidUDL();
}
else if (System.Text.Encoding.Unicode.GetString(bytes, 0, hdrlength) != UDL.Header) {
failure = ADP.InvalidUDL();
}
else { // please verify header before allocating memory block for connection string
bytes = new Byte[length - hdrlength];
count = fstream.Read(bytes, 0, bytes.Length);
connectionString = System.Text.Encoding.Unicode.GetString(bytes, 0, count);
}
}
}
}
catch(Exception e) {
//
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
throw ADP.UdlFileError(e);
}
if (null != failure) {
throw failure;
}
return connectionString.Trim();
}
[ResourceExposure(ResourceScope.None)] // reads OleDbServices value for the provider
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private string ValidateConnectionString(string connectionString) {
if (ConvertValueToBoolean(KEY.Asynchronous_Processing, false)) {
throw ODB.AsynchronousNotSupported();
}
int connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, 0);
if (connectTimeout < 0) {
throw ADP.InvalidConnectTimeoutValue();
}
string progid = ConvertValueToString(KEY.Data_Provider, null); // MDAC 71923
if (null != progid) {
progid = progid.Trim();
if (0 < progid.Length) { // don't fail on empty 'Data Provider' value
ValidateProvider(progid);
}
}
progid = ConvertValueToString(KEY.RemoteProvider, null); // MDAC 71923
if (null != progid) {
progid = progid.Trim();
if (0 < progid.Length) { // don't fail on empty 'Data Provider' value
ValidateProvider(progid);
}
}
progid = ConvertValueToString(KEY.Provider, ADP.StrEmpty).Trim();
ValidateProvider(progid); // will fail on empty 'Provider' value
// SQLBU VSTS 59322: initialize to default
// If the value is not provided in connection string and OleDbServices registry key has not been set by the provider,
// the default for the provider is -1 (all services are ON).
// our default is -13, we turn off ODB.DBPROPVAL_OS_AGR_AFTERSESSION and ODB.DBPROPVAL_OS_CLIENTCURSOR flags
_oledbServices = DbConnectionStringDefaults.OleDbServices;
bool hasOleDBServices = (base.ContainsKey(KEY.Ole_DB_Services) && !ADP.IsEmpty((string)base[KEY.Ole_DB_Services]));
if (!hasOleDBServices) { // don't touch registry if they have OLE DB Services
string classid = (string) ADP.ClassesRootRegistryValue(progid + "\\CLSID", String.Empty);
if ((null != classid) && (0 < classid.Length)) {
// CLSID detection of 'Microsoft OLE DB Provider for ODBC Drivers'
Guid classidProvider = new Guid(classid);
if (ODB.CLSID_MSDASQL == classidProvider) {
throw ODB.MSDASQLNotSupported();
}
object tmp = ADP.ClassesRootRegistryValue("CLSID\\{" + classidProvider.ToString("D", CultureInfo.InvariantCulture) + "}", ODB.OLEDB_SERVICES);
if (null != tmp) {
// @devnote: some providers like MSDataShape don't have the OLEDB_SERVICES value
// the MSDataShape provider doesn't support the 'Ole Db Services' keyword
// hence, if the value doesn't exist - don't prepend to string
try {
_oledbServices = (int)tmp;
}
catch(InvalidCastException e) {
ADP.TraceExceptionWithoutRethrow(e);
}
_oledbServices &= ~(ODB.DBPROPVAL_OS_AGR_AFTERSESSION | ODB.DBPROPVAL_OS_CLIENTCURSOR); // NT 347436, MDAC 58606
StringBuilder builder = new StringBuilder();
builder.Append(KEY.Ole_DB_Services);
builder.Append("=");
builder.Append(_oledbServices.ToString(CultureInfo.InvariantCulture));
builder.Append(";");
builder.Append(connectionString);
connectionString = builder.ToString();
}
}
}
else {
// SQLBU VSTS 59322: parse the Ole Db Services value from connection string
_oledbServices = ConvertValueToInt32(KEY.Ole_DB_Services, DbConnectionStringDefaults.OleDbServices);
}
return connectionString;
}
internal static bool IsMSDASQL(string progid) {
return (("msdasql" == progid) || progid.StartsWith("msdasql.", StringComparison.Ordinal) || ("microsoft ole db provider for odbc drivers" == progid));
}
static private void ValidateProvider(string progid) {
if (ADP.IsEmpty(progid)) {
throw ODB.NoProviderSpecified();
}
if (ODB.MaxProgIdLength <= progid.Length) { // MDAC 63151
throw ODB.InvalidProviderSpecified();
}
progid = progid.ToLower(CultureInfo.InvariantCulture);
if (IsMSDASQL(progid)) {
// fail msdasql even if not on the machine.
throw ODB.MSDASQLNotSupported();
}
}
static internal void ReleaseObjectPool() {
UDL._PoolSizeInit = false;
UDL._Pool = null;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Cookie.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 Org.Apache.Http.Cookie
{
/// <summary>
/// <para>This cookie comparator ensures that multiple cookies satisfying a common criteria are ordered in the <code>Cookie</code> header such that those with more specific Path attributes precede those with less specific.</para><para>This comparator assumes that Path attributes of two cookies path-match a commmon request-URI. Otherwise, the result of the comparison is undefined. </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookiePathComparator
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookiePathComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" +
"okie/Cookie;>;")]
public partial class CookiePathComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie>
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookiePathComparator() /* MethodBuilder.Create */
{
}
/// <java-name>
/// compare
/// </java-name>
[Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)]
public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */
{
return default(int);
}
[Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)]
public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
}
/// <summary>
/// <para>Defines the cookie management specification. </para><para>Cookie management specification must define <ul><li><para>rules of parsing "Set-Cookie" header </para></li><li><para>rules of validation of parsed cookies </para></li><li><para>formatting of "Cookie" header </para></li></ul>for a given host, port and path of origin</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpec
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpec", AccessFlags = 1537)]
public partial interface ICookieSpec
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns version of the state management this cookie specification conforms to.</para><para></para>
/// </summary>
/// <returns>
/// <para>version of the state management specification </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Parse the <code>"Set-Cookie"</code> Header into an array of Cookies.</para><para>This method will not perform the validation of the resultant Cookies</para><para><para>validate</para></para>
/// </summary>
/// <returns>
/// <para>an array of <code>Cookie</code>s parsed from the header </para>
/// </returns>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List<Lo" +
"rg/apache/http/cookie/Cookie;>;")]
global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> Parse(global::Org.Apache.Http.IHeader header, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Validate the cookie according to validation rules defined by the cookie specification.</para><para></para>
/// </summary>
/// <java-name>
/// validate
/// </java-name>
[Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)]
void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Determines if a Cookie matches the target location.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the cookie should be submitted with a request with given attributes, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// match
/// </java-name>
[Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)]
bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Create <code>"Cookie"</code> headers for an array of Cookies.</para><para></para>
/// </summary>
/// <returns>
/// <para>a Header for the given Cookies. </para>
/// </returns>
/// <java-name>
/// formatCookies
/// </java-name>
[Dot42.DexImport("formatCookies", "(Ljava/util/List;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;)Ljava/util/List<Lorg/apache/ht" +
"tp/Header;>;")]
global::Java.Util.IList<global::Org.Apache.Http.IHeader> FormatCookies(global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> cookies) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a request header identifying what version of the state management specification is understood. May be <code>null</code> if the cookie specification does not support <code>Cookie2</code> header. </para>
/// </summary>
/// <java-name>
/// getVersionHeader
/// </java-name>
[Dot42.DexImport("getVersionHeader", "()Lorg/apache/http/Header;", AccessFlags = 1025)]
global::Org.Apache.Http.IHeader GetVersionHeader() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SM
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class ISMConstants
/* scope: __dot42__ */
{
/// <java-name>
/// COOKIE
/// </java-name>
[Dot42.DexImport("COOKIE", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE = "Cookie";
/// <java-name>
/// COOKIE2
/// </java-name>
[Dot42.DexImport("COOKIE2", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE2 = "Cookie2";
/// <java-name>
/// SET_COOKIE
/// </java-name>
[Dot42.DexImport("SET_COOKIE", "Ljava/lang/String;", AccessFlags = 25)]
public const string SET_COOKIE = "Set-Cookie";
/// <java-name>
/// SET_COOKIE2
/// </java-name>
[Dot42.DexImport("SET_COOKIE2", "Ljava/lang/String;", AccessFlags = 25)]
public const string SET_COOKIE2 = "Set-Cookie2";
}
/// <summary>
/// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SM
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537)]
public partial interface ISM
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>This interface represents a <code>SetCookie2</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SetCookie2
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SetCookie2", AccessFlags = 1537)]
public partial interface ISetCookie2 : global::Org.Apache.Http.Cookie.ISetCookie
/* scope: __dot42__ */
{
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para>
/// </summary>
/// <java-name>
/// setCommentURL
/// </java-name>
[Dot42.DexImport("setCommentURL", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetCommentURL(string commentURL) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para>
/// </summary>
/// <java-name>
/// setPorts
/// </java-name>
[Dot42.DexImport("setPorts", "([I)V", AccessFlags = 1025)]
void SetPorts(int[] ports) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Set the Discard attribute.</para><para>Note: <code>Discard</code> attribute overrides <code>Max-age</code>.</para><para><para>isPersistent() </para></para>
/// </summary>
/// <java-name>
/// setDiscard
/// </java-name>
[Dot42.DexImport("setDiscard", "(Z)V", AccessFlags = 1025)]
void SetDiscard(bool discard) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/Cookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/Cookie", AccessFlags = 1537)]
public partial interface ICookie
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the name.</para><para></para>
/// </summary>
/// <returns>
/// <para>String name The name </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetName() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the value.</para><para></para>
/// </summary>
/// <returns>
/// <para>String value The current value. </para>
/// </returns>
/// <java-name>
/// getValue
/// </java-name>
[Dot42.DexImport("getValue", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetValue() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the comment describing the purpose of this cookie, or <code>null</code> if no such comment has been defined.</para><para></para>
/// </summary>
/// <returns>
/// <para>comment </para>
/// </returns>
/// <java-name>
/// getComment
/// </java-name>
[Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetComment() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para>
/// </summary>
/// <java-name>
/// getCommentURL
/// </java-name>
[Dot42.DexImport("getCommentURL", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetCommentURL() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the expiration Date of the cookie, or <code>null</code> if none exists. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril. </para><para></para>
/// </summary>
/// <returns>
/// <para>Expiration Date, or <code>null</code>. </para>
/// </returns>
/// <java-name>
/// getExpiryDate
/// </java-name>
[Dot42.DexImport("getExpiryDate", "()Ljava/util/Date;", AccessFlags = 1025)]
global::Java.Util.Date GetExpiryDate() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns <code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise </para>
/// </returns>
/// <java-name>
/// isPersistent
/// </java-name>
[Dot42.DexImport("isPersistent", "()Z", AccessFlags = 1025)]
bool IsPersistent() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns domain attribute of the cookie.</para><para></para>
/// </summary>
/// <returns>
/// <para>the value of the domain attribute </para>
/// </returns>
/// <java-name>
/// getDomain
/// </java-name>
[Dot42.DexImport("getDomain", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetDomain() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the path attribute of the cookie</para><para></para>
/// </summary>
/// <returns>
/// <para>The value of the path attribute. </para>
/// </returns>
/// <java-name>
/// getPath
/// </java-name>
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetPath() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Get the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para>
/// </summary>
/// <java-name>
/// getPorts
/// </java-name>
[Dot42.DexImport("getPorts", "()[I", AccessFlags = 1025)]
int[] GetPorts() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Indicates whether this cookie requires a secure connection.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if this cookie should only be sent over secure connections, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 1025)]
bool IsSecure() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the version of the cookie specification to which this cookie conforms.</para><para></para>
/// </summary>
/// <returns>
/// <para>the version of the cookie. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns true if this cookie has expired. </para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the cookie has expired. </para>
/// </returns>
/// <java-name>
/// isExpired
/// </java-name>
[Dot42.DexImport("isExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)]
bool IsExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>CookieOrigin class incapsulates details of an origin server that are relevant when parsing, validating or matching HTTP cookies.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieOrigin
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieOrigin", AccessFlags = 49)]
public sealed partial class CookieOrigin
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;ILjava/lang/String;Z)V", AccessFlags = 1)]
public CookieOrigin(string host, int port, string path, bool secure) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getHost
/// </java-name>
[Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetHost() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPath
/// </java-name>
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetPath() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPort
/// </java-name>
[Dot42.DexImport("getPort", "()I", AccessFlags = 1)]
public int GetPort() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 1)]
public bool IsSecure() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal CookieOrigin() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getHost
/// </java-name>
public string Host
{
[Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetHost(); }
}
/// <java-name>
/// getPath
/// </java-name>
public string Path
{
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPath(); }
}
/// <java-name>
/// getPort
/// </java-name>
public int Port
{
[Dot42.DexImport("getPort", "()I", AccessFlags = 1)]
get{ return GetPort(); }
}
}
/// <summary>
/// <para>This cookie comparator can be used to compare identity of cookies.</para><para>Cookies are considered identical if their names are equal and their domain attributes match ignoring case. </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieIdentityComparator
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieIdentityComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" +
"okie/Cookie;>;")]
public partial class CookieIdentityComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie>
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookieIdentityComparator() /* MethodBuilder.Create */
{
}
/// <java-name>
/// compare
/// </java-name>
[Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)]
public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */
{
return default(int);
}
[Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)]
public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
}
/// <summary>
/// <para>Signals that a cookie is in some way invalid or illegal in a given context</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/MalformedCookieException
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/MalformedCookieException", AccessFlags = 33)]
public partial class MalformedCookieException : global::Org.Apache.Http.ProtocolException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new MalformedCookieException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public MalformedCookieException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new MalformedCookieException with a specified message string.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public MalformedCookieException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new MalformedCookieException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public MalformedCookieException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Cookie specification registry that can be used to obtain the corresponding cookie specification implementation for a given type of type or version of cookie.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpecRegistry
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpecRegistry", AccessFlags = 49)]
public sealed partial class CookieSpecRegistry
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookieSpecRegistry() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Registers a CookieSpecFactory with the given identifier. If a specification with the given name already exists it will be overridden. This nameis the same one used to retrieve the CookieSpecFactory from getCookieSpec(String).</para><para><para>#getCookieSpec(String) </para></para>
/// </summary>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;)V", AccessFlags = 33)]
public void Register(string name, global::Org.Apache.Http.Cookie.ICookieSpecFactory factory) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Unregisters the CookieSpecFactory with the given ID.</para><para></para>
/// </summary>
/// <java-name>
/// unregister
/// </java-name>
[Dot42.DexImport("unregister", "(Ljava/lang/String;)V", AccessFlags = 33)]
public void Unregister(string id) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the cookie specification with the given ID.</para><para></para>
/// </summary>
/// <returns>
/// <para>cookie specification</para>
/// </returns>
/// <java-name>
/// getCookieSpec
/// </java-name>
[Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/Co" +
"okieSpec;", AccessFlags = 33)]
public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Cookie.ICookieSpec);
}
/// <summary>
/// <para>Gets the cookie specification with the given name.</para><para></para>
/// </summary>
/// <returns>
/// <para>cookie specification</para>
/// </returns>
/// <java-name>
/// getCookieSpec
/// </java-name>
[Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 33)]
public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Cookie.ICookieSpec);
}
/// <summary>
/// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para>
/// </summary>
/// <returns>
/// <para>list of registered cookie spec names </para>
/// </returns>
/// <java-name>
/// getSpecNames
/// </java-name>
[Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
public global::Java.Util.IList<string> GetSpecNames() /* MethodBuilder.Create */
{
return default(global::Java.Util.IList<string>);
}
/// <summary>
/// <para>Populates the internal collection of registered cookie specs with the content of the map passed as a parameter.</para><para></para>
/// </summary>
/// <java-name>
/// setItems
/// </java-name>
[Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;>;)V")]
public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Cookie.ICookieSpecFactory> map) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para>
/// </summary>
/// <returns>
/// <para>list of registered cookie spec names </para>
/// </returns>
/// <java-name>
/// getSpecNames
/// </java-name>
public global::Java.Util.IList<string> SpecNames
{
[Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
get{ return GetSpecNames(); }
}
}
/// <summary>
/// <para>This interface represents a <code>SetCookie</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SetCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SetCookie", AccessFlags = 1537)]
public partial interface ISetCookie : global::Org.Apache.Http.Cookie.ICookie
/* scope: __dot42__ */
{
/// <java-name>
/// setValue
/// </java-name>
[Dot42.DexImport("setValue", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetValue(string value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment.</para><para><para>getComment() </para></para>
/// </summary>
/// <java-name>
/// setComment
/// </java-name>
[Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetComment(string comment) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets expiration date. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril.</para><para><para>Cookie::getExpiryDate </para></para>
/// </summary>
/// <java-name>
/// setExpiryDate
/// </java-name>
[Dot42.DexImport("setExpiryDate", "(Ljava/util/Date;)V", AccessFlags = 1025)]
void SetExpiryDate(global::Java.Util.Date expiryDate) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the domain attribute.</para><para><para>Cookie::getDomain </para></para>
/// </summary>
/// <java-name>
/// setDomain
/// </java-name>
[Dot42.DexImport("setDomain", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetDomain(string domain) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the path attribute.</para><para><para>Cookie::getPath </para></para>
/// </summary>
/// <java-name>
/// setPath
/// </java-name>
[Dot42.DexImport("setPath", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetPath(string path) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the secure attribute of the cookie. </para><para>When <code>true</code> the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value.</para><para><para>isSecure() </para></para>
/// </summary>
/// <java-name>
/// setSecure
/// </java-name>
[Dot42.DexImport("setSecure", "(Z)V", AccessFlags = 1025)]
void SetSecure(bool secure) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the version of the cookie specification to which this cookie conforms.</para><para><para>Cookie::getVersion </para></para>
/// </summary>
/// <java-name>
/// setVersion
/// </java-name>
[Dot42.DexImport("setVersion", "(I)V", AccessFlags = 1025)]
void SetVersion(int version) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/ClientCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IClientCookieConstants
/* scope: __dot42__ */
{
/// <java-name>
/// VERSION_ATTR
/// </java-name>
[Dot42.DexImport("VERSION_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string VERSION_ATTR = "version";
/// <java-name>
/// PATH_ATTR
/// </java-name>
[Dot42.DexImport("PATH_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string PATH_ATTR = "path";
/// <java-name>
/// DOMAIN_ATTR
/// </java-name>
[Dot42.DexImport("DOMAIN_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string DOMAIN_ATTR = "domain";
/// <java-name>
/// MAX_AGE_ATTR
/// </java-name>
[Dot42.DexImport("MAX_AGE_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_AGE_ATTR = "max-age";
/// <java-name>
/// SECURE_ATTR
/// </java-name>
[Dot42.DexImport("SECURE_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string SECURE_ATTR = "secure";
/// <java-name>
/// COMMENT_ATTR
/// </java-name>
[Dot42.DexImport("COMMENT_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string COMMENT_ATTR = "comment";
/// <java-name>
/// EXPIRES_ATTR
/// </java-name>
[Dot42.DexImport("EXPIRES_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string EXPIRES_ATTR = "expires";
/// <java-name>
/// PORT_ATTR
/// </java-name>
[Dot42.DexImport("PORT_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string PORT_ATTR = "port";
/// <java-name>
/// COMMENTURL_ATTR
/// </java-name>
[Dot42.DexImport("COMMENTURL_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string COMMENTURL_ATTR = "commenturl";
/// <java-name>
/// DISCARD_ATTR
/// </java-name>
[Dot42.DexImport("DISCARD_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string DISCARD_ATTR = "discard";
}
/// <summary>
/// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/ClientCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537)]
public partial interface IClientCookie : global::Org.Apache.Http.Cookie.ICookie
/* scope: __dot42__ */
{
/// <java-name>
/// getAttribute
/// </java-name>
[Dot42.DexImport("getAttribute", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
string GetAttribute(string name) /* MethodBuilder.Create */ ;
/// <java-name>
/// containsAttribute
/// </java-name>
[Dot42.DexImport("containsAttribute", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
bool ContainsAttribute(string name) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Ths interface represents a cookie attribute handler responsible for parsing, validating, and matching a specific cookie attribute, such as path, domain, port, etc.</para><para>Different cookie specifications can provide a specific implementation for this class based on their cookie handling rules.</para><para><para> (Samit Jain)</para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieAttributeHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieAttributeHandler", AccessFlags = 1537)]
public partial interface ICookieAttributeHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>Parse the given cookie attribute value and update the corresponding org.apache.http.cookie.Cookie property.</para><para></para>
/// </summary>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Lorg/apache/http/cookie/SetCookie;Ljava/lang/String;)V", AccessFlags = 1025)]
void Parse(global::Org.Apache.Http.Cookie.ISetCookie cookie, string value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Peforms cookie validation for the given attribute value.</para><para></para>
/// </summary>
/// <java-name>
/// validate
/// </java-name>
[Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)]
void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the match is successful; <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// match
/// </java-name>
[Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)]
bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpecFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpecFactory", AccessFlags = 1537)]
public partial interface ICookieSpecFactory
/* scope: __dot42__ */
{
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 1025)]
global::Org.Apache.Http.Cookie.ICookieSpec NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ;
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="InputStreamSinkSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.IO;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.IO;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.IO
{
public class InputStreamSinkSpec : AkkaSpec
{
private static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(300);
private readonly ActorMaterializer _materializer;
private readonly ByteString _byteString = RandomByteString(3);
public InputStreamSinkSpec(ITestOutputHelper helper) : base(Utils.UnboundedMailboxConfig, helper)
{
Sys.Settings.InjectTopLevelFallback(ActorMaterializer.DefaultConfig());
var settings = ActorMaterializerSettings.Create(Sys).WithDispatcher("akka.actor.default-dispatcher");
_materializer = Sys.Materializer(settings);
}
[Fact]
public void InputStreamSink_should_read_bytes_from_input_stream()
{
this.AssertAllStagesStopped(() =>
{
var inputStream = Source.Single(_byteString).RunWith(StreamConverters.AsInputStream(), _materializer);
var result = ReadN(inputStream, _byteString.Count);
inputStream.Close();
result.Item1.Should().Be(_byteString.Count);
result.Item2.Should().BeEquivalentTo(_byteString);
}, _materializer);
}
[Fact]
public void InputStreamSink_should_read_bytes_correctly_if_requested_by_input_stream_not_in_chunk_size()
{
this.AssertAllStagesStopped(() =>
{
var sinkProbe = CreateTestProbe();
var byteString2 = RandomByteString(3);
var inputStream = Source.From(new[] { _byteString, byteString2, null })
.RunWith(TestSink(sinkProbe), _materializer);
sinkProbe.ExpectMsgAllOf(GraphStageMessages.Push.Instance, GraphStageMessages.Push.Instance);
var result = ReadN(inputStream, 2);
result.Item1.Should().Be(2);
result.Item2.Should().BeEquivalentTo(_byteString.Take(2));
result = ReadN(inputStream, 2);
result.Item1.Should().Be(2);
result.Item2.Should().BeEquivalentTo(_byteString.Drop(2).Concat(byteString2.Take(1)));
result = ReadN(inputStream, 2);
result.Item1.Should().Be(2);
result.Item2.Should().BeEquivalentTo(byteString2.Drop(1));
inputStream.Close();
}, _materializer);
}
[Fact]
public void InputStreamSink_should_return_less_than_was_expected_when_data_source_has_provided_some_but_not_enough_data()
{
this.AssertAllStagesStopped(() =>
{
var inputStream = Source.Single(_byteString).RunWith(StreamConverters.AsInputStream(), _materializer);
var arr = new byte[_byteString.Count + 1];
inputStream.Read(arr, 0, arr.Length).Should().Be(arr.Length - 1);
inputStream.Close();
ByteString.Create(arr).ShouldBeEquivalentTo(_byteString.Concat(ByteString.Create(new byte[] { 0 })));
}, _materializer);
}
[Fact]
public void InputStreamSink_should_block_read_until_get_requested_number_of_bytes_from_upstream()
{
this.AssertAllStagesStopped(() =>
{
var run =
this.SourceProbe<ByteString>()
.ToMaterialized(StreamConverters.AsInputStream(), Keep.Both)
.Run(_materializer);
var probe = run.Item1;
var inputStream = run.Item2;
var f = Task.Run(() => inputStream.Read(new byte[_byteString.Count], 0, _byteString.Count));
f.Wait(Timeout).Should().BeFalse();
probe.SendNext(_byteString);
f.Wait(Timeout).Should().BeTrue();
f.Result.Should().Be(_byteString.Count);
probe.SendComplete();
inputStream.ReadByte().Should().Be(-1);
inputStream.Close();
}, _materializer);
}
[Fact]
public void InputStreamSink_should_throw_error_when_reactive_stream_is_closed()
{
this.AssertAllStagesStopped(() =>
{
var t = this.SourceProbe<ByteString>()
.ToMaterialized(StreamConverters.AsInputStream(), Keep.Both)
.Run(_materializer);
var probe = t.Item1;
var inputStream = t.Item2;
probe.SendNext(_byteString);
inputStream.Close();
probe.ExpectCancellation();
Action block = () => inputStream.Read(new byte[1], 0, 1);
block.ShouldThrow<IOException>();
}, _materializer);
}
[Fact]
public void InputStreamSink_should_return_all_data_when_upstream_is_completed()
{
this.AssertAllStagesStopped(() =>
{
var sinkProbe = CreateTestProbe();
var t = this.SourceProbe<ByteString>().ToMaterialized(TestSink(sinkProbe), Keep.Both).Run(_materializer);
var probe = t.Item1;
var inputStream = t.Item2;
var bytes = RandomByteString(1);
probe.SendNext(bytes);
sinkProbe.ExpectMsg<GraphStageMessages.Push>();
probe.SendComplete();
sinkProbe.ExpectMsg<GraphStageMessages.UpstreamFinish>();
var result = ReadN(inputStream, 3);
result.Item1.Should().Be(1);
result.Item2.Should().BeEquivalentTo(bytes);
}, _materializer);
}
[Fact]
public void InputStreamSink_should_work_when_read_chunks_smaller_then_stream_chunks()
{
this.AssertAllStagesStopped(() =>
{
var bytes = RandomByteString(10);
var inputStream = Source.Single(bytes).RunWith(StreamConverters.AsInputStream(), _materializer);
while (bytes.NonEmpty)
{
var expected = bytes.Take(3);
bytes = bytes.Drop(3);
var result = ReadN(inputStream, 3);
result.Item1.Should().Be(expected.Count);
result.Item2.ShouldBeEquivalentTo(expected);
}
inputStream.Close();
}, _materializer);
}
[Fact]
public void InputStreamSink_should_throw_exception_when_call_read_With_wrong_parameters()
{
this.AssertAllStagesStopped(() =>
{
var inputStream = Source.Single(_byteString).RunWith(StreamConverters.AsInputStream(), _materializer);
var buf = new byte[3];
Action(() => inputStream.Read(buf, -1, 2)).ShouldThrow<ArgumentException>();
Action(() => inputStream.Read(buf, 0, 5)).ShouldThrow<ArgumentException>();
Action(() => inputStream.Read(new byte[0], 0, 1)).ShouldThrow<ArgumentException>();
Action(() => inputStream.Read(buf, 0, 0)).ShouldThrow<ArgumentException>();
}, _materializer);
}
private Action Action(Action a) => a;
[Fact]
public void InputStreamSink_should_successfully_read_several_chunks_at_once()
{
this.AssertAllStagesStopped(() =>
{
var bytes = Enumerable.Range(1, 4).Select(_ => RandomByteString(4)).ToList();
var sinkProbe = CreateTestProbe();
var inputStream = Source.From(bytes).RunWith(TestSink(sinkProbe), _materializer);
//need to wait while all elements arrive to sink
bytes.ForEach(_ => sinkProbe.ExpectMsg<GraphStageMessages.Push>());
for (var i = 0; i < 2; i++)
{
var r = ReadN(inputStream, 8);
r.Item1.Should().Be(8);
r.Item2.ShouldBeEquivalentTo(bytes[i * 2].Concat(bytes[i * 2 + 1]));
}
inputStream.Close();
}, _materializer);
}
[Fact]
public void InputStreamSink_should_work_when_read_chunks_bigger_than_stream_chunks()
{
this.AssertAllStagesStopped(() =>
{
var bytes1 = RandomByteString(10);
var bytes2 = RandomByteString(10);
var sinkProbe = CreateTestProbe();
var inputStream = Source.From(new[] { bytes1, bytes2, null }).RunWith(TestSink(sinkProbe), _materializer);
//need to wait while both elements arrive to sink
sinkProbe.ExpectMsgAllOf(GraphStageMessages.Push.Instance, GraphStageMessages.Push.Instance);
var r1 = ReadN(inputStream, 15);
r1.Item1.Should().Be(15);
r1.Item2.ShouldBeEquivalentTo(bytes1.Concat(bytes2.Take(5)));
var r2 = ReadN(inputStream, 15);
r2.Item1.Should().Be(5);
r2.Item2.ShouldBeEquivalentTo(bytes2.Drop(5));
inputStream.Close();
}, _materializer);
}
[Fact]
public void InputStreamSink_should_return_minus_1_when_read_after_stream_is_completed()
{
this.AssertAllStagesStopped(() =>
{
var inputStream = Source.Single(_byteString).RunWith(StreamConverters.AsInputStream(), _materializer);
var r = ReadN(inputStream, _byteString.Count);
r.Item1.Should().Be(_byteString.Count);
r.Item2.ShouldBeEquivalentTo(_byteString);
inputStream.ReadByte().Should().Be(-1);
inputStream.Close();
}, _materializer);
}
[Fact]
public void InputStreamSink_should_return_Exception_when_stream_is_failed()
{
this.AssertAllStagesStopped(() =>
{
var sinkProbe = CreateTestProbe();
var t = this.SourceProbe<ByteString>().ToMaterialized(TestSink(sinkProbe), Keep.Both).Run(_materializer);
var probe = t.Item1;
var inputStream = t.Item2;
var ex = new SystemException("Stream failed.");
probe.SendNext(_byteString);
sinkProbe.ExpectMsg<GraphStageMessages.Push>();
var r = ReadN(inputStream, _byteString.Count);
r.Item1.Should().Be(_byteString.Count);
r.Item2.ShouldBeEquivalentTo(_byteString);
probe.SendError(ex);
sinkProbe.ExpectMsg<GraphStageMessages.Failure>().Ex.Should().Be(ex);
var task = Task.Run(() => inputStream.ReadByte());
Action block = () => task.Wait(Timeout);
block.ShouldThrow<Exception>();
task.Exception.InnerException.Should().Be(ex);
}, _materializer);
}
[Fact]
public void InputStreamSink_should_use_dedicated_default_blocking_io_dispatcher_by_default()
{
this.AssertAllStagesStopped(() =>
{
var sys = ActorSystem.Create("dispatcher-testing", Utils.UnboundedMailboxConfig);
var materializer = ActorMaterializer.Create(sys);
try
{
this.SourceProbe<ByteString>().RunWith(StreamConverters.AsInputStream(), materializer);
(materializer as ActorMaterializerImpl).Supervisor.Tell(StreamSupervisor.GetChildren.Instance, TestActor);
var children = ExpectMsg<StreamSupervisor.Children>().Refs;
var actorRef = children.First(c => c.Path.ToString().Contains("inputStreamSink"));
Utils.AssertDispatcher(actorRef, "akka.stream.default-blocking-io-dispatcher");
}
finally
{
Shutdown(sys);
}
}, _materializer);
}
[Fact]
public void InputStreamSink_should_work_when_more_bytes_pulled_from_input_stream_than_available()
{
this.AssertAllStagesStopped(() =>
{
var inputStream = Source.Single(_byteString).RunWith(StreamConverters.AsInputStream(), _materializer);
var r = ReadN(inputStream, _byteString.Count * 2);
r.Item1.Should().Be(_byteString.Count);
r.Item2.ShouldBeEquivalentTo(_byteString);
inputStream.Close();
}, _materializer);
}
[Fact]
public void InputStreamSink_should_fail_to_materialize_with_zero_sized_input_buffer()
{
Action a = () => Source.Single(_byteString).RunWith(StreamConverters.AsInputStream(Timeout).WithAttributes(Attributes.CreateInputBuffer(0, 0)), _materializer);
a.ShouldThrow<ArgumentException>();
/*
With Source.single we test the code path in which the sink
itself throws an exception when being materialized. If
Source.empty is used, the same exception is thrown by
Materializer.
*/
}
private static ByteString RandomByteString(int size)
{
var a = new byte[size];
new Random().NextBytes(a);
return ByteString.Create(a);
}
private Tuple<int, ByteString> ReadN(Stream s, int n)
{
var buf = new byte[n];
var r = s.Read(buf, 0, n);
return new Tuple<int, ByteString>(r, ByteString.Create(buf, 0, r));
}
private TestSinkStage<ByteString, Stream> TestSink(TestProbe probe)
=> TestSinkStage<ByteString, Stream>.Create(new InputStreamSinkStage(Timeout), probe);
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Sax.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 Android.Sax
{
/// <summary>
/// <para>Listens for the end of elements. </para>
/// </summary>
/// <java-name>
/// android/sax/EndElementListener
/// </java-name>
[Dot42.DexImport("android/sax/EndElementListener", AccessFlags = 1537)]
public partial interface IEndElementListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Invoked at the end of an element. </para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "()V", AccessFlags = 1025)]
void End() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>An XML element. Provides access to child elements and hooks to listen for events related to this element.</para><para><para>RootElement </para></para>
/// </summary>
/// <java-name>
/// android/sax/Element
/// </java-name>
[Dot42.DexImport("android/sax/Element", AccessFlags = 33)]
public partial class Element
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal Element() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the child element with the given name. Uses an empty string as the namespace. </para>
/// </summary>
/// <java-name>
/// getChild
/// </java-name>
[Dot42.DexImport("getChild", "(Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element GetChild(string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Gets the child element with the given name. </para>
/// </summary>
/// <java-name>
/// getChild
/// </java-name>
[Dot42.DexImport("getChild", "(Ljava/lang/String;Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element GetChild(string uri, string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Gets the child element with the given name. Uses an empty string as the namespace. We will throw a org.xml.sax.SAXException at parsing time if the specified child is missing. This helps you ensure that your listeners are called. </para>
/// </summary>
/// <java-name>
/// requireChild
/// </java-name>
[Dot42.DexImport("requireChild", "(Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element RequireChild(string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Gets the child element with the given name. We will throw a org.xml.sax.SAXException at parsing time if the specified child is missing. This helps you ensure that your listeners are called. </para>
/// </summary>
/// <java-name>
/// requireChild
/// </java-name>
[Dot42.DexImport("requireChild", "(Ljava/lang/String;Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element RequireChild(string uri, string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Sets start and end element listeners at the same time. </para>
/// </summary>
/// <java-name>
/// setElementListener
/// </java-name>
[Dot42.DexImport("setElementListener", "(Landroid/sax/ElementListener;)V", AccessFlags = 1)]
public virtual void SetElementListener(global::Android.Sax.IElementListener elementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets start and end text element listeners at the same time. </para>
/// </summary>
/// <java-name>
/// setTextElementListener
/// </java-name>
[Dot42.DexImport("setTextElementListener", "(Landroid/sax/TextElementListener;)V", AccessFlags = 1)]
public virtual void SetTextElementListener(global::Android.Sax.ITextElementListener elementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets a listener for the start of this element. </para>
/// </summary>
/// <java-name>
/// setStartElementListener
/// </java-name>
[Dot42.DexImport("setStartElementListener", "(Landroid/sax/StartElementListener;)V", AccessFlags = 1)]
public virtual void SetStartElementListener(global::Android.Sax.IStartElementListener startElementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets a listener for the end of this element. </para>
/// </summary>
/// <java-name>
/// setEndElementListener
/// </java-name>
[Dot42.DexImport("setEndElementListener", "(Landroid/sax/EndElementListener;)V", AccessFlags = 1)]
public virtual void SetEndElementListener(global::Android.Sax.IEndElementListener endElementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets a listener for the end of this text element. </para>
/// </summary>
/// <java-name>
/// setEndTextElementListener
/// </java-name>
[Dot42.DexImport("setEndTextElementListener", "(Landroid/sax/EndTextElementListener;)V", AccessFlags = 1)]
public virtual void SetEndTextElementListener(global::Android.Sax.IEndTextElementListener endTextElementListener) /* MethodBuilder.Create */
{
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
}
/// <summary>
/// <para>Listens for the beginning and ending of elements. </para>
/// </summary>
/// <java-name>
/// android/sax/ElementListener
/// </java-name>
[Dot42.DexImport("android/sax/ElementListener", AccessFlags = 1537)]
public partial interface IElementListener : global::Android.Sax.IStartElementListener, global::Android.Sax.IEndElementListener
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>Listens for the end of text elements. </para>
/// </summary>
/// <java-name>
/// android/sax/EndTextElementListener
/// </java-name>
[Dot42.DexImport("android/sax/EndTextElementListener", AccessFlags = 1537)]
public partial interface IEndTextElementListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Invoked at the end of a text element with the body of the element.</para><para></para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void End(string body) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Listens for the beginning and ending of text elements. </para>
/// </summary>
/// <java-name>
/// android/sax/TextElementListener
/// </java-name>
[Dot42.DexImport("android/sax/TextElementListener", AccessFlags = 1537)]
public partial interface ITextElementListener : global::Android.Sax.IStartElementListener, global::Android.Sax.IEndTextElementListener
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>Listens for the beginning of elements. </para>
/// </summary>
/// <java-name>
/// android/sax/StartElementListener
/// </java-name>
[Dot42.DexImport("android/sax/StartElementListener", AccessFlags = 1537)]
public partial interface IStartElementListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Invoked at the beginning of an element.</para><para></para>
/// </summary>
/// <java-name>
/// start
/// </java-name>
[Dot42.DexImport("start", "(Lorg/xml/sax/Attributes;)V", AccessFlags = 1025)]
void Start(global::Org.Xml.Sax.IAttributes attributes) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The root XML element. The entry point for this API. Not safe for concurrent use.</para><para>For example, passing this XML:</para><para><pre>
/// <feed xmlns='>
/// <entry>
/// <id>bob</id>
/// </entry>
/// </feed>
/// </pre></para><para>to this code:</para><para><pre>
/// static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
///
/// ...
///
/// RootElement root = new RootElement(ATOM_NAMESPACE, "feed");
/// Element entry = root.getChild(ATOM_NAMESPACE, "entry");
/// entry.getChild(ATOM_NAMESPACE, "id").setEndTextElementListener(
/// new EndTextElementListener() {
/// public void end(String body) {
/// System.out.println("Entry ID: " + body);
/// }
/// });
///
/// XMLReader reader = ...;
/// reader.setContentHandler(root.getContentHandler());
/// reader.parse(...);
/// </pre></para><para>would output:</para><para><pre>
/// Entry ID: bob
/// </pre> </para>
/// </summary>
/// <java-name>
/// android/sax/RootElement
/// </java-name>
[Dot42.DexImport("android/sax/RootElement", AccessFlags = 33)]
public partial class RootElement : global::Android.Sax.Element
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new root element with the given name.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public RootElement(string uri, string localName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a new root element with the given name. Uses an empty string as the namespace.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public RootElement(string localName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the SAX <c> ContentHandler </c> . Pass this to your SAX parser. </para>
/// </summary>
/// <java-name>
/// getContentHandler
/// </java-name>
[Dot42.DexImport("getContentHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)]
public virtual global::Org.Xml.Sax.IContentHandler GetContentHandler() /* MethodBuilder.Create */
{
return default(global::Org.Xml.Sax.IContentHandler);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal RootElement() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Gets the SAX <c> ContentHandler </c> . Pass this to your SAX parser. </para>
/// </summary>
/// <java-name>
/// getContentHandler
/// </java-name>
public global::Org.Xml.Sax.IContentHandler ContentHandler
{
[Dot42.DexImport("getContentHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)]
get{ return GetContentHandler(); }
}
}
}
| |
// 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 TestCInt16()
{
var test = new BooleanBinaryOpTest__TestCInt16();
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();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// 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 class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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 BooleanBinaryOpTest__TestCInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestCInt16 testClass)
{
var result = Avx.TestC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestCInt16 testClass)
{
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx.TestC(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestCInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public BooleanBinaryOpTest__TestCInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestC(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestC(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestC(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int16>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestC(
Avx.LoadVector256((Int16*)(pClsVar1)),
Avx.LoadVector256((Int16*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestCInt16();
var result = Avx.TestC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestCInt16();
fixed (Vector256<Int16>* pFld1 = &test._fld1)
fixed (Vector256<Int16>* pFld2 = &test._fld2)
{
var result = Avx.TestC(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx.TestC(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestC(
Avx.LoadVector256((Int16*)(&test._fld1)),
Avx.LoadVector256((Int16*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((~left[i] & right[i]) == 0);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestC)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.ComponentModel.LicenseManagerTests test cases
//
// Authors:
// Ivan Hamilton ([email protected])
// Gonzalo Paniagua Javier ([email protected])
// Martin Willemoes Hansen ([email protected])
//
// (c) 2002 Ximian, Inc. (http://www.ximian.com)
// (c) 2003 Martin Willemoes Hansen
// (c) 2004 Ivan Hamilton
using Xunit;
using System.ComponentModel.Design;
namespace System.ComponentModel.Tests
{
public class UnlicensedObject
{
}
[LicenseProvider(typeof(TestLicenseProvider))]
public class LicensedObject
{
}
[LicenseProvider(typeof(TestLicenseProvider))]
public class InvalidLicensedObject
{
}
[LicenseProvider(typeof(TestLicenseProvider))]
public class RuntimeLicensedObject
{
public RuntimeLicensedObject()
{
LicenseManager.Validate(typeof(RuntimeLicensedObject));
}
public RuntimeLicensedObject(int a) : this() { }
}
[LicenseProvider(typeof(TestLicenseProvider))]
public class DesigntimeLicensedObject
{
public DesigntimeLicensedObject()
{
LicenseManager.Validate(typeof(DesigntimeLicensedObject));
}
}
public class TestLicenseProvider : LicenseProvider
{
private class TestLicense : License
{
public override void Dispose()
{
}
public override string LicenseKey => "YourLicenseKey";
}
public TestLicenseProvider() : base()
{
}
public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
{
if (type.Name.Equals("RuntimeLicensedObject"))
{
if (context.UsageMode != LicenseUsageMode.Runtime)
if (allowExceptions)
throw new LicenseException(type, instance, "License fails because this is a Runtime only license");
else
return null;
return new TestLicense();
}
if (type.Name.Equals("DesigntimeLicensedObject"))
{
if (context.UsageMode != LicenseUsageMode.Designtime)
if (allowExceptions)
throw new LicenseException(type, instance, "License fails because this is a Designtime only license");
else
return null;
return new TestLicense();
}
if (type.Name.Equals("LicensedObject"))
return new TestLicense();
if (allowExceptions)
throw new LicenseException(type, instance, "License fails because of class name.");
else
return null;
}
}
public class LicenseManagerTests
{
[Fact]
public void Test()
{
object lockObject = new object();
//**DEFAULT CONTEXT & LicenseUsageMode**
//Get CurrentContext, check default type
Assert.False(LicenseManager.CurrentContext is DesigntimeLicenseContext);
//Read default LicenseUsageMode, check against CurrentContext (LicCont).UsageMode
Assert.Equal(LicenseManager.CurrentContext.UsageMode, LicenseManager.UsageMode);
//**CHANGING CONTEXT**
//Change the context and check it changes
LicenseContext oldcontext = LicenseManager.CurrentContext;
LicenseContext newcontext = new DesigntimeLicenseContext();
LicenseManager.CurrentContext = newcontext;
Assert.Equal(newcontext, LicenseManager.CurrentContext);
//Check the UsageMode changed too
Assert.Equal(newcontext.UsageMode, LicenseManager.UsageMode);
//Set Context back to original
LicenseManager.CurrentContext = oldcontext;
//Check it went back
Assert.Equal(oldcontext, LicenseManager.CurrentContext);
//Check the UsageMode changed too
Assert.Equal(oldcontext.UsageMode, LicenseManager.UsageMode);
//**CONTEXT LOCKING**
//Lock the context
LicenseManager.LockContext(lockObject);
//Try and set new context again, should throw System.InvalidOperationException: The CurrentContext property of the LicenseManager is currently locked and cannot be changed.
bool exceptionThrown = false;
try
{
LicenseManager.CurrentContext = newcontext;
}
catch (Exception e)
{
Assert.Equal(typeof(InvalidOperationException), e.GetType());
exceptionThrown = true;
}
//Check the exception was thrown
Assert.Equal(true, exceptionThrown);
//Check the context didn't change
Assert.Equal(oldcontext, LicenseManager.CurrentContext);
//Unlock it
LicenseManager.UnlockContext(lockObject);
//Now's unlocked, change it
LicenseManager.CurrentContext = newcontext;
Assert.Equal(newcontext, LicenseManager.CurrentContext);
//Change it back
LicenseManager.CurrentContext = oldcontext;
//Lock the context
LicenseManager.LockContext(lockObject);
//Unlock with different "user" should throw System.ArgumentException: The CurrentContext property of the LicenseManager can only be unlocked with the same contextUser.
object wrongLockObject = new object();
exceptionThrown = false;
try
{
LicenseManager.UnlockContext(wrongLockObject);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
exceptionThrown = true;
}
Assert.Equal(true, exceptionThrown);
//Unlock it
LicenseManager.UnlockContext(lockObject);
//** bool IsValid(Type);
Assert.Equal(true, LicenseManager.IsLicensed(typeof(UnlicensedObject)));
Assert.Equal(true, LicenseManager.IsLicensed(typeof(LicensedObject)));
Assert.Equal(false, LicenseManager.IsLicensed(typeof(InvalidLicensedObject)));
Assert.Equal(true, LicenseManager.IsValid(typeof(UnlicensedObject)));
Assert.Equal(true, LicenseManager.IsValid(typeof(LicensedObject)));
Assert.Equal(false, LicenseManager.IsValid(typeof(InvalidLicensedObject)));
UnlicensedObject unlicensedObject = new UnlicensedObject();
LicensedObject licensedObject = new LicensedObject();
InvalidLicensedObject invalidLicensedObject = new InvalidLicensedObject();
//** bool IsValid(Type, object, License);
License license = null;
Assert.Equal(true, LicenseManager.IsValid(unlicensedObject.GetType(), unlicensedObject, out license));
Assert.Equal(null, license);
license = null;
Assert.Equal(true, LicenseManager.IsValid(licensedObject.GetType(), licensedObject, out license));
Assert.Equal("TestLicense", license.GetType().Name);
license = null;
Assert.Equal(false, LicenseManager.IsValid(invalidLicensedObject.GetType(), invalidLicensedObject, out license));
Assert.Equal(null, license);
//** void Validate(Type);
//Shouldn't throw exception
LicenseManager.Validate(typeof(UnlicensedObject));
//Shouldn't throw exception
LicenseManager.Validate(typeof(LicensedObject));
//Should throw exception
exceptionThrown = false;
try
{
LicenseManager.Validate(typeof(InvalidLicensedObject));
}
catch (Exception e)
{
Assert.Equal(typeof(LicenseException), e.GetType());
exceptionThrown = true;
}
//Check the exception was thrown
Assert.Equal(true, exceptionThrown);
//** License Validate(Type, object);
//Shouldn't throw exception, returns null license
license = LicenseManager.Validate(typeof(UnlicensedObject), unlicensedObject);
Assert.Equal(null, license);
//Shouldn't throw exception, returns TestLicense license
license = LicenseManager.Validate(typeof(LicensedObject), licensedObject);
Assert.Equal("TestLicense", license.GetType().Name);
//Should throw exception, returns null license
exceptionThrown = false;
try
{
license = null;
license = LicenseManager.Validate(typeof(InvalidLicensedObject), invalidLicensedObject);
}
catch (Exception e)
{
Assert.Equal(typeof(LicenseException), e.GetType());
exceptionThrown = true;
}
//Check the exception was thrown
Assert.Equal(true, exceptionThrown);
Assert.Equal(null, license);
//** object CreateWithContext (Type, LicenseContext);
object cwc = null;
//Test we can create an unlicensed object with no context
cwc = LicenseManager.CreateWithContext(typeof(UnlicensedObject), null);
Assert.Equal("UnlicensedObject", cwc.GetType().Name);
//Test we can create RunTime with CurrentContext (runtime)
cwc = null;
cwc = LicenseManager.CreateWithContext(typeof(RuntimeLicensedObject),
LicenseManager.CurrentContext);
Assert.Equal("RuntimeLicensedObject", cwc.GetType().Name);
//Test we can't create DesignTime with CurrentContext (runtime)
exceptionThrown = false;
try
{
cwc = null;
cwc = LicenseManager.CreateWithContext(typeof(DesigntimeLicensedObject), LicenseManager.CurrentContext);
}
catch (Exception e)
{
Assert.Equal(typeof(LicenseException), e.GetType());
exceptionThrown = true;
}
//Check the exception was thrown
Assert.Equal(true, exceptionThrown);
//Test we can create DesignTime with A new DesignTimeContext
cwc = null;
cwc = LicenseManager.CreateWithContext(typeof(DesigntimeLicensedObject),
new DesigntimeLicenseContext());
Assert.Equal("DesigntimeLicensedObject", cwc.GetType().Name);
//** object CreateWithContext(Type, LicenseContext, object[]);
//Test we can create RunTime with CurrentContext (runtime)
cwc = null;
cwc = LicenseManager.CreateWithContext(typeof(RuntimeLicensedObject),
LicenseManager.CurrentContext, new object[] { 7 });
Assert.Equal("RuntimeLicensedObject", cwc.GetType().Name);
}
}
}
| |
/***************************************************************************\
*
* File: BamlWriter.cs
*
* Purpose: Public api for writing baml records to a stream
*
* History:
* 10/15/03: peterost Created
*
* Copyright (C) 2002 by Microsoft Corporation. All rights reserved.
*
\***************************************************************************/
using System;
using System.Xml;
using System.IO;
using System.Windows;
using System.Text;
using System.Collections;
using System.ComponentModel;
using MS.Internal.Utility;
using MS.Internal;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Threading;
using MS.Utility;
namespace System.Windows.Markup
{
/// <summary>
/// Writes BAML records to Stream and exposes an XmlWriter-liker interface for BAML
/// </summary>
// <SecurityNote>
// This code should always be transparent. Meaning you should never add
// SecurityCritical to this section of the code.
// </SecurityNote>
internal class BamlWriter : IParserHelper
{
#region Constructor
/// <summary>
/// Create a BamlWriter on the passed stream. The stream must be writable.
/// </summary>
public BamlWriter(
Stream stream)
{
if (null == stream)
{
throw new ArgumentNullException( "stream" );
}
if (!stream.CanWrite)
{
throw new ArgumentException(SR.Get(SRID.BamlWriterBadStream));
}
_parserContext = new ParserContext();
if (null == _parserContext.XamlTypeMapper)
{
_parserContext.XamlTypeMapper = new BamlWriterXamlTypeMapper(XmlParserDefaults.GetDefaultAssemblyNames(),
XmlParserDefaults.GetDefaultNamespaceMaps());
}
_xamlTypeMapper = _parserContext.XamlTypeMapper;
_bamlRecordWriter = new BamlRecordWriter(stream, _parserContext, true);
_startDocumentWritten = false;
_depth = 0;
_closed = false;
_nodeTypeStack = new ParserStack();
_assemblies = new Hashtable(7);
_extensionParser = new MarkupExtensionParser((IParserHelper)this, _parserContext);
_markupExtensionNodes = new ArrayList();
}
#endregion Constructor
#region Close
/// <summary>
/// Close the underlying stream and terminate write operations.
/// </summary>
/// <remarks>
/// Once Close() is called, the BamlWriter cannot be used again and all
/// subsequent calls to BamlWriter will fail.
/// </remarks>
public void Close()
{
_bamlRecordWriter.BamlStream.Close();
_closed = true;
}
#endregion Close
#region IParserHelper
string IParserHelper.LookupNamespace(string prefix)
{
return _parserContext.XmlnsDictionary[prefix];
}
bool IParserHelper.GetElementType(
bool extensionFirst,
string localName,
string namespaceURI,
ref string assemblyName,
ref string typeFullName,
ref Type baseType,
ref Type serializerType)
{
bool result = false;
assemblyName = string.Empty;
typeFullName = string.Empty;
serializerType = null;
baseType = null;
// if no namespaceURI or local name don't bother
if (null == namespaceURI || null == localName)
{
return false;
}
TypeAndSerializer typeAndSerializer =
_xamlTypeMapper.GetTypeAndSerializer(namespaceURI, localName, null);
// If the normal type resolution fails, try the name with "Extension" added
// so that we'll find MarkupExtension subclasses.
if (typeAndSerializer == null)
{
typeAndSerializer = _xamlTypeMapper.GetTypeAndSerializer(namespaceURI, localName + "Extension", null);
}
if (typeAndSerializer != null &&
typeAndSerializer.ObjectType != null)
{
serializerType = typeAndSerializer.SerializerType;
baseType = typeAndSerializer.ObjectType;
typeFullName = baseType.FullName;
assemblyName = baseType.Assembly.FullName;
result = true;
Debug.Assert(null != assemblyName,"assembly name returned from GetBaseElement is null");
Debug.Assert(null != typeFullName,"Type name returned from GetBaseElement is null");
}
return result;
}
bool IParserHelper.CanResolveLocalAssemblies()
{
return false;
}
#endregion IParserHelper
#region Record Writing
/// <summary>
/// Write the start of document record, giving the baml version string
/// </summary>
/// <remarks>
/// This must be the first call made when creating a new baml file. This
/// is needed to specify the start of the document and baml version.
/// </remarks>
public void WriteStartDocument()
{
if (_closed)
{
throw new InvalidOperationException(SR.Get(SRID.BamlWriterClosed));
}
if (_startDocumentWritten)
{
throw new InvalidOperationException(SR.Get(SRID.BamlWriterStartDoc));
}
XamlDocumentStartNode node = new XamlDocumentStartNode(0,0,_depth);
_bamlRecordWriter.WriteDocumentStart(node);
_startDocumentWritten = true;
Push(BamlRecordType.DocumentStart);
}
/// <summary>
/// Write the end of document record.
/// </summary>
/// <remarks>
/// This must be the last call made when creating a new baml file.
/// </remarks>
public void WriteEndDocument()
{
VerifyEndTagState(BamlRecordType.DocumentStart,
BamlRecordType.DocumentEnd);
XamlDocumentEndNode node = new XamlDocumentEndNode(0,0,_depth);
_bamlRecordWriter.WriteDocumentEnd(node);
}
/// <summary>
/// Write the connection Id record.
/// </summary>
/// <remarks>
/// A record that contains the connection Id of the current element
/// for hooking up IDs and events.
/// </remarks>
public void WriteConnectionId(Int32 connectionId)
{
VerifyWriteState();
_bamlRecordWriter.WriteConnectionId(connectionId);
}
/// <summary>
/// Write the start of element record.
/// </summary>
/// <remarks>
/// An element start marks the beginning of an object that exists
/// in a tree structure. This may the contents of a complex property,
/// or an element in the logical tree.
/// </remarks>
public void WriteStartElement(
string assemblyName,
string typeFullName,
bool isInjected,
bool useTypeConverter)
{
VerifyWriteState();
_dpProperty = null;
_parserContext.PushScope();
ProcessMarkupExtensionNodes();
Type elementType = GetType(assemblyName, typeFullName);
Type serializerType = _xamlTypeMapper.GetXamlSerializerForType(elementType);
Push(BamlRecordType.ElementStart, elementType);
XamlElementStartNode node = new XamlElementStartNode(
0,
0,
_depth++,
assemblyName,
typeFullName,
elementType,
serializerType);
node.IsInjected = isInjected;
node.CreateUsingTypeConverter = useTypeConverter;
_bamlRecordWriter.WriteElementStart(node);
}
/// <summary>
/// Write the end of element record.
/// </summary>
/// <remarks>
/// An element end marks the ending of an object that exists
/// in a tree structure. This may the contents of a complex property,
/// or an element in the logical tree.
/// </remarks>
public void WriteEndElement()
{
VerifyEndTagState(BamlRecordType.ElementStart,
BamlRecordType.ElementEnd);
ProcessMarkupExtensionNodes();
XamlElementEndNode node = new XamlElementEndNode(
0,
0,
--_depth);
_bamlRecordWriter.WriteElementEnd(node);
_parserContext.PopScope();
}
/// <summary>
/// Write the start of constructor section that follows the start of an element.
/// </summary>
public void WriteStartConstructor()
{
VerifyWriteState();
Push(BamlRecordType.ConstructorParametersStart);
XamlConstructorParametersStartNode node = new XamlConstructorParametersStartNode(
0,
0,
--_depth);
_bamlRecordWriter.WriteConstructorParametersStart(node);
}
/// <summary>
/// Write the end of constructor section that follows the start of an element.
/// </summary>
public void WriteEndConstructor()
{
VerifyEndTagState(BamlRecordType.ConstructorParametersStart,
BamlRecordType.ConstructorParametersEnd);
XamlConstructorParametersEndNode node = new XamlConstructorParametersEndNode(
0,
0,
--_depth);
_bamlRecordWriter.WriteConstructorParametersEnd(node);
}
/// <summary>
/// Write simple property information to baml.
/// </summary>
/// <remarks>
/// If the type of this property supports
/// custom serialization using a XamlSerializer and custom serialization
/// is chosen, then write out a
/// Custom serialization record. Note that for custom serialization
/// to work, the assembly that contains the property's type must be
/// loaded. If custom serialization is not chosen, then
/// write out a 'normal' record, which will cause type conversion to happen
/// at load time from the stored string.
/// </remarks>
public void WriteProperty(
string assemblyName,
string ownerTypeFullName,
string propName,
string value,
BamlAttributeUsage propUsage)
{
VerifyWriteState();
BamlRecordType parentType = PeekRecordType();
if (parentType != BamlRecordType.ElementStart)
{
throw new InvalidOperationException(SR.Get(SRID.BamlWriterNoInElement,
"WriteProperty",
parentType.ToString()));
}
object dpOrPi;
Type declaringType;
GetDpOrPi(assemblyName, ownerTypeFullName, propName, out dpOrPi, out declaringType);
// Check if the value is a MarkupExtension. If so it must be expanded into
// a series of baml records. Otherwise just write out the property.
AttributeData data = _extensionParser.IsMarkupExtensionAttribute(
declaringType,
propName,
ref value,
0, // No line numbers for baml
0,
0,
dpOrPi);
if (data == null)
{
XamlPropertyNode propNode = new XamlPropertyNode(
0,
0,
_depth,
dpOrPi,
assemblyName,
ownerTypeFullName,
propName,
value,
propUsage,
false);
Type propType = XamlTypeMapper.GetPropertyType(dpOrPi);
if (propType == typeof(DependencyProperty))
{
Type ownerType = null;
_dpProperty = XamlTypeMapper.ParsePropertyName(_parserContext, value, ref ownerType);
if (_bamlRecordWriter != null && _dpProperty != null)
{
short typeId;
short propertyId = _parserContext.MapTable.GetAttributeOrTypeId(_bamlRecordWriter.BinaryWriter,
ownerType,
_dpProperty.Name,
out typeId);
if (propertyId < 0)
{
propNode.ValueId = propertyId;
propNode.MemberName = null;
}
else
{
propNode.ValueId = typeId;
propNode.MemberName = _dpProperty.Name;
}
}
}
else if (_dpProperty != null)
{
propNode.ValuePropertyType = _dpProperty.PropertyType;
propNode.ValuePropertyMember = _dpProperty;
propNode.ValuePropertyName = _dpProperty.Name;
propNode.ValueDeclaringType = _dpProperty.OwnerType;
string propAssemblyName = _dpProperty.OwnerType.Assembly.FullName;
_dpProperty = null;
}
_bamlRecordWriter.WriteProperty(propNode);
}
else
{
if (data.IsSimple)
{
if (data.IsTypeExtension)
{
Type typeValue = _xamlTypeMapper.GetTypeFromBaseString(data.Args,
_parserContext,
true);
Debug.Assert(typeValue != null);
XamlPropertyWithTypeNode xamlPropertyWithTypeNode =
new XamlPropertyWithTypeNode(0,
0,
_depth,
dpOrPi,
assemblyName,
ownerTypeFullName,
propName,
typeValue.FullName,
typeValue.Assembly.FullName,
typeValue,
string.Empty,
string.Empty);
_bamlRecordWriter.WritePropertyWithType(xamlPropertyWithTypeNode);
}
else
{
XamlPropertyWithExtensionNode xamlPropertyWithExtensionNode =
new XamlPropertyWithExtensionNode(0,
0,
_depth,
dpOrPi,
assemblyName,
ownerTypeFullName,
propName,
data.Args,
data.ExtensionTypeId,
data.IsValueNestedExtension,
data.IsValueTypeExtension);
_bamlRecordWriter.WritePropertyWithExtension(xamlPropertyWithExtensionNode);
}
}
else
{
_extensionParser.CompileAttribute(
_markupExtensionNodes, data);
}
}
}
/// <summary>
/// Write Content Property Record.
/// </summary>
public void WriteContentProperty(
string assemblyName,
string ownerTypeFullName,
string propName )
{
object dpOrPi;
Type declaringType;
GetDpOrPi(assemblyName, ownerTypeFullName, propName, out dpOrPi, out declaringType);
XamlContentPropertyNode CpaNode = new XamlContentPropertyNode(
0, 0, _depth,
dpOrPi,
assemblyName,
ownerTypeFullName,
propName);
_bamlRecordWriter.WriteContentProperty( CpaNode );
}
/// <summary>
/// Write xml namespace declaration information to baml.
/// </summary>
/// <remarks>
/// This is used for setting the default namespace, or for mapping
/// a namespace prefix (or localName) to a namespace. If prefix is
/// an empty string, then this sets the default namespace.
/// </remarks>
public void WriteXmlnsProperty(
string localName,
string xmlNamespace)
{
VerifyWriteState();
BamlRecordType parentType = PeekRecordType();
if (parentType != BamlRecordType.ElementStart &&
parentType != BamlRecordType.PropertyComplexStart &&
parentType != BamlRecordType.PropertyArrayStart &&
parentType != BamlRecordType.PropertyIListStart &&
parentType != BamlRecordType.PropertyIDictionaryStart)
{
throw new InvalidOperationException(SR.Get(SRID.BamlWriterBadXmlns,
"WriteXmlnsProperty",
parentType.ToString()));
}
XamlXmlnsPropertyNode xmlnsNode = new XamlXmlnsPropertyNode(
0,
0,
_depth,
localName,
xmlNamespace);
_bamlRecordWriter.WriteNamespacePrefix(xmlnsNode);
_parserContext.XmlnsDictionary[localName] = xmlNamespace;
}
/// <summary>
/// Write an attribute in the Definition namespace.
/// </summary>
/// <remarks>
/// This is really a processing directive, rather than an actual property.
/// It is used to define keys for dictionaries, resource references,
/// language declarations, base class names for tags, etc.
/// </remarks>
public void WriteDefAttribute(
string name,
string value)
{
VerifyWriteState();
BamlRecordType parentType = PeekRecordType();
if (parentType != BamlRecordType.ElementStart &&
name != "Uid" ) // Parser's supposed to ignore x:Uid everywhere
{
throw new InvalidOperationException(SR.Get(SRID.BamlWriterNoInElement,
"WriteDefAttribute",
parentType.ToString()));
}
else if (name == XamlReaderHelper.DefinitionName)
{
// Check if this is a MarkupExtension, and if so expand it in xaml so that
// it represents a key tree.
DefAttributeData data = _extensionParser.IsMarkupExtensionDefAttribute(
PeekElementType(),
ref value, 0, 0, 0);
if (data != null)
{
if (name != XamlReaderHelper.DefinitionName)
{
data.IsSimple = false;
}
if (data.IsSimple)
{
// If the MarkupExtension does not expand out into a complex property
// subtree, but can be handled inline with other properties, then
// process it immediately in place of the normal property
int colonIndex = data.Args.IndexOf(':');
string prefix = string.Empty;
string typeName = data.Args;
if (colonIndex > 0)
{
prefix = data.Args.Substring(0, colonIndex);
typeName = data.Args.Substring(colonIndex+1);
}
string valueNamespaceURI = _parserContext.XmlnsDictionary[prefix];
string valueAssemblyName = string.Empty;
string valueTypeFullName = string.Empty;
Type valueElementType = null;
Type valueSerializerType = null;
bool resolvedTag = ((IParserHelper)this).GetElementType(false, typeName,
valueNamespaceURI,ref valueAssemblyName,
ref valueTypeFullName, ref valueElementType,
ref valueSerializerType);
// If we can't resolve a simple TypeExtension value at compile time,
// then write it out as a normal type extension and wait until runtime
// since the type may not be visible now.
if (resolvedTag)
{
XamlDefAttributeKeyTypeNode defKeyNode = new XamlDefAttributeKeyTypeNode(
0,
0,
_depth,
valueTypeFullName,
valueElementType.Assembly.FullName,
valueElementType);
_bamlRecordWriter.WriteDefAttributeKeyType(defKeyNode);
}
else
{
data.IsSimple = false;
data.Args += "}";
}
}
if (!data.IsSimple)
{
_extensionParser.CompileDictionaryKey(
_markupExtensionNodes, data);
}
return;
}
}
XamlDefAttributeNode defNode = new XamlDefAttributeNode(
0,
0,
_depth,
name,
value);
_bamlRecordWriter.WriteDefAttribute(defNode);
}
/// <summary>
/// Write an attribute in the PresentationOptions namespace.
/// </summary>
/// <remarks>
/// This is really a processing directive, rather than an actual property.
/// It is used to define WPF-specific parsing options (e.g., PresentationOptions:Freeze)
/// </remarks>
public void WritePresentationOptionsAttribute(
string name,
string value)
{
VerifyWriteState();
XamlPresentationOptionsAttributeNode defNode = new XamlPresentationOptionsAttributeNode(
0,
0,
_depth,
name,
value);
_bamlRecordWriter.WritePresentationOptionsAttribute(defNode);
}
/// <summary>
/// Write the start of a complex property
/// </summary>
/// <remarks>
/// A complex property start marks the beginning of an object that exists
/// in a property on an element in the tree.
/// </remarks>
public void WriteStartComplexProperty(
string assemblyName,
string ownerTypeFullName,
string propName)
{
VerifyWriteState();
_parserContext.PushScope();
ProcessMarkupExtensionNodes();
object dpOrPi;
Type ownerType;
Type propertyType = null;
bool propertyCanWrite = true;
GetDpOrPi(assemblyName, ownerTypeFullName, propName, out dpOrPi, out ownerType);
if (dpOrPi == null)
{
MethodInfo mi = GetMi(assemblyName, ownerTypeFullName, propName, out ownerType);
if (mi != null)
{
XamlTypeMapper.GetPropertyType(mi, out propertyType, out propertyCanWrite);
}
}
else
{
propertyType = XamlTypeMapper.GetPropertyType(dpOrPi);
PropertyInfo pi = dpOrPi as PropertyInfo;
if (pi != null)
{
propertyCanWrite = pi.CanWrite;
}
else
{
DependencyProperty dp = dpOrPi as DependencyProperty;
if (dp != null)
{
propertyCanWrite = !dp.ReadOnly;
}
}
}
// Based on the type of the property, we could write this as
// a complex IList, Array, IDictionary or a regular complex property.
// NOTE: The order this is checked in must the same order as the
// XamlReaderHelper.CompileComplexProperty so that we have
// the same property behavior (eg - if something implements
// IDictionary and IList, it is treated as an IList)
if (propertyType == null)
{
// Unknown complex properties are written out using the string
// information passed. This applies to things like Set.Value
// and other style related DPs
Push(BamlRecordType.PropertyComplexStart);
XamlPropertyComplexStartNode propertyStart = new XamlPropertyComplexStartNode(
0,
0,
_depth++,
null,
assemblyName,
ownerTypeFullName,
propName);
_bamlRecordWriter.WritePropertyComplexStart(propertyStart);
}
else
{
BamlRecordType recordType = BamlRecordManager.GetPropertyStartRecordType(propertyType, propertyCanWrite);
Push(recordType);
switch (recordType)
{
case BamlRecordType.PropertyArrayStart:
{
XamlPropertyArrayStartNode arrayStart = new XamlPropertyArrayStartNode(
0,
0,
_depth++,
dpOrPi,
assemblyName,
ownerTypeFullName,
propName);
_bamlRecordWriter.WritePropertyArrayStart(arrayStart);
break;
}
case BamlRecordType.PropertyIDictionaryStart:
{
XamlPropertyIDictionaryStartNode dictionaryStart =
new XamlPropertyIDictionaryStartNode(
0,
0,
_depth++,
dpOrPi,
assemblyName,
ownerTypeFullName,
propName);
_bamlRecordWriter.WritePropertyIDictionaryStart(dictionaryStart);
break;
}
case BamlRecordType.PropertyIListStart:
{
XamlPropertyIListStartNode listStart = new XamlPropertyIListStartNode(
0,
0,
_depth++,
dpOrPi,
assemblyName,
ownerTypeFullName,
propName);
_bamlRecordWriter.WritePropertyIListStart(listStart);
break;
}
default: // PropertyComplexStart
{
XamlPropertyComplexStartNode node = new XamlPropertyComplexStartNode(
0,
0,
_depth++,
dpOrPi,
assemblyName,
ownerTypeFullName,
propName);
_bamlRecordWriter.WritePropertyComplexStart(node);
break;
}
}
}
}
/// <summary>
/// Write the end of the complex property
/// </summary>
public void WriteEndComplexProperty()
{
VerifyWriteState();
// The type of end record written depends on what the start record
// was. This is held on the _nodeTypeStack
BamlRecordType startTagType = Pop();
switch (startTagType)
{
case BamlRecordType.PropertyArrayStart:
XamlPropertyArrayEndNode arrayEnd =
new XamlPropertyArrayEndNode(
0,
0,
--_depth);
_bamlRecordWriter.WritePropertyArrayEnd(arrayEnd);
break;
case BamlRecordType.PropertyIListStart:
XamlPropertyIListEndNode listEnd =
new XamlPropertyIListEndNode(
0,
0,
--_depth);
_bamlRecordWriter.WritePropertyIListEnd(listEnd);
break;
case BamlRecordType.PropertyIDictionaryStart:
XamlPropertyIDictionaryEndNode dictionaryEnd =
new XamlPropertyIDictionaryEndNode(
0,
0,
--_depth);
_bamlRecordWriter.WritePropertyIDictionaryEnd(dictionaryEnd);
break;
case BamlRecordType.PropertyComplexStart:
XamlPropertyComplexEndNode complexEnd =
new XamlPropertyComplexEndNode(
0,
0,
--_depth);
_bamlRecordWriter.WritePropertyComplexEnd(complexEnd);
break;
default:
throw new InvalidOperationException(
SR.Get(SRID.BamlWriterBadScope,
startTagType.ToString(),
BamlRecordType.PropertyComplexEnd.ToString()));
}
_parserContext.PopScope();
}
/// <summary>
/// Write a literal content record to baml stream
/// </summary>
public void WriteLiteralContent(
string contents)
{
VerifyWriteState();
ProcessMarkupExtensionNodes();
XamlLiteralContentNode literalContent = new XamlLiteralContentNode(
0,
0,
_depth,
contents);
_bamlRecordWriter.WriteLiteralContent(literalContent);
}
/// <summary>
/// Write a mapping processing instruction to baml stream
/// </summary>
public void WritePIMapping(
string xmlNamespace,
string clrNamespace,
string assemblyName)
{
VerifyWriteState();
ProcessMarkupExtensionNodes();
XamlPIMappingNode piMapping = new XamlPIMappingNode(
0,
0,
_depth,
xmlNamespace,
clrNamespace,
assemblyName);
if (!_xamlTypeMapper.PITable.Contains(xmlNamespace))
{
ClrNamespaceAssemblyPair mapping = new ClrNamespaceAssemblyPair(clrNamespace, assemblyName);
_xamlTypeMapper.PITable.Add(xmlNamespace, mapping);
}
// Write it out anyway. It is redundant but we are being asked to write it so write it.
// In the round trip case this will preserve the exact file data.
_bamlRecordWriter.WritePIMapping(piMapping);
}
/// <summary>
/// Write text content into baml stream
/// </summary>
public void WriteText(
string textContent,
string typeConverterAssemblyName,
string typeConverterName)
{
VerifyWriteState();
ProcessMarkupExtensionNodes();
Type typeConverter=null;
if (!String.IsNullOrEmpty(typeConverterName))
{
typeConverter = GetType(typeConverterAssemblyName, typeConverterName);
}
XamlTextNode textNode = new XamlTextNode(
0,
0,
_depth,
textContent,
typeConverter);
_bamlRecordWriter.WriteText(textNode);
}
/// <summary>
/// Write a routed event record to BAML.
/// </summary>
/// <remarks>
/// The Avalon parser does not process routed event records itself and will
/// throw an exception if it encounters a routed event record in BAML. It
/// is included here for completeness and future expandability.
/// </remarks>
public void WriteRoutedEvent(
string assemblyName,
string ownerTypeFullName,
string eventIdName,
string handlerName)
{
#if EVENTSUPPORT
VerifyWriteState();
XamlRoutedEventNode eventNode = new XamlRoutedEventNode(
0,
0,
_depth,
null,
assemblyName,
ownerTypeFullName,
eventIdName,
handlerName);
_bamlRecordWriter.WriteRoutedEvent(eventNode);
#else
throw new NotSupportedException(SR.Get(SRID.ParserBamlEvent, eventIdName));
#endif
}
/// <summary>
/// Write an event record to BAML.
/// </summary>
/// <remarks>
/// The Avalon parser does not process event records itself and will
/// throw an exception if it encounters an event record in BAML. It
/// is included here for completeness and future expandability.
/// </remarks>
public void WriteEvent(
string eventName,
string handlerName)
{
#if EVENTSUPPORT
VerifyWriteState();
XamlClrEventNode eventNode = new XamlClrEventNode(
0,
0,
_depth,
eventName,
null,
handlerName);
_bamlRecordWriter.WriteClrEvent(eventNode);
#else
throw new NotSupportedException(SR.Get(SRID.ParserBamlEvent, eventName));
#endif
}
#endregion Record Writing
#region Internal Methods
/***************************************************************************\
*
* BamlWriter.ProcessMarkupExtensionNodes
*
* Write out baml records for all the xamlnodes contained in the buffered
* markup extension list.
* NOTE: This list must contain only xamlnodes that are known to be part of
* MarkupExtensions. This is NOT a general method to handle all types
* of xaml nodes.
*
\***************************************************************************/
private void ProcessMarkupExtensionNodes()
{
for (int i=0; i < _markupExtensionNodes.Count; i++)
{
XamlNode node = _markupExtensionNodes[i] as XamlNode;
switch (node.TokenType)
{
case XamlNodeType.ElementStart:
_bamlRecordWriter.WriteElementStart((XamlElementStartNode)node);
break;
case XamlNodeType.ElementEnd:
_bamlRecordWriter.WriteElementEnd((XamlElementEndNode)node);
break;
case XamlNodeType.KeyElementStart:
_bamlRecordWriter.WriteKeyElementStart((XamlKeyElementStartNode)node);
break;
case XamlNodeType.KeyElementEnd:
_bamlRecordWriter.WriteKeyElementEnd((XamlKeyElementEndNode)node);
break;
case XamlNodeType.Property:
_bamlRecordWriter.WriteProperty((XamlPropertyNode)node);
break;
case XamlNodeType.PropertyWithExtension:
_bamlRecordWriter.WritePropertyWithExtension((XamlPropertyWithExtensionNode)node);
break;
case XamlNodeType.PropertyWithType:
_bamlRecordWriter.WritePropertyWithType((XamlPropertyWithTypeNode)node);
break;
case XamlNodeType.PropertyComplexStart:
_bamlRecordWriter.WritePropertyComplexStart((XamlPropertyComplexStartNode)node);
break;
case XamlNodeType.PropertyComplexEnd:
_bamlRecordWriter.WritePropertyComplexEnd((XamlPropertyComplexEndNode)node);
break;
case XamlNodeType.Text:
_bamlRecordWriter.WriteText((XamlTextNode)node);
break;
case XamlNodeType.EndAttributes:
_bamlRecordWriter.WriteEndAttributes((XamlEndAttributesNode)node);
break;
case XamlNodeType.ConstructorParametersStart:
_bamlRecordWriter.WriteConstructorParametersStart((XamlConstructorParametersStartNode)node);
break;
case XamlNodeType.ConstructorParametersEnd:
_bamlRecordWriter.WriteConstructorParametersEnd((XamlConstructorParametersEndNode)node);
break;
default:
throw new InvalidOperationException(SR.Get(SRID.BamlWriterUnknownMarkupExtension));
}
}
_markupExtensionNodes.Clear();
}
/***************************************************************************\
*
* BamlWriter.VerifyWriteState
*
* Verify that we are in a good state to perform a record write. Throw
* appropriate exceptions if not.
*
\***************************************************************************/
private void VerifyWriteState()
{
if (_closed)
{
throw new InvalidOperationException(SR.Get(SRID.BamlWriterClosed));
}
if (!_startDocumentWritten)
{
throw new InvalidOperationException(SR.Get(SRID.BamlWriterStartDoc));
}
}
/***************************************************************************\
*
* BamlWriter.VerifyEndTagState
*
* Verify that we are in a good state to perform a record write and that
* the xamlnodetype on the node type stack is of the expected type. This
* is called when an end tag record is written
*
\***************************************************************************/
private void VerifyEndTagState(
BamlRecordType expectedStartTag,
BamlRecordType endTagBeingWritten)
{
VerifyWriteState();
BamlRecordType startTagState = Pop();
if (startTagState != expectedStartTag)
{
throw new InvalidOperationException(SR.Get(SRID.BamlWriterBadScope,
startTagState.ToString(),
endTagBeingWritten.ToString()));
}
}
/***************************************************************************\
*
* BamlWriter.GetAssembly
*
* Get the Assembly given a name. This uses the LoadWrapper to load the
* assembly from the current directory.
* NOTE: Assembly paths are not currently supported, but may be in the
* future if the need arises.
*
\***************************************************************************/
private Assembly GetAssembly(string assemblyName)
{
Assembly assy = _assemblies[assemblyName] as Assembly;
if (assy == null)
{
assy = ReflectionHelper.LoadAssembly(assemblyName, null);
if (assy == null)
{
throw new ArgumentException(SR.Get(SRID.BamlWriterBadAssembly,
assemblyName));
}
else
{
_assemblies[assemblyName] = assy;
}
}
return assy;
}
/***************************************************************************\
*
* BamlWriter.GetType
*
* Get the Type given an assembly name where the type is declared and the
* type's fully qualified name
*
\***************************************************************************/
private Type GetType(
string assemblyName,
string typeFullName)
{
// Get the assembly that contains the type of the element
Assembly assembly = GetAssembly(assemblyName);
// Now see if the type is declared in this assembly
Type objectType = assembly.GetType(typeFullName);
// Note that null objectType is allowed, since this may be something like
// a <Set> element in a style, which is mapped to a element tag
return objectType;
}
/***************************************************************************\
*
* BamlWriter.GetDpOrPi
*
* Get the DependencyProperty or the PropertyInfo that corresponds to the
* passed property name on the passed owner type (or type where the
* property is declared).
*
\***************************************************************************/
private object GetDpOrPi(
Type ownerType,
string propName)
{
// Now that we have the type, see if this is a DependencyProperty or
// a PropertyInfo. Note that ownerType may be null for fake properties
// like those associated with Styles. Note also that the property may
// not resolve to a known DP. This is allowed for fake properties like
// those contained in Styles, such as Set.Value.
object dpOrPi = null;
#if !PBTCOMPILER
if (ownerType != null)
{
dpOrPi = DependencyProperty.FromName(propName, ownerType);
if (dpOrPi == null)
{
PropertyInfo mostDerived = null;
MemberInfo[] infos = ownerType.GetMember(propName, MemberTypes.Property, BindingFlags.Instance | BindingFlags.Public);
foreach(PropertyInfo pi in infos)
{
if(pi.GetIndexParameters().Length == 0)
{
if(mostDerived == null || mostDerived.DeclaringType.IsAssignableFrom(pi.DeclaringType))
{
mostDerived = pi;
}
}
}
dpOrPi = mostDerived;
}
}
#else
if (ownerType != null)
{
dpOrPi = KnownTypes.Types[(int)KnownElements.DependencyProperty].InvokeMember("FromName",
BindingFlags.InvokeMethod,
null,
null,
new object[] {propName, ownerType} );
if (dpOrPi == null)
{
dpOrPi = ownerType.GetProperty(propName,
BindingFlags.Instance | BindingFlags.Public);
}
}
#endif
return dpOrPi;
}
/***************************************************************************\
*
* BamlWriter.GetDpOrPi
*
* Get the DependencyProperty or the PropertyInfo that corresponds to the
* passed property name on the passed owner type name. This typename is
* first resolved to a type.
*
\***************************************************************************/
private void GetDpOrPi(
string assemblyName,
string ownerTypeFullName,
string propName,
out object dpOrPi,
out Type ownerType)
{
// If there is no valid owner or assembly, then we can't resolve the type,
// so just return null. This can occur if we are writing 'fake' properties
// that are used for things such as Style property triggers.
if (assemblyName == string.Empty || ownerTypeFullName == string.Empty)
{
dpOrPi = null;
ownerType = null;
}
else
{
ownerType = GetType(assemblyName, ownerTypeFullName);
dpOrPi = GetDpOrPi(ownerType, propName);
}
}
private MethodInfo GetMi(Type ownerType, string propName)
{
MethodInfo memberInfo = null;
memberInfo = ownerType.GetMethod("Set" + propName,
BindingFlags.Public |
BindingFlags.Static |
BindingFlags.FlattenHierarchy);
if (memberInfo != null && ((MethodInfo)memberInfo).GetParameters().Length != 2)
{
memberInfo = null;
}
// Try read-only case (Getter only)
if (memberInfo == null)
{
memberInfo = ownerType.GetMethod("Get" + propName,
BindingFlags.Public |
BindingFlags.Static |
BindingFlags.FlattenHierarchy);
if (memberInfo != null && ((MethodInfo)memberInfo).GetParameters().Length != 1)
{
memberInfo = null;
}
}
return memberInfo;
}
private MethodInfo GetMi(
string assemblyName,
string ownerTypeFullName,
string propName,
out Type ownerType)
{
MethodInfo mi = null;
// If there is no valid owner or assembly, then we can't resolve the type,
// so just return null. This can occur if we are writing 'fake' properties
// that are used for things such as Style property triggers.
if (assemblyName == string.Empty || ownerTypeFullName == string.Empty)
{
mi = null;
ownerType = null;
}
else
{
ownerType = GetType(assemblyName, ownerTypeFullName);
mi = GetMi(ownerType, propName);
}
return mi;
}
// Helper methods for dealing with the node stack
// Push a new record type on the stack. If we have not generated an
// end attributes write operation for the current item on the stack, and
// that item is a start element, then now is the time to do it.
private void Push(BamlRecordType recordType)
{
CheckEndAttributes();
_nodeTypeStack.Push(new WriteStackNode(recordType));
}
private void Push(BamlRecordType recordType, Type elementType)
{
CheckEndAttributes();
_nodeTypeStack.Push(new WriteStackNode(recordType, elementType));
}
// Pop an item off the node stack and return its type.
private BamlRecordType Pop()
{
WriteStackNode stackNode = _nodeTypeStack.Pop() as WriteStackNode;
Debug.Assert(stackNode != null);
return stackNode.RecordType;
}
// Return the record type on the top of the stack
private BamlRecordType PeekRecordType()
{
WriteStackNode stackNode = _nodeTypeStack.Peek() as WriteStackNode;
Debug.Assert(stackNode != null);
return stackNode.RecordType;
}
// Return the element type on the top of the stack
private Type PeekElementType()
{
WriteStackNode stackNode = _nodeTypeStack.Peek() as WriteStackNode;
Debug.Assert(stackNode != null);
return stackNode.ElementType;
}
// Check if we have to insert an EndAttributes xaml node at the end
// of an element start tag.
private void CheckEndAttributes()
{
if (_nodeTypeStack.Count > 0)
{
WriteStackNode parentNode = _nodeTypeStack.Peek() as WriteStackNode;
if (!parentNode.EndAttributesReached &&
parentNode.RecordType == BamlRecordType.ElementStart)
{
XamlEndAttributesNode node = new XamlEndAttributesNode(
0,
0,
_depth,
false);
_bamlRecordWriter.WriteEndAttributes(node);
}
parentNode.EndAttributesReached = true;
}
}
#endregion Internal Methods
#region Data
// Item pushed on a node stack to keep track for matching
// end tags and for determining when the end of the
// start tag has been reached for generating an end attribute write.
private class WriteStackNode
{
public WriteStackNode(
BamlRecordType recordType)
{
_recordType = recordType;
_endAttributesReached = false;
}
public WriteStackNode(
BamlRecordType recordType,
Type elementType) : this(recordType)
{
_elementType = elementType;
}
public BamlRecordType RecordType
{
get { return _recordType; }
}
public bool EndAttributesReached
{
get { return _endAttributesReached; }
set { _endAttributesReached = value; }
}
public Type ElementType
{
get { return _elementType; }
}
bool _endAttributesReached;
BamlRecordType _recordType;
Type _elementType;
}
// Writer that actually writes BamlRecords to a stream.
BamlRecordWriter _bamlRecordWriter;
// True if the DocumentStart record has been written to the stream.
bool _startDocumentWritten;
// The depth of the element tree, including complex properties
int _depth;
// True if Close() has been called.
bool _closed;
// If a custom property is of Type DependencyProperty, this is used to provide
// info about the Type of value for such a property in order to write it out in
// an optimized form by its custom serializer.
DependencyProperty _dpProperty;
// Stack of the type of nodes written to the baml stream. This is
// used for end-tag matching and basic structure checking. This
// contains WriteStackNode objects.
ParserStack _nodeTypeStack;
// Cache of assemblies that are needed for type resolutions when
// doingIBamlSerialize
Hashtable _assemblies;
// XamlTypeMapper used by this writer
XamlTypeMapper _xamlTypeMapper;
// ParserContext for this writer
ParserContext _parserContext;
// The helper class that handles parsing of MarkupExtension values.
MarkupExtensionParser _extensionParser;
// Buffered XamlNodes that occur when a property with a MarkupExtension value
// is written and expanded into a complex property subtree.
ArrayList _markupExtensionNodes;
#endregion Data
}
internal class BamlWriterXamlTypeMapper : XamlTypeMapper
{
internal BamlWriterXamlTypeMapper(
string[] assemblyNames,
NamespaceMapEntry[] namespaceMaps) : base(assemblyNames, namespaceMaps)
{
}
/// <summary>
/// Allows BamlWriter to allow access to legitimate internal types
/// </summary>
/// <param name="type">The internal type</param>
/// <returns>
/// Always Returns true by default, since this is used by localization
/// </returns>
sealed protected override bool AllowInternalType(Type type)
{
return true;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using Hammock.Model;
using Newtonsoft.Json;
namespace TweetSharp
{
#if !SILVERLIGHT
[Serializable]
#endif
#if !Smartphone && !NET20
[DataContract]
[DebuggerDisplay("{User.ScreenName}: {Text}")]
#endif
[JsonObject(MemberSerialization.OptIn)]
public class TwitterStatus : PropertyChangedBase,
IComparable<TwitterStatus>,
IEquatable<TwitterStatus>,
ITwitterModel,
ITweetable
{
private DateTime _createdDate;
private long _id;
private string _idStr;
private string _inReplyToScreenName;
private long? _inReplyToStatusId;
private long? _inReplyToUserId;
private bool _isFavorited;
private bool _isTruncated;
private string _source;
private string _text;
private TwitterUser _user;
private TwitterStatus _retweetedStatus;
private TwitterGeoLocation _location;
private string _language;
private TwitterEntities _entities;
private bool? _isPossiblySensitive;
private TwitterPlace _place;
private int _retweetCount;
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual long Id
{
get { return _id; }
set
{
if (_id == value)
{
return;
}
_id = value;
OnPropertyChanged("Id");
}
}
[JsonProperty("id_str")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string IdStr
{
get { return _idStr; }
set
{
if (_idStr == value)
{
return;
}
_idStr = value;
OnPropertyChanged("IdStr");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual long? InReplyToUserId
{
get { return _inReplyToUserId; }
set
{
if (_inReplyToUserId == value)
{
return;
}
_inReplyToUserId = value;
OnPropertyChanged("InReplyToUserId");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual long? InReplyToStatusId
{
get { return _inReplyToStatusId; }
set
{
if (_inReplyToStatusId == value)
{
return;
}
_inReplyToStatusId = value;
OnPropertyChanged("InReplyToStatusId");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string InReplyToScreenName
{
get { return _inReplyToScreenName; }
set
{
if (_inReplyToScreenName == value)
{
return;
}
_inReplyToScreenName = value;
OnPropertyChanged("InReplyToScreenName");
}
}
[JsonProperty("truncated")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual bool IsTruncated
{
get { return _isTruncated; }
set
{
if (_isTruncated == value)
{
return;
}
_isTruncated = value;
OnPropertyChanged("IsTruncated");
}
}
[JsonProperty("favorited")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual bool IsFavorited
{
get { return _isFavorited; }
set
{
if (_isFavorited == value)
{
return;
}
_isFavorited = value;
OnPropertyChanged("IsFavorited");
}
}
[JsonProperty("retweet_count")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual int RetweetCount
{
get
{
return _retweetCount;
}
set
{
if (_retweetCount == value)
{
return;
}
_retweetCount = value;
OnPropertyChanged("RetweetCount");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string Text
{
get { return _text; }
set
{
if (_text == value)
{
return;
}
_text = value;
_textAsHtml = null;
_textDecoded = null;
OnPropertyChanged("Text");
}
}
private string _textAsHtml;
public virtual string TextAsHtml
{
get
{
return (_textAsHtml ?? (_textAsHtml = this.ParseTextWithEntities()));
}
set
{
_textAsHtml = value;
this.OnPropertyChanged("TextAsHtml");
}
}
private string _textDecoded;
public virtual string TextDecoded
{
get
{
if (string.IsNullOrEmpty(Text))
{
return Text;
}
#if !SILVERLIGHT && !WINDOWS_PHONE
return _textDecoded ?? (_textDecoded = System.Compat.Web.HttpUtility.HtmlDecode(Text));
#elif WINDOWS_PHONE
return _textDecoded ?? (_textDecoded = System.Net.HttpUtility.HtmlDecode(Text));
#else
return _textDecoded ?? (_textDecoded = System.Windows.Browser.HttpUtility.HtmlDecode(Text));
#endif
}
set
{
_textDecoded = value;
OnPropertyChanged("TextDecoded");
}
}
public ITweeter Author
{
get { return User; }
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string Source
{
get { return _source; }
set
{
if (_source == value)
{
return;
}
_source = value;
OnPropertyChanged("Source");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterUser User
{
get { return _user; }
set
{
if (_user == value)
{
return;
}
_user = value;
OnPropertyChanged("TwitterUser");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterStatus RetweetedStatus
{
get { return _retweetedStatus; }
set
{
if (_retweetedStatus == value)
{
return;
}
_retweetedStatus = value;
OnPropertyChanged("RetweetedStatus");
}
}
[JsonProperty("created_at")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual DateTime CreatedDate
{
get { return _createdDate; }
set
{
if (_createdDate == value)
{
return;
}
_createdDate = value;
OnPropertyChanged("CreatedDate");
}
}
[JsonProperty("geo")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterGeoLocation Location
{
get { return _location; }
set
{
if (_location == value)
{
return;
}
_location = value;
OnPropertyChanged("Location");
}
}
[JsonProperty("lang")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string Language
{
get { return _language; }
set
{
if (_language == value)
{
return;
}
_language = value;
OnPropertyChanged("Language");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterEntities Entities
{
get { return _entities; }
set
{
if (_entities == value)
{
return;
}
_entities = value;
OnPropertyChanged("Entities");
}
}
[JsonProperty("possibly_sensitive")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual bool? IsPossiblySensitive
{
get { return _isPossiblySensitive; }
set
{
if (_isPossiblySensitive == value)
{
return;
}
_isPossiblySensitive = value;
OnPropertyChanged("IsPossiblySensitive");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterPlace Place
{
get { return _place; }
set
{
if (_place == value)
{
return;
}
_place = value;
OnPropertyChanged("Place");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string RawSource { get; set; }
#region IComparable<TwitterStatus> Members
public int CompareTo(TwitterStatus other)
{
return other.Id == Id ? 0 : other.Id > Id ? -1 : 1;
}
#endregion
#region IEquatable<TwitterStatus> Members
public bool Equals(TwitterStatus status)
{
if (ReferenceEquals(null, status))
{
return false;
}
if (ReferenceEquals(this, status))
{
return true;
}
return status.Id == Id;
}
#endregion
public override bool Equals(object status)
{
if (ReferenceEquals(null, status))
{
return false;
}
if (ReferenceEquals(this, status))
{
return true;
}
return status.GetType() == typeof (TwitterStatus) && Equals((TwitterStatus) status);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
public static bool operator ==(TwitterStatus left, TwitterStatus right)
{
return Equals(left, right);
}
public static bool operator !=(TwitterStatus left, TwitterStatus right)
{
return !Equals(left, right);
}
}
}
| |
/*******************************************************************************
* Copyright 2019 Viridian Software Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace monogame.Graphics
{
internal class MonoGameShapeRenderer
{
private static Vector2 _sharedPositionVector = Vector2.Zero;
private static Vector2 _sharedScaleVector = Vector2.One;
private static Texture2D _sharedTexture;
private readonly SpriteBatch _spriteBatch;
private readonly GraphicsDevice _graphicsDevice;
private Color _color;
internal int LineHeight;
public MonoGameShapeRenderer(GraphicsDevice graphicsDevice, MonoGameColor color, SpriteBatch spriteBatch)
{
_graphicsDevice = graphicsDevice;
setColor(color);
_spriteBatch = spriteBatch;
if (_sharedTexture == null)
{
_sharedTexture = new Texture2D(_graphicsDevice, 1, 1, false, SurfaceFormat.Color);
_sharedTexture.SetData(new[]{0xffffffff});
}
}
public void setColor(MonoGameColor color)
{
_color = color._color;
}
private void draw(Texture2D texture, Vector2 position, Color color, Vector2 scale = default(Vector2))
{
if (scale == default(Vector2))
{
scale = Vector2.One;
}
_spriteBatch.Draw(texture,
position, null, color, 0f,
Vector2.Zero, scale, SpriteEffects.None, 0f);
}
public void drawLine(int x, int y, int x2, int y2)
{
var minX = Math.Min(x, x2);
var minY = Math.Min(y, y2);
x -= minX;
x2 -= minX;
y -= minY;
y2 -= minY;
var deltaX = x2 - x;
var deltaY = y2 - y;
var deltaXSign = Math.Sign(deltaX);
var deltaYSign = Math.Sign(deltaY);
var dx2 = deltaXSign;
var dy2 = 0;
var width = Math.Abs(deltaX);
var height = Math.Abs(deltaY);
if (width <= height)
{
width = Math.Abs(deltaY);
height = Math.Abs(deltaX);
dy2 = Math.Sign(deltaY);
dx2 = 0;
}
var numerator = width >> 1 ;
for (var i=0; i<=width; i++)
{
_sharedPositionVector.X = minX + x;
_sharedPositionVector.Y = minY + y;
draw(_sharedTexture, _sharedPositionVector, color: _color);
numerator += height;
if (numerator >= width)
{
numerator -= width;
x += deltaXSign;
y += deltaYSign;
}
else
{
x += dx2;
y += dy2;
}
}
}
public void drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
{
drawLine(x1, y1, x2, y2);
drawLine(x2, y2, x3, y3);
drawLine(x3, y3, x1, y1);
}
public void drawRect(int x, int y, int width, int height)
{
_sharedPositionVector.X = x;
_sharedPositionVector.Y = y;
_sharedScaleVector.X = width;
_sharedScaleVector.Y = 1;
draw(_sharedTexture, _sharedPositionVector, _color, _sharedScaleVector);
_sharedPositionVector.Y += height;
draw(_sharedTexture, _sharedPositionVector, _color, _sharedScaleVector);
_sharedPositionVector.X = x;
_sharedPositionVector.Y = y;
_sharedScaleVector.X = 1;
_sharedScaleVector.Y = height;
draw(_sharedTexture, _sharedPositionVector, _color, _sharedScaleVector);
_sharedPositionVector.X += width;
draw(_sharedTexture, _sharedPositionVector, _color, _sharedScaleVector);
}
public void fillRect(int x, int y, int width, int height)
{
_sharedPositionVector.X = x;
_sharedPositionVector.Y = y;
_sharedScaleVector.X = width;
_sharedScaleVector.Y = height;
draw(_sharedTexture, _sharedPositionVector, _color, _sharedScaleVector);
}
private void putPixel(int pixX, int pixY, Color color)
{
_sharedPositionVector.X += pixX;
_sharedPositionVector.Y += pixY;
draw(_sharedTexture, _sharedPositionVector, color: color);
_sharedPositionVector.X -= pixX;
_sharedPositionVector.Y -= pixY;
}
public void drawCircle(int centerX, int centerY, int radius)
{
_sharedPositionVector.X = centerX;
_sharedPositionVector.Y = centerY;
var radiusSquared = radius * radius;
putPixel(0, radius, _color);
putPixel(0, -radius, _color);
putPixel(radius, 0, _color);
putPixel(-radius, 0, _color);
var x = 1;
var y = (int) Math.Sqrt(radiusSquared - 1);
while (x < y) {
putPixel(x, y, _color);
putPixel(x, -y, _color);
putPixel(-x, y, _color);
putPixel(-x, -y, _color);
putPixel(y, x, _color);
putPixel(y, -x, _color);
putPixel(-y, x, _color);
putPixel(-y, -x, _color);
x += 1;
y = (int) (Math.Sqrt(radiusSquared - x*x));
}
if (x == y) {
putPixel(x, y, _color);
putPixel(x, -y, _color);
putPixel(-x, y, _color);
putPixel(-x, -y, _color);
}
}
public void fillCircle(int centerX, int centerY, int radius)
{
_sharedPositionVector.X = centerX - radius;
_sharedPositionVector.Y = centerY - radius;
for (int circleX = 0; circleX < radius * 2; circleX++)
{
for (int circleY = 0; circleY < radius * 2; circleY++)
{
if (Math.Pow(circleX - radius, 2) + Math.Pow(circleY - radius, 2) <= Math.Pow(radius, 2))
{
draw(_sharedTexture, _sharedPositionVector, _color);
}
_sharedPositionVector.Y = _sharedPositionVector.Y + 1;
}
_sharedPositionVector.Y = centerY - radius;
_sharedPositionVector.X = _sharedPositionVector.X + 1;
}
}
public void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
{
var xMin = Math.Min(x1, Math.Min(x2, x3));
var yMin = Math.Min(y1, Math.Min(y2, y3));
var xMax = Math.Max(x1, Math.Max(x2, x3));
var yMax = Math.Max(y1, Math.Max(y2, y3));
if (xMax - xMin == 0 || yMax - yMin == 0)
{
return;
}
x1 -= xMin;
x2 -= xMin;
x3 -= xMin;
y1 -= yMin;
y2 -= yMin;
y3 -= yMin;
//sort the vertices by y
if (y1 > y2)
{
//swap x1, x2
x1 ^= x2;
x2 ^= x1;
x1 ^= x2;
//swap y1, y2
y1 ^= y2;
y2 ^= y1;
y1 ^= y2;
}
if (y1 > y3)
{
//swap x1, x3
x1 ^= x3;
x3 ^= x1;
x1 ^= x3;
//swap y1, y3
y1 ^= y3;
y3 ^= y1;
y1 ^= y3;
}
if (y2 > y3)
{
//swap x2, x3
x2 ^= x3;
x3 ^= x2;
x2 ^= x3;
//swap y2, y3
y2 ^= y3;
y3 ^= y2;
y2 ^= y3;
}
var triangleHeight = y3 - y1;
for (var i = 0; i < triangleHeight; i++)
{
var secondHalf = i > y2 - y1 || y2 == y1;
var segmentHeight = secondHalf ? y3 - y2 : y2 - y1;
var alpha = (float) i / triangleHeight;
var beta = (float) (i - (secondHalf ? y2 - y1 : 0)) / segmentHeight;
var aX = x1 + (x3 - x1) * alpha;
var bX = secondHalf ? x2 + (x3 - x2) * beta : x1 + (x2 - x1) * beta;
if (aX > bX)
{
aX += bX;
bX = aX - bX;
aX -= bX;
}
for (var j = (int) aX; j <= bX; j++)
{
_sharedPositionVector.X = xMin + j;
_sharedPositionVector.Y = yMin + y1 + i;
draw(_sharedTexture, _sharedPositionVector, _color);
}
}
}
}
}
| |
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using DocumentFormat.OpenXml.Office2013.Excel;
using Signum.Entities.Files;
using Signum.Utilities;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Signum.Engine.Files
{
public static class BlobContainerClientPool
{
static ConcurrentDictionary<(string connectionString, string blobContainerName), BlobContainerClient> Pool =
new ConcurrentDictionary<(string connectionString, string blobContainerName), BlobContainerClient>();
public static BlobContainerClient Get(string connectionString, string blobContainerName)
{
return Pool.GetOrAdd((connectionString, blobContainerName), t => new BlobContainerClient(t.connectionString, t.blobContainerName));
}
}
public enum BlobAction
{
Open,
Download
}
public class AzureBlobStoragebFileTypeAlgorithm : FileTypeAlgorithmBase, IFileTypeAlgorithm
{
public Func<IFilePath, BlobContainerClient> GetClient { get; private set; }
public Func<bool> WebDownload { get; private set; } = () => false;
public Func<IFilePath, string> CalculateSuffix { get; set; } = SuffixGenerators.Safe.YearMonth_Guid_Filename;
public bool RenameOnCollision { get; set; } = true;
public bool WeakFileReference { get; set; }
public bool CreateBlobContainerIfNotExists { get; set; }
public Func<string, int, string> RenameAlgorithm { get; set; } = FileTypeAlgorithm.DefaultRenameAlgorithm;
public Func<IFilePath, BlobAction> BlobAction { get; set; } = (IFilePath ifp) => { return Files.BlobAction.Download; };
public AzureBlobStoragebFileTypeAlgorithm(Func<IFilePath, BlobContainerClient> getClient)
{
this.GetClient = getClient;
}
public PrefixPair GetPrefixPair(IFilePath efp)
{
var client = GetClient(efp);
if (!this.WebDownload())
return PrefixPair.None();
//return PrefixPair.WebOnly($"https://{client.Uri}/{efp.Suffix}");
return PrefixPair.WebOnly($"{client.Uri}");
}
public BlobProperties GetProperties(IFilePath fp)
{
using (HeavyProfiler.Log("AzureBlobStorage GetProperties"))
{
var client = GetClient(fp);
return client.GetBlobClient(fp.Suffix).GetProperties();
}
}
public Stream OpenRead(IFilePath fp)
{
using (HeavyProfiler.Log("AzureBlobStorage OpenRead"))
{
var client = GetClient(fp);
return client.GetBlobClient(fp.Suffix).Download().Value.Content;
}
}
public byte[] ReadAllBytes(IFilePath fp)
{
using (HeavyProfiler.Log("AzureBlobStorage ReadAllBytes"))
{
var client = GetClient(fp);
return client.GetBlobClient(fp.Suffix).Download().Value.Content.ReadAllBytes();
}
}
public virtual void SaveFile(IFilePath fp)
{
using (HeavyProfiler.Log("AzureBlobStorage SaveFile"))
using (new EntityCache(EntityCacheType.ForceNew))
{
if (WeakFileReference)
return;
string suffix = CalculateSuffix(fp);
if (!suffix.HasText())
throw new InvalidOperationException("Suffix not set");
fp.SetPrefixPair(GetPrefixPair(fp));
var client = GetClient(fp);
if (CreateBlobContainerIfNotExists)
{
using (HeavyProfiler.Log("AzureBlobStorage OpenRead"))
{
client.CreateIfNotExists();
}
}
int i = 2;
fp.Suffix = suffix.Replace("\\", "/");
while (RenameOnCollision && client.ExistsBlob(fp.Suffix))
{
fp.Suffix = RenameAlgorithm(suffix, i).Replace("\\", "/");
i++;
}
try
{
var action = this.BlobAction(fp);
client.GetBlobClient(fp.Suffix).Upload(new MemoryStream(fp.BinaryFile),
httpHeaders: new Azure.Storage.Blobs.Models.BlobHttpHeaders
{
ContentType = action == Files.BlobAction.Download
? "application/octet-stream"
: ContentTypesDict.TryGet(Path.GetExtension(fp.FileName), "application/octet-stream"),
ContentDisposition = action == Files.BlobAction.Download ? "attachment" : "inline"
});
}
catch (Exception ex)
{
ex.Data.Add("Suffix", fp.Suffix);
ex.Data.Add("AccountName", client.AccountName);
ex.Data.Add("ContainerName", client.Name);
}
}
}
public void MoveFile(IFilePath ofp, IFilePath nfp)
{
using (HeavyProfiler.Log("AzureBlobStorage MoveFile"))
{
if (WeakFileReference)
return;
throw new NotImplementedException();
}
}
public void DeleteFiles(IEnumerable<IFilePath> files)
{
using (HeavyProfiler.Log("AzureBlobStorage DeleteFiles"))
{
if (WeakFileReference)
return;
foreach (var f in files)
{
GetClient(f).DeleteBlob(f.Suffix);
}
}
}
public void DeleteFilesIfExist(IEnumerable<IFilePath> files)
{
using (HeavyProfiler.Log("AzureBlobStorage DeleteFiles"))
{
if (WeakFileReference)
return;
foreach (var f in files)
{
GetClient(f).DeleteBlobIfExists(f.Suffix);
}
}
}
public readonly static Dictionary<string, string> ContentTypesDict = new Dictionary<string, string>()
{
{".x3d", "application/vnd.hzn-3d-crossword"},
{".3gp", "video/3gpp"},
{".3g2", "video/3gpp2"},
{".mseq", "application/vnd.mseq"},
{".pwn", "application/vnd.3m.post-it-notes"},
{".plb", "application/vnd.3gpp.pic-bw-large"},
{".psb", "application/vnd.3gpp.pic-bw-small"},
{".pvb", "application/vnd.3gpp.pic-bw-var"},
{".tcap", "application/vnd.3gpp2.tcap"},
{".7z", "application/x-7z-compressed"},
{".abw", "application/x-abiword"},
{".ace", "application/x-ace-compressed"},
{".acc", "application/vnd.americandynamics.acc"},
{".acu", "application/vnd.acucobol"},
{".atc", "application/vnd.acucorp"},
{".adp", "audio/adpcm"},
{".aab", "application/x-authorware-bin"},
{".aam", "application/x-authorware-map"},
{".aas", "application/x-authorware-seg"},
{".air", "application/vnd.adobe.air-application-installer-package+zip"},
{".swf", "application/x-shockwave-flash"},
{".fxp", "application/vnd.adobe.fxp"},
{".pdf", "application/pdf"},
{".ppd", "application/vnd.cups-ppd"},
{".dir", "application/x-director"},
{".xdp", "application/vnd.adobe.xdp+xml"},
{".xfdf", "application/vnd.adobe.xfdf"},
{".aac", "audio/x-aac"},
{".ahead", "application/vnd.ahead.space"},
{".azf", "application/vnd.airzip.filesecure.azf"},
{".azs", "application/vnd.airzip.filesecure.azs"},
{".azw", "application/vnd.amazon.ebook"},
{".ami", "application/vnd.amiga.ami"},
{".apk", "application/vnd.android.package-archive"},
{".cii", "application/vnd.anser-web-certificate-issue-initiation"},
{".fti", "application/vnd.anser-web-funds-transfer-initiation"},
{".atx", "application/vnd.antix.game-component"},
{".mpkg", "application/vnd.apple.installer+xml"},
{".aw", "application/applixware"},
{".les", "application/vnd.hhe.lesson-player"},
{".swi", "application/vnd.aristanetworks.swi"},
{".s", "text/x-asm"},
{".atomcat", "application/atomcat+xml"},
{".atomsvc", "application/atomsvc+xml"},
{".atom, .xml", "application/atom+xml"},
{".ac", "application/pkix-attr-cert"},
{".aif", "audio/x-aiff"},
{".avi", "video/x-msvideo"},
{".aep", "application/vnd.audiograph"},
{".dxf", "image/vnd.dxf"},
{".dwf", "model/vnd.dwf"},
{".par", "text/plain-bas"},
{".bcpio", "application/x-bcpio"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".torrent", "application/x-bittorrent"},
{".cod", "application/vnd.rim.cod"},
{".mpm", "application/vnd.blueice.multipass"},
{".bmi", "application/vnd.bmi"},
{".sh", "application/x-sh"},
{".btif", "image/prs.btif"},
{".rep", "application/vnd.businessobjects"},
{".bz", "application/x-bzip"},
{".bz2", "application/x-bzip2"},
{".csh", "application/x-csh"},
{".c", "text/x-c"},
{".cdxml", "application/vnd.chemdraw+xml"},
{".css", "text/css"},
{".cdx", "chemical/x-cdx"},
{".cml", "chemical/x-cml"},
{".csml", "chemical/x-csml"},
{".cdbcmsg", "application/vnd.contact.cmsg"},
{".cla", "application/vnd.claymore"},
{".c4g", "application/vnd.clonk.c4group"},
{".sub", "image/vnd.dvb.subtitle"},
{".cdmia", "application/cdmi-capability"},
{".cdmic", "application/cdmi-container"},
{".cdmid", "application/cdmi-domain"},
{".cdmio", "application/cdmi-object"},
{".cdmiq", "application/cdmi-queue"},
{".c11amc", "application/vnd.cluetrust.cartomobile-config"},
{".c11amz", "application/vnd.cluetrust.cartomobile-config-pkg"},
{".ras", "image/x-cmu-raster"},
{".dae", "model/vnd.collada+xml"},
{".csv", "text/csv"},
{".cpt", "application/mac-compactpro"},
{".wmlc", "application/vnd.wap.wmlc"},
{".cgm", "image/cgm"},
{".ice", "x-conference/x-cooltalk"},
{".cmx", "image/x-cmx"},
{".xar", "application/vnd.xara"},
{".cmc", "application/vnd.cosmocaller"},
{".cpio", "application/x-cpio"},
{".clkx", "application/vnd.crick.clicker"},
{".clkk", "application/vnd.crick.clicker.keyboard"},
{".clkp", "application/vnd.crick.clicker.palette"},
{".clkt", "application/vnd.crick.clicker.template"},
{".clkw", "application/vnd.crick.clicker.wordbank"},
{".wbs", "application/vnd.criticaltools.wbs+xml"},
{".cryptonote", "application/vnd.rig.cryptonote"},
{".cif", "chemical/x-cif"},
{".cmdf", "chemical/x-cmdf"},
{".cu", "application/cu-seeme"},
{".cww", "application/prs.cww"},
{".curl", "text/vnd.curl"},
{".dcurl", "text/vnd.curl.dcurl"},
{".mcurl", "text/vnd.curl.mcurl"},
{".scurl", "text/vnd.curl.scurl"},
{".car", "application/vnd.curl.car"},
{".pcurl", "application/vnd.curl.pcurl"},
{".cmp", "application/vnd.yellowriver-custom-menu"},
{".dssc", "application/dssc+der"},
{".xdssc", "application/dssc+xml"},
{".deb", "application/x-debian-package"},
{".uva", "audio/vnd.dece.audio"},
{".uvi", "image/vnd.dece.graphic"},
{".uvh", "video/vnd.dece.hd"},
{".uvm", "video/vnd.dece.mobile"},
{".uvu", "video/vnd.uvvu.mp4"},
{".uvp", "video/vnd.dece.pd"},
{".uvs", "video/vnd.dece.sd"},
{".uvv", "video/vnd.dece.video"},
{".dvi", "application/x-dvi"},
{".seed", "application/vnd.fdsn.seed"},
{".dtb", "application/x-dtbook+xml"},
{".res", "application/x-dtbresource+xml"},
{".ait", "application/vnd.dvb.ait"},
{".svc", "application/vnd.dvb.service"},
{".eol", "audio/vnd.digital-winds"},
{".djvu", "image/vnd.djvu"},
{".dtd", "application/xml-dtd"},
{".mlp", "application/vnd.dolby.mlp"},
{".wad", "application/x-doom"},
{".dpg", "application/vnd.dpgraph"},
{".dra", "audio/vnd.dra"},
{".dfac", "application/vnd.dreamfactory"},
{".dts", "audio/vnd.dts"},
{".dtshd", "audio/vnd.dts.hd"},
{".dwg", "image/vnd.dwg"},
{".geo", "application/vnd.dynageo"},
{".es", "application/ecmascript"},
{".mag", "application/vnd.ecowin.chart"},
{".mmr", "image/vnd.fujixerox.edmics-mmr"},
{".rlc", "image/vnd.fujixerox.edmics-rlc"},
{".exi", "application/exi"},
{".mgz", "application/vnd.proteus.magazine"},
{".epub", "application/epub+zip"},
{".eml", "message/rfc822"},
{".nml", "application/vnd.enliven"},
{".xpr", "application/vnd.is-xpr"},
{".xif", "image/vnd.xiff"},
{".xfdl", "application/vnd.xfdl"},
{".emma", "application/emma+xml"},
{".ez2", "application/vnd.ezpix-album"},
{".ez3", "application/vnd.ezpix-package"},
{".fst", "image/vnd.fst"},
{".fvt", "video/vnd.fvt"},
{".fbs", "image/vnd.fastbidsheet"},
{".fe_launch", "application/vnd.denovo.fcselayout-link"},
{".f4v", "video/x-f4v"},
{".flv", "video/x-flv"},
{".fpx", "image/vnd.fpx"},
{".npx", "image/vnd.net-fpx"},
{".flx", "text/vnd.fmi.flexstor"},
{".fli", "video/x-fli"},
{".ftc", "application/vnd.fluxtime.clip"},
{".fdf", "application/vnd.fdf"},
{".f", "text/x-fortran"},
{".mif", "application/vnd.mif"},
{".fm", "application/vnd.framemaker"},
{".fh", "image/x-freehand"},
{".fsc", "application/vnd.fsc.weblaunch"},
{".fnc", "application/vnd.frogans.fnc"},
{".ltf", "application/vnd.frogans.ltf"},
{".ddd", "application/vnd.fujixerox.ddd"},
{".xdw", "application/vnd.fujixerox.docuworks"},
{".xbd", "application/vnd.fujixerox.docuworks.binder"},
{".oas", "application/vnd.fujitsu.oasys"},
{".oa2", "application/vnd.fujitsu.oasys2"},
{".oa3", "application/vnd.fujitsu.oasys3"},
{".fg5", "application/vnd.fujitsu.oasysgp"},
{".bh2", "application/vnd.fujitsu.oasysprs"},
{".spl", "application/x-futuresplash"},
{".fzs", "application/vnd.fuzzysheet"},
{".g3", "image/g3fax"},
{".gmx", "application/vnd.gmx"},
{".gtw", "model/vnd.gtw"},
{".txd", "application/vnd.genomatix.tuxedo"},
{".ggb", "application/vnd.geogebra.file"},
{".ggt", "application/vnd.geogebra.tool"},
{".gdl", "model/vnd.gdl"},
{".gex", "application/vnd.geometry-explorer"},
{".gxt", "application/vnd.geonext"},
{".g2w", "application/vnd.geoplan"},
{".g3w", "application/vnd.geospace"},
{".gsf", "application/x-font-ghostscript"},
{".bdf", "application/x-font-bdf"},
{".gtar", "application/x-gtar"},
{".texinfo", "application/x-texinfo"},
{".gnumeric", "application/x-gnumeric"},
{".kml", "application/vnd.google-earth.kml+xml"},
{".kmz", "application/vnd.google-earth.kmz"},
{".gqf", "application/vnd.grafeq"},
{".gif", "image/gif"},
{".gv", "text/vnd.graphviz"},
{".gac", "application/vnd.groove-account"},
{".ghf", "application/vnd.groove-help"},
{".gim", "application/vnd.groove-identity-message"},
{".grv", "application/vnd.groove-injector"},
{".gtm", "application/vnd.groove-tool-message"},
{".tpl", "application/vnd.groove-tool-template"},
{".vcg", "application/vnd.groove-vcard"},
{".h261", "video/h261"},
{".h263", "video/h263"},
{".h264", "video/h264"},
{".hpid", "application/vnd.hp-hpid"},
{".hps", "application/vnd.hp-hps"},
{".hdf", "application/x-hdf"},
{".rip", "audio/vnd.rip"},
{".hbci", "application/vnd.hbci"},
{".jlt", "application/vnd.hp-jlyt"},
{".pcl", "application/vnd.hp-pcl"},
{".hpgl", "application/vnd.hp-hpgl"},
{".hvs", "application/vnd.yamaha.hv-script"},
{".hvd", "application/vnd.yamaha.hv-dic"},
{".hvp", "application/vnd.yamaha.hv-voice"},
{".sfd-hdstx", "application/vnd.hydrostatix.sof-data"},
{".stk", "application/hyperstudio"},
{".hal", "application/vnd.hal+xml"},
{".html", "text/html"},
{".irm", "application/vnd.ibm.rights-management"},
{".sc", "application/vnd.ibm.secure-container"},
{".ics", "text/calendar"},
{".icc", "application/vnd.iccprofile"},
{".ico", "image/x-icon"},
{".igl", "application/vnd.igloader"},
{".ief", "image/ief"},
{".ivp", "application/vnd.immervision-ivp"},
{".ivu", "application/vnd.immervision-ivu"},
{".rif", "application/reginfo+xml"},
{".3dml", "text/vnd.in3d.3dml"},
{".spot", "text/vnd.in3d.spot"},
{".igs", "model/iges"},
{".i2g", "application/vnd.intergeo"},
{".cdy", "application/vnd.cinderella"},
{".xpw", "application/vnd.intercon.formnet"},
{".fcs", "application/vnd.isac.fcs"},
{".ipfix", "application/ipfix"},
{".cer", "application/pkix-cert"},
{".pki", "application/pkixcmp"},
{".crl", "application/pkix-crl"},
{".pkipath", "application/pkix-pkipath"},
{".igm", "application/vnd.insors.igm"},
{".rcprofile", "application/vnd.ipunplugged.rcprofile"},
{".irp", "application/vnd.irepository.package+xml"},
{".jad", "text/vnd.sun.j2me.app-descriptor"},
{".jar", "application/java-archive"},
{".class", "application/java-vm"},
{".jnlp", "application/x-java-jnlp-file"},
{".ser", "application/java-serialized-object"},
{".java", "text/x-java-source,java"},
{".js", "application/javascript"},
{".json", "application/json"},
{".joda", "application/vnd.joost.joda-archive"},
{".jpm", "video/jpm"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg" },
{".jpgv", "video/jpeg"},
{".ktz", "application/vnd.kahootz"},
{".mmd", "application/vnd.chipnuts.karaoke-mmd"},
{".karbon", "application/vnd.kde.karbon"},
{".chrt", "application/vnd.kde.kchart"},
{".kfo", "application/vnd.kde.kformula"},
{".flw", "application/vnd.kde.kivio"},
{".kon", "application/vnd.kde.kontour"},
{".kpr", "application/vnd.kde.kpresenter"},
{".ksp", "application/vnd.kde.kspread"},
{".kwd", "application/vnd.kde.kword"},
{".htke", "application/vnd.kenameaapp"},
{".kia", "application/vnd.kidspiration"},
{".kne", "application/vnd.kinar"},
{".sse", "application/vnd.kodak-descriptor"},
{".lasxml", "application/vnd.las.las+xml"},
{".latex", "application/x-latex"},
{".lbd", "application/vnd.llamagraphics.life-balance.desktop"},
{".lbe", "application/vnd.llamagraphics.life-balance.exchange+xml"},
{".jam", "application/vnd.jam"},
{".123", "application/vnd.lotus-1-2-3"},
{".apr", "application/vnd.lotus-approach"},
{".pre", "application/vnd.lotus-freelance"},
{".nsf", "application/vnd.lotus-notes"},
{".org", "application/vnd.lotus-organizer"},
{".scm", "application/vnd.lotus-screencam"},
{".lwp", "application/vnd.lotus-wordpro"},
{".lvp", "audio/vnd.lucent.voice"},
{".m3u", "audio/x-mpegurl"},
{".m4v", "video/x-m4v"},
{".hqx", "application/mac-binhex40"},
{".portpkg", "application/vnd.macports.portpkg"},
{".mgp", "application/vnd.osgeo.mapguide.package"},
{".mrc", "application/marc"},
{".mrcx", "application/marcxml+xml"},
{".mxf", "application/mxf"},
{".nbp", "application/vnd.wolfram.player"},
{".ma", "application/mathematica"},
{".mathml", "application/mathml+xml"},
{".mbox", "application/mbox"},
{".mc1", "application/vnd.medcalcdata"},
{".mscml", "application/mediaservercontrol+xml"},
{".cdkey", "application/vnd.mediastation.cdkey"},
{".mwf", "application/vnd.mfer"},
{".mfm", "application/vnd.mfmp"},
{".msh", "model/mesh"},
{".mads", "application/mads+xml"},
{".mets", "application/mets+xml"},
{".mods", "application/mods+xml"},
{".meta4", "application/metalink4+xml"},
{".potm", "application/vnd.ms-powerpoint.template.macroenabled.12"},
{".docm", "application/vnd.ms-word.document.macroenabled.12"},
{".dotm", "application/vnd.ms-word.template.macroenabled.12"},
{".mcd", "application/vnd.mcd"},
{".flo", "application/vnd.micrografx.flo"},
{".igx", "application/vnd.micrografx.igx"},
{".es3", "application/vnd.eszigno3+xml"},
{".mdb", "application/x-msaccess"},
{".asf", "video/x-ms-asf"},
{".exe", "application/x-msdownload"},
{".cil", "application/vnd.ms-artgalry"},
{".cab", "application/vnd.ms-cab-compressed"},
{".ims", "application/vnd.ms-ims"},
{".application", "application/x-ms-application"},
{".clp", "application/x-msclip"},
{".mdi", "image/vnd.ms-modi"},
{".eot", "application/vnd.ms-fontobject"},
{".xls", "application/vnd.ms-excel"},
{".xlam", "application/vnd.ms-excel.addin.macroenabled.12"},
{".xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12"},
{".xltm", "application/vnd.ms-excel.template.macroenabled.12"},
{".xlsm", "application/vnd.ms-excel.sheet.macroenabled.12"},
{".chm", "application/vnd.ms-htmlhelp"},
{".crd", "application/x-mscardfile"},
{".lrm", "application/vnd.ms-lrm"},
{".mvb", "application/x-msmediaview"},
{".mny", "application/x-msmoney"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
{".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{".obd", "application/x-msbinder"},
{".thmx", "application/vnd.ms-officetheme"},
{".onetoc", "application/onenote"},
{".pya", "audio/vnd.ms-playready.media.pya"},
{".pyv", "video/vnd.ms-playready.media.pyv"},
{".ppt", "application/vnd.ms-powerpoint"},
{".ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12"},
{".sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12"},
{".pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12"},
{".ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12"},
{".mpp", "application/vnd.ms-project"},
{".pub", "application/x-mspublisher"},
{".scd", "application/x-msschedule"},
{".xap", "application/x-silverlight-app"},
{".stl", "application/vnd.ms-pki.stl"},
{".cat", "application/vnd.ms-pki.seccat"},
{".vsd", "application/vnd.visio"},
{".wm", "video/x-ms-wm"},
{".wma", "audio/x-ms-wma"},
{".wax", "audio/x-ms-wax"},
{".wmx", "video/x-ms-wmx"},
{".wmd", "application/x-ms-wmd"},
{".wpl", "application/vnd.ms-wpl"},
{".wmz", "application/x-ms-wmz"},
{".wmv", "video/x-ms-wmv"},
{".wvx", "video/x-ms-wvx"},
{".wmf", "application/x-msmetafile"},
{".trm", "application/x-msterminal"},
{".doc", "application/msword"},
{".wri", "application/x-mswrite"},
{".wps", "application/vnd.ms-works"},
{".xbap", "application/x-ms-xbap"},
{".xps", "application/vnd.ms-xpsdocument"},
{".mid", "audio/midi"},
{".mpy", "application/vnd.ibm.minipay"},
{".afp", "application/vnd.ibm.modcap"},
{".rms", "application/vnd.jcp.javame.midlet-rms"},
{".tmo", "application/vnd.tmobile-livetv"},
{".prc", "application/x-mobipocket-ebook"},
{".mbk", "application/vnd.mobius.mbk"},
{".dis", "application/vnd.mobius.dis"},
{".plc", "application/vnd.mobius.plc"},
{".mqy", "application/vnd.mobius.mqy"},
{".msl", "application/vnd.mobius.msl"},
{".txf", "application/vnd.mobius.txf"},
{".daf", "application/vnd.mobius.daf"},
{".fly", "text/vnd.fly"},
{".mpc", "application/vnd.mophun.certificate"},
{".mpn", "application/vnd.mophun.application"},
{".mj2", "video/mj2"},
{".mpga", "audio/mpeg"},
{".mxu", "video/vnd.mpegurl"},
{".mpeg", "video/mpeg"},
{".m21", "application/mp21"},
{".mp4a", "audio/mp4"},
{".mp4", "video/mp4"},
{".m3u8", "application/vnd.apple.mpegurl"},
{".mus", "application/vnd.musician"},
{".msty", "application/vnd.muvee.style"},
{".mxml", "application/xv+xml"},
{".ngdat", "application/vnd.nokia.n-gage.data"},
{".n-gage", "application/vnd.nokia.n-gage.symbian.install"},
{".ncx", "application/x-dtbncx+xml"},
{".nc", "application/x-netcdf"},
{".nlu", "application/vnd.neurolanguage.nlu"},
{".dna", "application/vnd.dna"},
{".nnd", "application/vnd.noblenet-directory"},
{".nns", "application/vnd.noblenet-sealer"},
{".nnw", "application/vnd.noblenet-web"},
{".rpst", "application/vnd.nokia.radio-preset"},
{".rpss", "application/vnd.nokia.radio-presets"},
{".n3", "text/n3"},
{".edm", "application/vnd.novadigm.edm"},
{".edx", "application/vnd.novadigm.edx"},
{".ext", "application/vnd.novadigm.ext"},
{".gph", "application/vnd.flographit"},
{".ecelp4800", "audio/vnd.nuera.ecelp4800"},
{".ecelp7470", "audio/vnd.nuera.ecelp7470"},
{".ecelp9600", "audio/vnd.nuera.ecelp9600"},
{".oda", "application/oda"},
{".ogx", "application/ogg"},
{".oga", "audio/ogg"},
{".ogv", "video/ogg"},
{".dd2", "application/vnd.oma.dd2+xml"},
{".oth", "application/vnd.oasis.opendocument.text-web"},
{".opf", "application/oebps-package+xml"},
{".qbo", "application/vnd.intu.qbo"},
{".oxt", "application/vnd.openofficeorg.extension"},
{".osf", "application/vnd.yamaha.openscoreformat"},
{".weba", "audio/webm"},
{".webm", "video/webm"},
{".odc", "application/vnd.oasis.opendocument.chart"},
{".otc", "application/vnd.oasis.opendocument.chart-template"},
{".odb", "application/vnd.oasis.opendocument.database"},
{".odf", "application/vnd.oasis.opendocument.formula"},
{".odft", "application/vnd.oasis.opendocument.formula-template"},
{".odg", "application/vnd.oasis.opendocument.graphics"},
{".otg", "application/vnd.oasis.opendocument.graphics-template"},
{".odi", "application/vnd.oasis.opendocument.image"},
{".oti", "application/vnd.oasis.opendocument.image-template"},
{".odp", "application/vnd.oasis.opendocument.presentation"},
{".otp", "application/vnd.oasis.opendocument.presentation-template"},
{".ods", "application/vnd.oasis.opendocument.spreadsheet"},
{".ots", "application/vnd.oasis.opendocument.spreadsheet-template"},
{".odt", "application/vnd.oasis.opendocument.text"},
{".odm", "application/vnd.oasis.opendocument.text-master"},
{".ott", "application/vnd.oasis.opendocument.text-template"},
{".ktx", "image/ktx"},
{".sxc", "application/vnd.sun.xml.calc"},
{".stc", "application/vnd.sun.xml.calc.template"},
{".sxd", "application/vnd.sun.xml.draw"},
{".std", "application/vnd.sun.xml.draw.template"},
{".sxi", "application/vnd.sun.xml.impress"},
{".sti", "application/vnd.sun.xml.impress.template"},
{".sxm", "application/vnd.sun.xml.math"},
{".sxw", "application/vnd.sun.xml.writer"},
{".sxg", "application/vnd.sun.xml.writer.global"},
{".stw", "application/vnd.sun.xml.writer.template"},
{".otf", "application/x-font-otf"},
{".osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml"},
{".dp", "application/vnd.osgi.dp"},
{".pdb", "application/vnd.palm"},
{".p", "text/x-pascal"},
{".paw", "application/vnd.pawaafile"},
{".pclxl", "application/vnd.hp-pclxl"},
{".efif", "application/vnd.picsel"},
{".pcx", "image/x-pcx"},
{".psd", "image/vnd.adobe.photoshop"},
{".prf", "application/pics-rules"},
{".pic", "image/x-pict"},
{".chat", "application/x-chat"},
{".p10", "application/pkcs10"},
{".p12", "application/x-pkcs12"},
{".p7m", "application/pkcs7-mime"},
{".p7s", "application/pkcs7-signature"},
{".p7r", "application/x-pkcs7-certreqresp"},
{".p7b", "application/x-pkcs7-certificates"},
{".p8", "application/pkcs8"},
{".plf", "application/vnd.pocketlearn"},
{".pnm", "image/x-portable-anymap"},
{".pbm", "image/x-portable-bitmap"},
{".pcf", "application/x-font-pcf"},
{".pfr", "application/font-tdpfr"},
{".pgn", "application/x-chess-pgn"},
{".pgm", "image/x-portable-graymap"},
{".png", "image/png"},
{".ppm", "image/x-portable-pixmap"},
{".pskcxml", "application/pskc+xml"},
{".pml", "application/vnd.ctc-posml"},
{".ai", "application/postscript"},
{".pfa", "application/x-font-type1"},
{".pbd", "application/vnd.powerbuilder6"},
{".pgp", "application/pgp-signature"},
{".box", "application/vnd.previewsystems.box"},
{".ptid", "application/vnd.pvi.ptid1"},
{".pls", "application/pls+xml"},
{".str", "application/vnd.pg.format"},
{".ei6", "application/vnd.pg.osasli"},
{".dsc", "text/prs.lines.tag"},
{".psf", "application/x-font-linux-psf"},
{".qps", "application/vnd.publishare-delta-tree"},
{".wg", "application/vnd.pmi.widget"},
{".qxd", "application/vnd.quark.quarkxpress"},
{".esf", "application/vnd.epson.esf"},
{".msf", "application/vnd.epson.msf"},
{".ssf", "application/vnd.epson.ssf"},
{".qam", "application/vnd.epson.quickanime"},
{".qfx", "application/vnd.intu.qfx"},
{".qt", "video/quicktime"},
{".rar", "application/x-rar-compressed"},
{".ram", "audio/x-pn-realaudio"},
{".rmp", "audio/x-pn-realaudio-plugin"},
{".rsd", "application/rsd+xml"},
{".rm", "application/vnd.rn-realmedia"},
{".bed", "application/vnd.realvnc.bed"},
{".mxl", "application/vnd.recordare.musicxml"},
{".musicxml", "application/vnd.recordare.musicxml+xml"},
{".rnc", "application/relax-ng-compact-syntax"},
{".rdz", "application/vnd.data-vision.rdz"},
{".rdf", "application/rdf+xml"},
{".rp9", "application/vnd.cloanto.rp9"},
{".jisp", "application/vnd.jisp"},
{".rtf", "application/rtf"},
{".rtx", "text/richtext"},
{".link66", "application/vnd.route66.link66+xml"},
{".rss, .xml", "application/rss+xml"},
{".shf", "application/shf+xml"},
{".st", "application/vnd.sailingtracker.track"},
{".svg", "image/svg+xml"},
{".sus", "application/vnd.sus-calendar"},
{".sru", "application/sru+xml"},
{".setpay", "application/set-payment-initiation"},
{".setreg", "application/set-registration-initiation"},
{".sema", "application/vnd.sema"},
{".semd", "application/vnd.semd"},
{".semf", "application/vnd.semf"},
{".see", "application/vnd.seemail"},
{".snf", "application/x-font-snf"},
{".spq", "application/scvp-vp-request"},
{".spp", "application/scvp-vp-response"},
{".scq", "application/scvp-cv-request"},
{".scs", "application/scvp-cv-response"},
{".sdp", "application/sdp"},
{".etx", "text/x-setext"},
{".movie", "video/x-sgi-movie"},
{".ifm", "application/vnd.shana.informed.formdata"},
{".itp", "application/vnd.shana.informed.formtemplate"},
{".iif", "application/vnd.shana.informed.interchange"},
{".ipk", "application/vnd.shana.informed.package"},
{".tfi", "application/thraud+xml"},
{".shar", "application/x-shar"},
{".rgb", "image/x-rgb"},
{".slt", "application/vnd.epson.salt"},
{".aso", "application/vnd.accpac.simply.aso"},
{".imp", "application/vnd.accpac.simply.imp"},
{".twd", "application/vnd.simtech-mindmapper"},
{".csp", "application/vnd.commonspace"},
{".saf", "application/vnd.yamaha.smaf-audio"},
{".mmf", "application/vnd.smaf"},
{".spf", "application/vnd.yamaha.smaf-phrase"},
{".teacher", "application/vnd.smart.teacher"},
{".svd", "application/vnd.svd"},
{".rq", "application/sparql-query"},
{".srx", "application/sparql-results+xml"},
{".gram", "application/srgs"},
{".grxml", "application/srgs+xml"},
{".ssml", "application/ssml+xml"},
{".skp", "application/vnd.koan"},
{".sgml", "text/sgml"},
{".sdc", "application/vnd.stardivision.calc"},
{".sda", "application/vnd.stardivision.draw"},
{".sdd", "application/vnd.stardivision.impress"},
{".smf", "application/vnd.stardivision.math"},
{".sdw", "application/vnd.stardivision.writer"},
{".sgl", "application/vnd.stardivision.writer-global"},
{".sm", "application/vnd.stepmania.stepchart"},
{".sit", "application/x-stuffit"},
{".sitx", "application/x-stuffitx"},
{".sdkm", "application/vnd.solent.sdkm+xml"},
{".xo", "application/vnd.olpc-sugar"},
{".au", "audio/basic"},
{".wqd", "application/vnd.wqd"},
{".sis", "application/vnd.symbian.install"},
{".smi", "application/smil+xml"},
{".xsm", "application/vnd.syncml+xml"},
{".bdm", "application/vnd.syncml.dm+wbxml"},
{".xdm", "application/vnd.syncml.dm+xml"},
{".sv4cpio", "application/x-sv4cpio"},
{".sv4crc", "application/x-sv4crc"},
{".sbml", "application/sbml+xml"},
{".tsv", "text/tab-separated-values"},
{".tiff", "image/tiff"},
{".tao", "application/vnd.tao.intent-module-archive"},
{".tar", "application/x-tar"},
{".tcl", "application/x-tcl"},
{".tex", "application/x-tex"},
{".tfm", "application/x-tex-tfm"},
{".tei", "application/tei+xml"},
{".txt", "text/plain"},
{".dxp", "application/vnd.spotfire.dxp"},
{".sfs", "application/vnd.spotfire.sfs"},
{".tsd", "application/timestamped-data"},
{".tpt", "application/vnd.trid.tpt"},
{".mxs", "application/vnd.triscape.mxs"},
{".t", "text/troff"},
{".tra", "application/vnd.trueapp"},
{".ttf", "application/x-font-ttf"},
{".ttl", "text/turtle"},
{".umj", "application/vnd.umajin"},
{".uoml", "application/vnd.uoml+xml"},
{".unityweb", "application/vnd.unity"},
{".ufd", "application/vnd.ufdl"},
{".uri", "text/uri-list"},
{".utz", "application/vnd.uiq.theme"},
{".ustar", "application/x-ustar"},
{".uu", "text/x-uuencode"},
{".vcs", "text/x-vcalendar"},
{".vcf", "text/x-vcard"},
{".vcd", "application/x-cdlink"},
{".vsf", "application/vnd.vsf"},
{".wrl", "model/vrml"},
{".vcx", "application/vnd.vcx"},
{".mts", "model/vnd.mts"},
{".vtu", "model/vnd.vtu"},
{".vis", "application/vnd.visionary"},
{".viv", "video/vnd.vivo"},
{".ccxml", "application/ccxml+xml,"},
{".vxml", "application/voicexml+xml"},
{".src", "application/x-wais-source"},
{".wbxml", "application/vnd.wap.wbxml"},
{".wbmp", "image/vnd.wap.wbmp"},
{".wav", "audio/x-wav"},
{".davmount", "application/davmount+xml"},
{".woff", "application/x-font-woff"},
{".woff2", "application/x-font-woff"},
{".wspolicy", "application/wspolicy+xml"},
{".webp", "image/webp"},
{".wtb", "application/vnd.webturbo"},
{".wgt", "application/widget"},
{".hlp", "application/winhlp"},
{".wml", "text/vnd.wap.wml"},
{".wmls", "text/vnd.wap.wmlscript"},
{".wmlsc", "application/vnd.wap.wmlscriptc"},
{".wpd", "application/vnd.wordperfect"},
{".stf", "application/vnd.wt.stf"},
{".wsdl", "application/wsdl+xml"},
{".xbm", "image/x-xbitmap"},
{".xpm", "image/x-xpixmap"},
{".xwd", "image/x-xwindowdump"},
{".der", "application/x-x509-ca-cert"},
{".fig", "application/x-xfig"},
{".xhtml", "application/xhtml+xml"},
{".xml", "application/xml"},
{".xdf", "application/xcap-diff+xml"},
{".xenc", "application/xenc+xml"},
{".xer", "application/patch-ops-error+xml"},
{".rl", "application/resource-lists+xml"},
{".rs", "application/rls-services+xml"},
{".rld", "application/resource-lists-diff+xml"},
{".xslt", "application/xslt+xml"},
{".xop", "application/xop+xml"},
{".xpi", "application/x-xpinstall"},
{".xspf", "application/xspf+xml"},
{".xul", "application/vnd.mozilla.xul+xml"},
{".xyz", "chemical/x-xyz"},
{".yaml", "text/yaml"},
{".yang", "application/yang"},
{".yin", "application/yin+xml"},
{".zir", "application/vnd.zul"},
{".zip", "application/zip"},
{".zmm", "application/vnd.handheld-entertainment+xml"},
{".zaz", "application/vnd.zzazz.deck+xml"}
};
}
public static class BlobExtensions
{
public static bool ExistsBlob(this BlobContainerClient client, string blobName)
{
return client.GetBlobs(prefix: blobName.BeforeLast("/") ?? "").Any(b => b.Name == blobName);
}
}
}
| |
//
// ListView.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin 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 Xwt.Backends;
using System.ComponentModel;
namespace Xwt
{
[BackendType (typeof(IListViewBackend))]
public class ListView: Widget, IColumnContainer, IScrollableWidget
{
ListViewColumnCollection columns;
IListDataSource dataSource;
SelectionMode mode;
protected new class WidgetBackendHost: Widget.WidgetBackendHost<ListView,IListViewBackend>, IListViewEventSink
{
protected override void OnBackendCreated ()
{
base.OnBackendCreated ();
Parent.columns.Attach (Backend);
}
public void OnSelectionChanged ()
{
Parent.OnSelectionChanged (EventArgs.Empty);
}
public void OnRowActivated (int rowIndex)
{
Parent.OnRowActivated (new ListViewRowEventArgs (rowIndex));
}
public override Size GetDefaultNaturalSize ()
{
return Xwt.Backends.DefaultNaturalSizes.ListView;
}
}
static ListView ()
{
MapEvent (TableViewEvent.SelectionChanged, typeof(ListView), "OnSelectionChanged");
MapEvent (ListViewEvent.RowActivated, typeof(ListView), "OnRowActivated");
}
public ListView (IListDataSource source): this ()
{
VerifyConstructorCall (this);
DataSource = source;
}
public ListView ()
{
columns = new ListViewColumnCollection (this);
VerticalScrollPolicy = HorizontalScrollPolicy = ScrollPolicy.Automatic;
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
IListViewBackend Backend {
get { return (IListViewBackend) BackendHost.Backend; }
}
public bool BorderVisible
{
get { return Backend.BorderVisible; }
set { Backend.BorderVisible = value; }
}
public GridLines GridLinesVisible
{
get { return Backend.GridLinesVisible; }
set { Backend.GridLinesVisible = value; }
}
public ScrollPolicy VerticalScrollPolicy {
get { return Backend.VerticalScrollPolicy; }
set { Backend.VerticalScrollPolicy = value; }
}
public ScrollPolicy HorizontalScrollPolicy {
get { return Backend.HorizontalScrollPolicy; }
set { Backend.HorizontalScrollPolicy = value; }
}
ScrollControl verticalScrollAdjustment;
public ScrollControl VerticalScrollControl {
get {
if (verticalScrollAdjustment == null)
verticalScrollAdjustment = new ScrollControl (Backend.CreateVerticalScrollControl ());
return verticalScrollAdjustment;
}
}
ScrollControl horizontalScrollAdjustment;
public ScrollControl HorizontalScrollControl {
get {
if (horizontalScrollAdjustment == null)
horizontalScrollAdjustment = new ScrollControl (Backend.CreateHorizontalScrollControl ());
return horizontalScrollAdjustment;
}
}
public ListViewColumnCollection Columns {
get {
return columns;
}
}
public IListDataSource DataSource {
get {
return dataSource;
}
set {
if (dataSource != value) {
Backend.SetSource (value, value is IFrontend ? (IBackend)BackendHost.ToolkitEngine.GetSafeBackend (value) : null);
dataSource = value;
}
}
}
public bool HeadersVisible {
get {
return Backend.HeadersVisible;
}
set {
Backend.HeadersVisible = value;
}
}
public SelectionMode SelectionMode {
get {
return mode;
}
set {
mode = value;
Backend.SetSelectionMode (mode);
}
}
/// <summary>
/// Gets or sets the row the current event applies to.
/// The behavior of this property is undefined when used outside an
/// event that supports it.
/// </summary>
/// <value>
/// The current event row.
/// </value>
public int CurrentEventRow {
get {
return Backend.CurrentEventRow;
}
}
public int SelectedRow {
get {
var items = SelectedRows;
if (items.Length == 0)
return -1;
else
return items [0];
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public int[] SelectedRows {
get {
return Backend.SelectedRows;
}
}
/// <summary>
/// Gets or sets the focused row.
/// </summary>
/// <value>The row with the keyboard focus.</value>
public int FocusedRow {
get {
return Backend.FocusedRow;
}
set {
Backend.FocusedRow = value;
}
}
public void SelectRow (int row)
{
Backend.SelectRow (row);
}
public void UnselectRow (int row)
{
Backend.UnselectRow (row);
}
public void SelectAll ()
{
Backend.SelectAll ();
}
public void UnselectAll ()
{
Backend.UnselectAll ();
}
public void ScrollToRow (int row)
{
Backend.ScrollToRow (row);
}
/// <summary>
/// Returns the row at the given widget coordinates
/// </summary>
/// <returns>The row index</returns>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
public int GetRowAtPosition (double x, double y)
{
return GetRowAtPosition (new Point (x, y));
}
/// <summary>
/// Returns the row at the given widget coordinates
/// </summary>
/// <returns>The row index</returns>
/// <param name="p">A position, in widget coordinates</param>
public int GetRowAtPosition (Point p)
{
return Backend.GetRowAtPosition (p);
}
/// <summary>
/// Gets the bounds of a cell inside the given row.
/// </summary>
/// <returns>The cell bounds inside the widget, relative to the widget bounds.</returns>
/// <param name="row">The row index.</param>
/// <param name="cell">The cell view.</param>
/// <param name="includeMargin">If set to <c>true</c> include margin (the background of the row).</param>
public Rectangle GetCellBounds (int row, CellView cell, bool includeMargin)
{
return Backend.GetCellBounds (row, cell, includeMargin);
}
/// <summary>
/// Gets the bounds of the given row.
/// </summary>
/// <returns>The row bounds inside the widget, relative to the widget bounds.</returns>
/// <param name="row">The row index.</param>
/// <param name="includeMargin">If set to <c>true</c> include margin (the background of the row).</param>
public Rectangle GetRowBounds (int row, bool includeMargin)
{
return Backend.GetRowBounds (row, includeMargin);
}
void IColumnContainer.NotifyColumnsChanged ()
{
}
protected virtual void OnSelectionChanged (EventArgs a)
{
if (selectionChanged != null)
selectionChanged (this, a);
}
EventHandler selectionChanged;
public event EventHandler SelectionChanged {
add {
BackendHost.OnBeforeEventAdd (TableViewEvent.SelectionChanged, selectionChanged);
selectionChanged += value;
}
remove {
selectionChanged -= value;
BackendHost.OnAfterEventRemove (TableViewEvent.SelectionChanged, selectionChanged);
}
}
/// <summary>
/// Raises the row activated event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowActivated (ListViewRowEventArgs a)
{
if (rowActivated != null)
rowActivated (this, a);
}
EventHandler<ListViewRowEventArgs> rowActivated;
/// <summary>
/// Occurs when the user double-clicks on a row
/// </summary>
public event EventHandler<ListViewRowEventArgs> RowActivated {
add {
BackendHost.OnBeforeEventAdd (ListViewEvent.RowActivated, rowActivated);
rowActivated += value;
}
remove {
rowActivated -= value;
BackendHost.OnAfterEventRemove (ListViewEvent.RowActivated, rowActivated);
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using fyiReporting.RDL;
namespace fyiReporting.RDL
{
/// <summary>
/// Base class for all aggregate functions
/// </summary>
[Serializable]
internal abstract class FunctionAggr
{
public IExpr _Expr; // aggregate expression
public object _Scope; // DataSet or Grouping or DataRegion that contains (directly or
// indirectly) the report item that the aggregate
// function is used in
// Can also hold the Matrix object
bool _LevelCheck; // row processing requires level check
// i.e. simple specified on recursive row check
/// <summary>
/// Base class of all aggregate functions
/// </summary>
public FunctionAggr(IExpr e, object scp)
{
_Expr = e;
_Scope = scp;
_LevelCheck = false;
}
public bool IsConstant()
{
return false;
}
public IExpr ConstantOptimization()
{
if (_Expr != null)
_Expr = _Expr.ConstantOptimization();
return (IExpr) this;
}
public bool EvaluateBoolean(Report rpt, Row row)
{
return false;
}
public IExpr Expr
{
get { return _Expr; }
}
public object Scope
{
get { return _Scope; }
}
public bool LevelCheck
{
get { return _LevelCheck; }
set { _LevelCheck = value; }
}
// return an IEnumerable that represents the scope of the data
protected RowEnumerable GetDataScope(Report rpt, Row row, out bool bSave)
{
bSave=true;
RowEnumerable re=null;
if (this._Scope != null)
{
Type t = this._Scope.GetType();
//150208AJM GJL Trying - And Succeeding!!! to get data from chart
if (t == typeof(Chart)) {
Chart c = (Chart)this._Scope;
this._Scope = c.ChartMatrix;
t = this._Scope.GetType();
}
if (t == typeof(Grouping))
{
bSave=false;
Grouping g = (Grouping) (this._Scope);
if (g.InMatrix)
{
Rows rows = g.GetRows(rpt);
if (rows == null)
return null;
re = new RowEnumerable(0, rows.Data.Count-1, rows.Data, _LevelCheck);
}
else
{
if (row == null || row.R.CurrentGroups == null) // currentGroups can be null when reference Textbox in header/footer that has a scoped aggr function reference (TODO: this is a problem!)
return null;
GroupEntry ge = row.R.CurrentGroups[g.GetIndex(rpt)];
re = new RowEnumerable (ge.StartRow, ge.EndRow, row.R.Data, _LevelCheck);
}
}
else if (t == typeof(Matrix))
{
bSave=false;
Matrix m = (Matrix) (this._Scope);
Rows mData = m.GetMyData(rpt);
re = new RowEnumerable(0, mData.Data.Count-1, mData.Data, false);
}
else if (t == typeof(string))
{ // happens on page header/footer scope
if (row != null)
re = new RowEnumerable (0, row.R.Data.Count-1, row.R.Data, false);
bSave = false;
}
else if (t == typeof(DataSetDefn))
{
DataSetDefn ds = this._Scope as DataSetDefn;
if (ds != null && ds.Query != null)
{
Rows rows = ds.Query.GetMyData(rpt);
if (rows != null)
re = new RowEnumerable(0, rows.Data.Count - 1, rows.Data, false);
}
}
else if (row != null)
{
re = new RowEnumerable (0, row.R.Data.Count-1, row.R.Data, false);
}
else
{
DataSetDefn ds = this._Scope as DataSetDefn;
if (ds != null && ds.Query != null)
{
Rows rows = ds.Query.GetMyData(rpt);
if (rows != null)
re = new RowEnumerable(0, rows.Data.Count-1, rows.Data, false);
}
}
}
else if (row != null)
{
re = new RowEnumerable (0, row.R.Data.Count-1, row.R.Data, false);
}
return re;
}
}
internal class RowEnumerable : IEnumerable
{
int startRow;
int endRow;
List<Row> data;
bool _LevelCheck;
public RowEnumerable(int start, int end, List<Row> d, bool levelCheck)
{
startRow = start;
endRow = end;
data = d;
_LevelCheck = levelCheck;
}
public List<Row> Data
{
get{return data;}
}
public int FirstRow
{
get{return startRow;}
}
public int LastRow
{
get{return endRow;}
}
public bool LevelCheck
{
get{return _LevelCheck;}
}
// Methods
public IEnumerator GetEnumerator()
{
return new RowEnumerator(this);
}
}
internal class RowEnumerator : IEnumerator
{
private RowEnumerable re;
private int index = -1;
public RowEnumerator(RowEnumerable rea)
{
re = rea;
}
//Methods
public bool MoveNext()
{
index++;
while (true)
{
if (index + re.FirstRow > re.LastRow)
return false;
else
{
if (re.LevelCheck)
{ //
Row r1 = re.Data[re.FirstRow] as Row;
Row r2 = re.Data[index + re.FirstRow] as Row;
if (r1.Level == r1.Level)
return true;
index++;
}
else
return true;
}
}
}
public void Reset()
{
index=-1;
}
public object Current
{
get{return(re.Data[index + re.FirstRow]);}
}
}
}
| |
/*
* 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.
*/
/* Revised Aug, Sept 2009 by Kitto Flora. ODEDynamics.cs replaces
* ODEVehicleSettings.cs. It and ODEPrim.cs are re-organised:
* ODEPrim.cs contains methods dealing with Prim editing, Prim
* characteristics and Kinetic motion.
* ODEDynamics.cs contains methods dealing with Prim Physical motion
* (dynamics) and the associated settings. Old Linear and angular
* motors for dynamic motion have been replace with MoveLinear()
* and MoveAngular(); 'Physical' is used only to switch ODE dynamic
* simualtion on/off; VEHICAL_TYPE_NONE/VEHICAL_TYPE_<other> is to
* switch between 'VEHICLE' parameter use and general dynamics
* settings use.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModules.SharedBase;
namespace OpenSim.Region.PhysicsModule.ODE
{
public class ODEDynamics
{
public Vehicle Type
{
get { return m_type; }
}
public IntPtr Body
{
get { return m_body; }
}
private int frcount = 0; // Used to limit dynamics debug output to
// every 100th frame
// private OdeScene m_parentScene = null;
private IntPtr m_body = IntPtr.Zero;
// private IntPtr m_jointGroup = IntPtr.Zero;
// private IntPtr m_aMotor = IntPtr.Zero;
// Vehicle properties
private Vehicle m_type = Vehicle.TYPE_NONE; // If a 'VEHICLE', and what kind
// private Quaternion m_referenceFrame = Quaternion.Identity; // Axis modifier
private VehicleFlag m_flags = (VehicleFlag) 0; // Boolean settings:
// HOVER_TERRAIN_ONLY
// HOVER_GLOBAL_HEIGHT
// NO_DEFLECTION_UP
// HOVER_WATER_ONLY
// HOVER_UP_ONLY
// LIMIT_MOTOR_UP
// LIMIT_ROLL_ONLY
private VehicleFlag m_Hoverflags = (VehicleFlag)0;
private Vector3 m_BlockingEndPoint = Vector3.Zero;
private Quaternion m_RollreferenceFrame = Quaternion.Identity;
// Linear properties
private Vector3 m_linearMotorDirection = Vector3.Zero; // velocity requested by LSL, decayed by time
private Vector3 m_linearMotorDirectionLASTSET = Vector3.Zero; // velocity requested by LSL
private Vector3 m_dir = Vector3.Zero; // velocity applied to body
private Vector3 m_linearFrictionTimescale = Vector3.Zero;
private float m_linearMotorDecayTimescale = 0;
private float m_linearMotorTimescale = 0;
private Vector3 m_lastLinearVelocityVector = Vector3.Zero;
private SafeNativeMethods.Vector3 m_lastPositionVector = new SafeNativeMethods.Vector3();
// private bool m_LinearMotorSetLastFrame = false;
// private Vector3 m_linearMotorOffset = Vector3.Zero;
//Angular properties
private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor
private int m_angularMotorApply = 0; // application frame counter
private Vector3 m_angularMotorVelocity = Vector3.Zero; // current angular motor velocity
private float m_angularMotorTimescale = 0; // motor angular velocity ramp up rate
private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate
private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate
private Vector3 m_lastAngularVelocity = Vector3.Zero; // what was last applied to body
// private Vector3 m_lastVertAttractor = Vector3.Zero; // what VA was last applied to body
//Deflection properties
// private float m_angularDeflectionEfficiency = 0;
// private float m_angularDeflectionTimescale = 0;
// private float m_linearDeflectionEfficiency = 0;
// private float m_linearDeflectionTimescale = 0;
//Banking properties
// private float m_bankingEfficiency = 0;
// private float m_bankingMix = 0;
// private float m_bankingTimescale = 0;
//Hover and Buoyancy properties
private float m_VhoverHeight = 0f;
// private float m_VhoverEfficiency = 0f;
private float m_VhoverTimescale = 0f;
private float m_VhoverTargetHeight = -1.0f; // if <0 then no hover, else its the current target height
private float m_VehicleBuoyancy = 0f; //KF: m_VehicleBuoyancy is set by VEHICLE_BUOYANCY for a vehicle.
// Modifies gravity. Slider between -1 (double-gravity) and 1 (full anti-gravity)
// KF: So far I have found no good method to combine a script-requested .Z velocity and gravity.
// Therefore only m_VehicleBuoyancy=1 (0g) will use the script-requested .Z velocity.
//Attractor properties
private float m_verticalAttractionEfficiency = 1.0f; // damped
private float m_verticalAttractionTimescale = 500f; // Timescale > 300 means no vert attractor.
internal void ProcessFloatVehicleParam(Vehicle pParam, float pValue)
{
switch (pParam)
{
case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY:
if (pValue < 0.01f) pValue = 0.01f;
// m_angularDeflectionEfficiency = pValue;
break;
case Vehicle.ANGULAR_DEFLECTION_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
// m_angularDeflectionTimescale = pValue;
break;
case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_angularMotorDecayTimescale = pValue;
break;
case Vehicle.ANGULAR_MOTOR_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_angularMotorTimescale = pValue;
break;
case Vehicle.BANKING_EFFICIENCY:
if (pValue < 0.01f) pValue = 0.01f;
// m_bankingEfficiency = pValue;
break;
case Vehicle.BANKING_MIX:
if (pValue < 0.01f) pValue = 0.01f;
// m_bankingMix = pValue;
break;
case Vehicle.BANKING_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
// m_bankingTimescale = pValue;
break;
case Vehicle.BUOYANCY:
if (pValue < -1f) pValue = -1f;
if (pValue > 1f) pValue = 1f;
m_VehicleBuoyancy = pValue;
break;
// case Vehicle.HOVER_EFFICIENCY:
// if (pValue < 0f) pValue = 0f;
// if (pValue > 1f) pValue = 1f;
// m_VhoverEfficiency = pValue;
// break;
case Vehicle.HOVER_HEIGHT:
m_VhoverHeight = pValue;
break;
case Vehicle.HOVER_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_VhoverTimescale = pValue;
break;
case Vehicle.LINEAR_DEFLECTION_EFFICIENCY:
if (pValue < 0.01f) pValue = 0.01f;
// m_linearDeflectionEfficiency = pValue;
break;
case Vehicle.LINEAR_DEFLECTION_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
// m_linearDeflectionTimescale = pValue;
break;
case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_linearMotorDecayTimescale = pValue;
break;
case Vehicle.LINEAR_MOTOR_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_linearMotorTimescale = pValue;
break;
case Vehicle.VERTICAL_ATTRACTION_EFFICIENCY:
if (pValue < 0.1f) pValue = 0.1f; // Less goes unstable
if (pValue > 1.0f) pValue = 1.0f;
m_verticalAttractionEfficiency = pValue;
break;
case Vehicle.VERTICAL_ATTRACTION_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_verticalAttractionTimescale = pValue;
break;
// These are vector properties but the engine lets you use a single float value to
// set all of the components to the same value
case Vehicle.ANGULAR_FRICTION_TIMESCALE:
m_angularFrictionTimescale = new Vector3(pValue, pValue, pValue);
break;
case Vehicle.ANGULAR_MOTOR_DIRECTION:
m_angularMotorDirection = new Vector3(pValue, pValue, pValue);
m_angularMotorApply = 10;
break;
case Vehicle.LINEAR_FRICTION_TIMESCALE:
m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue);
break;
case Vehicle.LINEAR_MOTOR_DIRECTION:
m_linearMotorDirection = new Vector3(pValue, pValue, pValue);
m_linearMotorDirectionLASTSET = new Vector3(pValue, pValue, pValue);
break;
case Vehicle.LINEAR_MOTOR_OFFSET:
// m_linearMotorOffset = new Vector3(pValue, pValue, pValue);
break;
}
}//end ProcessFloatVehicleParam
internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue)
{
switch (pParam)
{
case Vehicle.ANGULAR_FRICTION_TIMESCALE:
m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.ANGULAR_MOTOR_DIRECTION:
m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
// Limit requested angular speed to 2 rps= 4 pi rads/sec
if (m_angularMotorDirection.X > 12.56f) m_angularMotorDirection.X = 12.56f;
if (m_angularMotorDirection.X < - 12.56f) m_angularMotorDirection.X = - 12.56f;
if (m_angularMotorDirection.Y > 12.56f) m_angularMotorDirection.Y = 12.56f;
if (m_angularMotorDirection.Y < - 12.56f) m_angularMotorDirection.Y = - 12.56f;
if (m_angularMotorDirection.Z > 12.56f) m_angularMotorDirection.Z = 12.56f;
if (m_angularMotorDirection.Z < - 12.56f) m_angularMotorDirection.Z = - 12.56f;
m_angularMotorApply = 10;
break;
case Vehicle.LINEAR_FRICTION_TIMESCALE:
m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.LINEAR_MOTOR_DIRECTION:
m_linearMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
m_linearMotorDirectionLASTSET = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.LINEAR_MOTOR_OFFSET:
// m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.BLOCK_EXIT:
m_BlockingEndPoint = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
}
}//end ProcessVectorVehicleParam
internal void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue)
{
switch (pParam)
{
case Vehicle.REFERENCE_FRAME:
// m_referenceFrame = pValue;
break;
case Vehicle.ROLL_FRAME:
m_RollreferenceFrame = pValue;
break;
}
}//end ProcessRotationVehicleParam
internal void ProcessVehicleFlags(int pParam, bool remove)
{
if (remove)
{
if (pParam == -1)
{
m_flags = (VehicleFlag)0;
m_Hoverflags = (VehicleFlag)0;
return;
}
if ((pParam & (int)VehicleFlag.HOVER_GLOBAL_HEIGHT) == (int)VehicleFlag.HOVER_GLOBAL_HEIGHT)
{
if ((m_Hoverflags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != (VehicleFlag)0)
m_Hoverflags &= ~(VehicleFlag.HOVER_GLOBAL_HEIGHT);
}
if ((pParam & (int)VehicleFlag.HOVER_TERRAIN_ONLY) == (int)VehicleFlag.HOVER_TERRAIN_ONLY)
{
if ((m_Hoverflags & VehicleFlag.HOVER_TERRAIN_ONLY) != (VehicleFlag)0)
m_Hoverflags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY);
}
if ((pParam & (int)VehicleFlag.HOVER_UP_ONLY) == (int)VehicleFlag.HOVER_UP_ONLY)
{
if ((m_Hoverflags & VehicleFlag.HOVER_UP_ONLY) != (VehicleFlag)0)
m_Hoverflags &= ~(VehicleFlag.HOVER_UP_ONLY);
}
if ((pParam & (int)VehicleFlag.HOVER_WATER_ONLY) == (int)VehicleFlag.HOVER_WATER_ONLY)
{
if ((m_Hoverflags & VehicleFlag.HOVER_WATER_ONLY) != (VehicleFlag)0)
m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY);
}
if ((pParam & (int)VehicleFlag.LIMIT_MOTOR_UP) == (int)VehicleFlag.LIMIT_MOTOR_UP)
{
if ((m_flags & VehicleFlag.LIMIT_MOTOR_UP) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.LIMIT_MOTOR_UP);
}
if ((pParam & (int)VehicleFlag.LIMIT_ROLL_ONLY) == (int)VehicleFlag.LIMIT_ROLL_ONLY)
{
if ((m_flags & VehicleFlag.LIMIT_ROLL_ONLY) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.LIMIT_ROLL_ONLY);
}
if ((pParam & (int)VehicleFlag.MOUSELOOK_BANK) == (int)VehicleFlag.MOUSELOOK_BANK)
{
if ((m_flags & VehicleFlag.MOUSELOOK_BANK) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.MOUSELOOK_BANK);
}
if ((pParam & (int)VehicleFlag.MOUSELOOK_STEER) == (int)VehicleFlag.MOUSELOOK_STEER)
{
if ((m_flags & VehicleFlag.MOUSELOOK_STEER) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.MOUSELOOK_STEER);
}
if ((pParam & (int)VehicleFlag.NO_DEFLECTION_UP) == (int)VehicleFlag.NO_DEFLECTION_UP)
{
if ((m_flags & VehicleFlag.NO_DEFLECTION_UP) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP);
}
if ((pParam & (int)VehicleFlag.CAMERA_DECOUPLED) == (int)VehicleFlag.CAMERA_DECOUPLED)
{
if ((m_flags & VehicleFlag.CAMERA_DECOUPLED) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.CAMERA_DECOUPLED);
}
if ((pParam & (int)VehicleFlag.NO_X) == (int)VehicleFlag.NO_X)
{
if ((m_flags & VehicleFlag.NO_X) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.NO_X);
}
if ((pParam & (int)VehicleFlag.NO_Y) == (int)VehicleFlag.NO_Y)
{
if ((m_flags & VehicleFlag.NO_Y) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.NO_Y);
}
if ((pParam & (int)VehicleFlag.NO_Z) == (int)VehicleFlag.NO_Z)
{
if ((m_flags & VehicleFlag.NO_Z) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.NO_Z);
}
if ((pParam & (int)VehicleFlag.LOCK_HOVER_HEIGHT) == (int)VehicleFlag.LOCK_HOVER_HEIGHT)
{
if ((m_Hoverflags & VehicleFlag.LOCK_HOVER_HEIGHT) != (VehicleFlag)0)
m_Hoverflags &= ~(VehicleFlag.LOCK_HOVER_HEIGHT);
}
if ((pParam & (int)VehicleFlag.NO_DEFLECTION) == (int)VehicleFlag.NO_DEFLECTION)
{
if ((m_flags & VehicleFlag.NO_DEFLECTION) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.NO_DEFLECTION);
}
if ((pParam & (int)VehicleFlag.LOCK_ROTATION) == (int)VehicleFlag.LOCK_ROTATION)
{
if ((m_flags & VehicleFlag.LOCK_ROTATION) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.LOCK_ROTATION);
}
}
else
{
if ((pParam & (int)VehicleFlag.HOVER_GLOBAL_HEIGHT) == (int)VehicleFlag.HOVER_GLOBAL_HEIGHT)
{
m_Hoverflags |= (VehicleFlag.HOVER_GLOBAL_HEIGHT | m_flags);
}
if ((pParam & (int)VehicleFlag.HOVER_TERRAIN_ONLY) == (int)VehicleFlag.HOVER_TERRAIN_ONLY)
{
m_Hoverflags |= (VehicleFlag.HOVER_TERRAIN_ONLY | m_flags);
}
if ((pParam & (int)VehicleFlag.HOVER_UP_ONLY) == (int)VehicleFlag.HOVER_UP_ONLY)
{
m_Hoverflags |= (VehicleFlag.HOVER_UP_ONLY | m_flags);
}
if ((pParam & (int)VehicleFlag.HOVER_WATER_ONLY) == (int)VehicleFlag.HOVER_WATER_ONLY)
{
m_Hoverflags |= (VehicleFlag.HOVER_WATER_ONLY | m_flags);
}
if ((pParam & (int)VehicleFlag.LIMIT_MOTOR_UP) == (int)VehicleFlag.LIMIT_MOTOR_UP)
{
m_flags |= (VehicleFlag.LIMIT_MOTOR_UP | m_flags);
}
if ((pParam & (int)VehicleFlag.MOUSELOOK_BANK) == (int)VehicleFlag.MOUSELOOK_BANK)
{
m_flags |= (VehicleFlag.MOUSELOOK_BANK | m_flags);
}
if ((pParam & (int)VehicleFlag.MOUSELOOK_STEER) == (int)VehicleFlag.MOUSELOOK_STEER)
{
m_flags |= (VehicleFlag.MOUSELOOK_STEER | m_flags);
}
if ((pParam & (int)VehicleFlag.NO_DEFLECTION_UP) == (int)VehicleFlag.NO_DEFLECTION_UP)
{
m_flags |= (VehicleFlag.NO_DEFLECTION_UP | m_flags);
}
if ((pParam & (int)VehicleFlag.CAMERA_DECOUPLED) == (int)VehicleFlag.CAMERA_DECOUPLED)
{
m_flags |= (VehicleFlag.CAMERA_DECOUPLED | m_flags);
}
if ((pParam & (int)VehicleFlag.NO_X) == (int)VehicleFlag.NO_X)
{
m_flags |= (VehicleFlag.NO_X);
}
if ((pParam & (int)VehicleFlag.NO_Y) == (int)VehicleFlag.NO_Y)
{
m_flags |= (VehicleFlag.NO_Y);
}
if ((pParam & (int)VehicleFlag.NO_Z) == (int)VehicleFlag.NO_Z)
{
m_flags |= (VehicleFlag.NO_Z);
}
if ((pParam & (int)VehicleFlag.LOCK_HOVER_HEIGHT) == (int)VehicleFlag.LOCK_HOVER_HEIGHT)
{
m_Hoverflags |= (VehicleFlag.LOCK_HOVER_HEIGHT);
}
if ((pParam & (int)VehicleFlag.NO_DEFLECTION) == (int)VehicleFlag.NO_DEFLECTION)
{
m_flags |= (VehicleFlag.NO_DEFLECTION);
}
if ((pParam & (int)VehicleFlag.LOCK_ROTATION) == (int)VehicleFlag.LOCK_ROTATION)
{
m_flags |= (VehicleFlag.LOCK_ROTATION);
}
}
}//end ProcessVehicleFlags
internal void ProcessTypeChange(Vehicle pType)
{
// Set Defaults For Type
m_type = pType;
switch (pType)
{
case Vehicle.TYPE_NONE:
m_linearFrictionTimescale = new Vector3(0, 0, 0);
m_angularFrictionTimescale = new Vector3(0, 0, 0);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 0;
m_linearMotorDecayTimescale = 0;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 0;
m_angularMotorDecayTimescale = 0;
m_VhoverHeight = 0;
m_VhoverTimescale = 0;
m_VehicleBuoyancy = 0;
m_flags = (VehicleFlag)0;
break;
case Vehicle.TYPE_SLED:
m_linearFrictionTimescale = new Vector3(30, 1, 1000);
m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 1000;
m_linearMotorDecayTimescale = 120;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 1000;
m_angularMotorDecayTimescale = 120;
m_VhoverHeight = 0;
// m_VhoverEfficiency = 1;
m_VhoverTimescale = 10;
m_VehicleBuoyancy = 0;
// m_linearDeflectionEfficiency = 1;
// m_linearDeflectionTimescale = 1;
// m_angularDeflectionEfficiency = 1;
// m_angularDeflectionTimescale = 1000;
// m_bankingEfficiency = 0;
// m_bankingMix = 1;
// m_bankingTimescale = 10;
// m_referenceFrame = Quaternion.Identity;
m_Hoverflags &=
~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP);
break;
case Vehicle.TYPE_CAR:
m_linearFrictionTimescale = new Vector3(100, 2, 1000);
m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 1;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 1;
m_angularMotorDecayTimescale = 0.8f;
m_VhoverHeight = 0;
// m_VhoverEfficiency = 0;
m_VhoverTimescale = 1000;
m_VehicleBuoyancy = 0;
// // m_linearDeflectionEfficiency = 1;
// // m_linearDeflectionTimescale = 2;
// // m_angularDeflectionEfficiency = 0;
// m_angularDeflectionTimescale = 10;
m_verticalAttractionEfficiency = 1f;
m_verticalAttractionTimescale = 10f;
// m_bankingEfficiency = -0.2f;
// m_bankingMix = 1;
// m_bankingTimescale = 1;
// m_referenceFrame = Quaternion.Identity;
m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT);
m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY |
VehicleFlag.LIMIT_MOTOR_UP);
m_Hoverflags |= (VehicleFlag.HOVER_UP_ONLY);
break;
case Vehicle.TYPE_BOAT:
m_linearFrictionTimescale = new Vector3(10, 3, 2);
m_angularFrictionTimescale = new Vector3(10,10,10);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 5;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 4;
m_angularMotorDecayTimescale = 4;
m_VhoverHeight = 0;
// m_VhoverEfficiency = 0.5f;
m_VhoverTimescale = 2;
m_VehicleBuoyancy = 1;
// m_linearDeflectionEfficiency = 0.5f;
// m_linearDeflectionTimescale = 3;
// m_angularDeflectionEfficiency = 0.5f;
// m_angularDeflectionTimescale = 5;
m_verticalAttractionEfficiency = 0.5f;
m_verticalAttractionTimescale = 5f;
// m_bankingEfficiency = -0.3f;
// m_bankingMix = 0.8f;
// m_bankingTimescale = 1;
// m_referenceFrame = Quaternion.Identity;
m_Hoverflags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
m_flags &= ~(VehicleFlag.LIMIT_ROLL_ONLY);
m_flags |= (VehicleFlag.NO_DEFLECTION_UP |
VehicleFlag.LIMIT_MOTOR_UP);
m_Hoverflags |= (VehicleFlag.HOVER_WATER_ONLY);
break;
case Vehicle.TYPE_AIRPLANE:
m_linearFrictionTimescale = new Vector3(200, 10, 5);
m_angularFrictionTimescale = new Vector3(20, 20, 20);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 2;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 4;
m_angularMotorDecayTimescale = 4;
m_VhoverHeight = 0;
// m_VhoverEfficiency = 0.5f;
m_VhoverTimescale = 1000;
m_VehicleBuoyancy = 0;
// m_linearDeflectionEfficiency = 0.5f;
// m_linearDeflectionTimescale = 3;
// m_angularDeflectionEfficiency = 1;
// m_angularDeflectionTimescale = 2;
m_verticalAttractionEfficiency = 0.9f;
m_verticalAttractionTimescale = 2f;
// m_bankingEfficiency = 1;
// m_bankingMix = 0.7f;
// m_bankingTimescale = 2;
// m_referenceFrame = Quaternion.Identity;
m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP);
m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY);
break;
case Vehicle.TYPE_BALLOON:
m_linearFrictionTimescale = new Vector3(5, 5, 5);
m_angularFrictionTimescale = new Vector3(10, 10, 10);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 5;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 6;
m_angularMotorDecayTimescale = 10;
m_VhoverHeight = 5;
// m_VhoverEfficiency = 0.8f;
m_VhoverTimescale = 10;
m_VehicleBuoyancy = 1;
// m_linearDeflectionEfficiency = 0;
// m_linearDeflectionTimescale = 5;
// m_angularDeflectionEfficiency = 0;
// m_angularDeflectionTimescale = 5;
m_verticalAttractionEfficiency = 1f;
m_verticalAttractionTimescale = 100f;
// m_bankingEfficiency = 0;
// m_bankingMix = 0.7f;
// m_bankingTimescale = 5;
// m_referenceFrame = Quaternion.Identity;
m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_UP_ONLY);
m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP);
m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY);
m_Hoverflags |= (VehicleFlag.HOVER_GLOBAL_HEIGHT);
break;
}
}//end SetDefaultsForType
internal void Enable(IntPtr pBody, OdeScene pParentScene)
{
if (m_type == Vehicle.TYPE_NONE)
return;
m_body = pBody;
}
internal void Stop()
{
m_lastLinearVelocityVector = Vector3.Zero;
m_lastAngularVelocity = Vector3.Zero;
m_lastPositionVector = SafeNativeMethods.BodyGetPosition(Body);
}
internal void Step(float pTimestep, OdeScene pParentScene)
{
if (m_body == IntPtr.Zero || m_type == Vehicle.TYPE_NONE)
return;
frcount++; // used to limit debug comment output
if (frcount > 100)
frcount = 0;
MoveLinear(pTimestep, pParentScene);
MoveAngular(pTimestep);
LimitRotation(pTimestep);
}// end Step
private void MoveLinear(float pTimestep, OdeScene _pParentScene)
{
if (!m_linearMotorDirection.ApproxEquals(Vector3.Zero, 0.01f)) // requested m_linearMotorDirection is significant
{
if (!SafeNativeMethods.BodyIsEnabled(Body))
SafeNativeMethods.BodyEnable(Body);
// add drive to body
Vector3 addAmount = m_linearMotorDirection/(m_linearMotorTimescale/pTimestep);
m_lastLinearVelocityVector += (addAmount*10); // lastLinearVelocityVector is the current body velocity vector?
// This will work temporarily, but we really need to compare speed on an axis
// KF: Limit body velocity to applied velocity?
if (Math.Abs(m_lastLinearVelocityVector.X) > Math.Abs(m_linearMotorDirectionLASTSET.X))
m_lastLinearVelocityVector.X = m_linearMotorDirectionLASTSET.X;
if (Math.Abs(m_lastLinearVelocityVector.Y) > Math.Abs(m_linearMotorDirectionLASTSET.Y))
m_lastLinearVelocityVector.Y = m_linearMotorDirectionLASTSET.Y;
if (Math.Abs(m_lastLinearVelocityVector.Z) > Math.Abs(m_linearMotorDirectionLASTSET.Z))
m_lastLinearVelocityVector.Z = m_linearMotorDirectionLASTSET.Z;
// decay applied velocity
Vector3 decayfraction = ((Vector3.One/(m_linearMotorDecayTimescale/pTimestep)));
//Console.WriteLine("decay: " + decayfraction);
m_linearMotorDirection -= m_linearMotorDirection * decayfraction * 0.5f;
//Console.WriteLine("actual: " + m_linearMotorDirection);
}
else
{ // requested is not significant
// if what remains of applied is small, zero it.
if (m_lastLinearVelocityVector.ApproxEquals(Vector3.Zero, 0.01f))
m_lastLinearVelocityVector = Vector3.Zero;
}
// convert requested object velocity to world-referenced vector
m_dir = m_lastLinearVelocityVector;
SafeNativeMethods.Quaternion rot = SafeNativeMethods.BodyGetQuaternion(Body);
Quaternion rotq = new Quaternion(rot.X, rot.Y, rot.Z, rot.W); // rotq = rotation of object
m_dir *= rotq; // apply obj rotation to velocity vector
// add Gravity andBuoyancy
// KF: So far I have found no good method to combine a script-requested
// .Z velocity and gravity. Therefore only 0g will used script-requested
// .Z velocity. >0g (m_VehicleBuoyancy < 1) will used modified gravity only.
Vector3 grav = Vector3.Zero;
// There is some gravity, make a gravity force vector
// that is applied after object velocity.
SafeNativeMethods.Mass objMass;
SafeNativeMethods.BodyGetMass(Body, out objMass);
// m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g;
grav.Z = _pParentScene.gravityz * objMass.mass * (1f - m_VehicleBuoyancy);
// Preserve the current Z velocity
SafeNativeMethods.Vector3 vel_now = SafeNativeMethods.BodyGetLinearVel(Body);
m_dir.Z = vel_now.Z; // Preserve the accumulated falling velocity
SafeNativeMethods.Vector3 pos = SafeNativeMethods.BodyGetPosition(Body);
// Vector3 accel = new Vector3(-(m_dir.X - m_lastLinearVelocityVector.X / 0.1f), -(m_dir.Y - m_lastLinearVelocityVector.Y / 0.1f), m_dir.Z - m_lastLinearVelocityVector.Z / 0.1f);
Vector3 posChange = new Vector3();
posChange.X = pos.X - m_lastPositionVector.X;
posChange.Y = pos.Y - m_lastPositionVector.Y;
posChange.Z = pos.Z - m_lastPositionVector.Z;
double Zchange = Math.Abs(posChange.Z);
if (m_BlockingEndPoint != Vector3.Zero)
{
if (pos.X >= (m_BlockingEndPoint.X - (float)1))
{
pos.X -= posChange.X + 1;
SafeNativeMethods.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
if (pos.Y >= (m_BlockingEndPoint.Y - (float)1))
{
pos.Y -= posChange.Y + 1;
SafeNativeMethods.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
if (pos.Z >= (m_BlockingEndPoint.Z - (float)1))
{
pos.Z -= posChange.Z + 1;
SafeNativeMethods.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
if (pos.X <= 0)
{
pos.X += posChange.X + 1;
SafeNativeMethods.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
if (pos.Y <= 0)
{
pos.Y += posChange.Y + 1;
SafeNativeMethods.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
}
if (pos.Z < _pParentScene.GetTerrainHeightAtXY(pos.X, pos.Y))
{
pos.Z = _pParentScene.GetTerrainHeightAtXY(pos.X, pos.Y) + 2;
SafeNativeMethods.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
// Check if hovering
if ((m_Hoverflags & (VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT)) != 0)
{
// We should hover, get the target height
if ((m_Hoverflags & VehicleFlag.HOVER_WATER_ONLY) != 0)
{
m_VhoverTargetHeight = _pParentScene.GetWaterLevel() + m_VhoverHeight;
}
if ((m_Hoverflags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0)
{
m_VhoverTargetHeight = _pParentScene.GetTerrainHeightAtXY(pos.X, pos.Y) + m_VhoverHeight;
}
if ((m_Hoverflags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != 0)
{
m_VhoverTargetHeight = m_VhoverHeight;
}
if ((m_Hoverflags & VehicleFlag.HOVER_UP_ONLY) != 0)
{
// If body is aready heigher, use its height as target height
if (pos.Z > m_VhoverTargetHeight) m_VhoverTargetHeight = pos.Z;
}
if ((m_Hoverflags & VehicleFlag.LOCK_HOVER_HEIGHT) != 0)
{
if ((pos.Z - m_VhoverTargetHeight) > .2 || (pos.Z - m_VhoverTargetHeight) < -.2)
{
SafeNativeMethods.BodySetPosition(Body, pos.X, pos.Y, m_VhoverTargetHeight);
}
}
else
{
float herr0 = pos.Z - m_VhoverTargetHeight;
// Replace Vertical speed with correction figure if significant
if (Math.Abs(herr0) > 0.01f)
{
m_dir.Z = -((herr0 * pTimestep * 50.0f) / m_VhoverTimescale);
//KF: m_VhoverEfficiency is not yet implemented
}
else
{
m_dir.Z = 0f;
}
}
// m_VhoverEfficiency = 0f; // 0=boucy, 1=Crit.damped
// m_VhoverTimescale = 0f; // time to acheive height
// pTimestep is time since last frame,in secs
}
if ((m_flags & (VehicleFlag.LIMIT_MOTOR_UP)) != 0)
{
//Start Experimental Values
if (Zchange > .3)
{
grav.Z = (float)(grav.Z * 3);
}
if (Zchange > .15)
{
grav.Z = (float)(grav.Z * 2);
}
if (Zchange > .75)
{
grav.Z = (float)(grav.Z * 1.5);
}
if (Zchange > .05)
{
grav.Z = (float)(grav.Z * 1.25);
}
if (Zchange > .025)
{
grav.Z = (float)(grav.Z * 1.125);
}
float terraintemp = _pParentScene.GetTerrainHeightAtXY(pos.X, pos.Y);
float postemp = (pos.Z - terraintemp);
if (postemp > 2.5f)
{
grav.Z = (float)(grav.Z * 1.037125);
}
//End Experimental Values
}
if ((m_flags & (VehicleFlag.NO_X)) != 0)
{
m_dir.X = 0;
}
if ((m_flags & (VehicleFlag.NO_Y)) != 0)
{
m_dir.Y = 0;
}
if ((m_flags & (VehicleFlag.NO_Z)) != 0)
{
m_dir.Z = 0;
}
m_lastPositionVector = SafeNativeMethods.BodyGetPosition(Body);
// Apply velocity
SafeNativeMethods.BodySetLinearVel(Body, m_dir.X, m_dir.Y, m_dir.Z);
// apply gravity force
SafeNativeMethods.BodyAddForce(Body, grav.X, grav.Y, grav.Z);
// apply friction
Vector3 decayamount = Vector3.One / (m_linearFrictionTimescale / pTimestep);
m_lastLinearVelocityVector -= m_lastLinearVelocityVector * decayamount;
} // end MoveLinear()
private void MoveAngular(float pTimestep)
{
/*
private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor
private int m_angularMotorApply = 0; // application frame counter
private float m_angularMotorVelocity = 0; // current angular motor velocity (ramps up and down)
private float m_angularMotorTimescale = 0; // motor angular velocity ramp up rate
private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate
private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate
private Vector3 m_lastAngularVelocity = Vector3.Zero; // what was last applied to body
*/
// Get what the body is doing, this includes 'external' influences
SafeNativeMethods.Vector3 angularVelocity = SafeNativeMethods.BodyGetAngularVel(Body);
// Vector3 angularVelocity = Vector3.Zero;
if (m_angularMotorApply > 0)
{
// ramp up to new value
// current velocity += error / (time to get there / step interval)
// requested speed - last motor speed
m_angularMotorVelocity.X += (m_angularMotorDirection.X - m_angularMotorVelocity.X) / (m_angularMotorTimescale / pTimestep);
m_angularMotorVelocity.Y += (m_angularMotorDirection.Y - m_angularMotorVelocity.Y) / (m_angularMotorTimescale / pTimestep);
m_angularMotorVelocity.Z += (m_angularMotorDirection.Z - m_angularMotorVelocity.Z) / (m_angularMotorTimescale / pTimestep);
m_angularMotorApply--; // This is done so that if script request rate is less than phys frame rate the expected
// velocity may still be acheived.
}
else
{
// no motor recently applied, keep the body velocity
/* m_angularMotorVelocity.X = angularVelocity.X;
m_angularMotorVelocity.Y = angularVelocity.Y;
m_angularMotorVelocity.Z = angularVelocity.Z; */
// and decay the velocity
m_angularMotorVelocity -= m_angularMotorVelocity / (m_angularMotorDecayTimescale / pTimestep);
} // end motor section
// Vertical attractor section
Vector3 vertattr = Vector3.Zero;
if (m_verticalAttractionTimescale < 300)
{
float VAservo = 0.2f / (m_verticalAttractionTimescale * pTimestep);
// get present body rotation
SafeNativeMethods.Quaternion rot = SafeNativeMethods.BodyGetQuaternion(Body);
Quaternion rotq = new Quaternion(rot.X, rot.Y, rot.Z, rot.W);
// make a vector pointing up
Vector3 verterr = Vector3.Zero;
verterr.Z = 1.0f;
// rotate it to Body Angle
verterr = verterr * rotq;
// verterr.X and .Y are the World error ammounts. They are 0 when there is no error (Vehicle Body is 'vertical'), and .Z will be 1.
// As the body leans to its side |.X| will increase to 1 and .Z fall to 0. As body inverts |.X| will fall and .Z will go
// negative. Similar for tilt and |.Y|. .X and .Y must be modulated to prevent a stable inverted body.
if (verterr.Z < 0.0f)
{
verterr.X = 2.0f - verterr.X;
verterr.Y = 2.0f - verterr.Y;
}
// Error is 0 (no error) to +/- 2 (max error)
// scale it by VAservo
verterr = verterr * VAservo;
//if (frcount == 0) Console.WriteLine("VAerr=" + verterr);
// As the body rotates around the X axis, then verterr.Y increases; Rotated around Y then .X increases, so
// Change Body angular velocity X based on Y, and Y based on X. Z is not changed.
vertattr.X = verterr.Y;
vertattr.Y = - verterr.X;
vertattr.Z = 0f;
// scaling appears better usingsquare-law
float bounce = 1.0f - (m_verticalAttractionEfficiency * m_verticalAttractionEfficiency);
vertattr.X += bounce * angularVelocity.X;
vertattr.Y += bounce * angularVelocity.Y;
} // else vertical attractor is off
// m_lastVertAttractor = vertattr;
// Bank section tba
// Deflection section tba
// Sum velocities
m_lastAngularVelocity = m_angularMotorVelocity + vertattr; // + bank + deflection
if ((m_flags & (VehicleFlag.NO_DEFLECTION_UP)) != 0)
{
m_lastAngularVelocity.X = 0;
m_lastAngularVelocity.Y = 0;
}
if (!m_lastAngularVelocity.ApproxEquals(Vector3.Zero, 0.01f))
{
if (!SafeNativeMethods.BodyIsEnabled (Body)) SafeNativeMethods.BodyEnable (Body);
}
else
{
m_lastAngularVelocity = Vector3.Zero; // Reduce small value to zero.
}
// apply friction
Vector3 decayamount = Vector3.One / (m_angularFrictionTimescale / pTimestep);
m_lastAngularVelocity -= m_lastAngularVelocity * decayamount;
// Apply to the body
SafeNativeMethods.BodySetAngularVel (Body, m_lastAngularVelocity.X, m_lastAngularVelocity.Y, m_lastAngularVelocity.Z);
} //end MoveAngular
internal void LimitRotation(float timestep)
{
SafeNativeMethods.Quaternion rot = SafeNativeMethods.BodyGetQuaternion(Body);
Quaternion rotq = new Quaternion(rot.X, rot.Y, rot.Z, rot.W); // rotq = rotation of object
SafeNativeMethods.Quaternion m_rot = new SafeNativeMethods.Quaternion();
bool changed = false;
m_rot.X = rotq.X;
m_rot.Y = rotq.Y;
m_rot.Z = rotq.Z;
m_rot.W = rotq.W;
if (m_RollreferenceFrame != Quaternion.Identity)
{
if (rotq.X >= m_RollreferenceFrame.X)
{
m_rot.X = rotq.X - (m_RollreferenceFrame.X / 2);
}
if (rotq.Y >= m_RollreferenceFrame.Y)
{
m_rot.Y = rotq.Y - (m_RollreferenceFrame.Y / 2);
}
if (rotq.X <= -m_RollreferenceFrame.X)
{
m_rot.X = rotq.X + (m_RollreferenceFrame.X / 2);
}
if (rotq.Y <= -m_RollreferenceFrame.Y)
{
m_rot.Y = rotq.Y + (m_RollreferenceFrame.Y / 2);
}
changed = true;
}
if ((m_flags & VehicleFlag.LOCK_ROTATION) != 0)
{
m_rot.X = 0;
m_rot.Y = 0;
changed = true;
}
if (changed)
SafeNativeMethods.BodySetQuaternion(Body, ref m_rot);
}
}
}
| |
// Authors:
// Rafael Mizrahi <[email protected]>
// Erez Lotan <[email protected]>
// Oren Gurfinkel <[email protected]>
// Ofer Borstein
//
// Copyright (c) 2004 Mainsoft Co.
//
// 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 NUnit.Framework;
using System;
using System.Data;
using GHTUtils;
using GHTUtils.Base;
namespace tests.system_data_dll.System_Data
{
[TestFixture] public class DataSet_CaseSensitive : GHTBase
{
[Test] public void Main()
{
DataSet_CaseSensitive tc = new DataSet_CaseSensitive();
Exception exp = null;
try
{
tc.BeginTest("DataSet_CaseSensitive");
tc.run();
}
catch(Exception ex)
{
exp = ex;
}
finally
{
tc.EndTest(exp);
}
}
//Activate This Construntor to log All To Standard output
//public TestClass():base(true){}
//Activate this constructor to log Failures to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, false){}
//Activate this constructor to log All to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, true){}
//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES
public void run()
{
Exception exp = null;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
try
{
BeginCase("CaseSensitive - default value (false)");
Compare(ds.CaseSensitive ,false );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
ds.CaseSensitive = true;
try
{
BeginCase("CaseSensitive - get");
Compare(ds.CaseSensitive ,true );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
//add a datatable to a dataset
ds.Tables.Add(dt);
try
{
BeginCase("DataTable CaseSensitive from DataSet - true");
Compare(dt.CaseSensitive ,true );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
ds.Tables.Clear();
ds.CaseSensitive = false;
dt = new DataTable();
ds.Tables.Add(dt);
try
{
BeginCase("DataTable CaseSensitive from DataSet - false");
Compare(dt.CaseSensitive ,false);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
//change DataSet CaseSensitive and check DataTables in it
ds.Tables.Clear();
ds.CaseSensitive = false;
dt = new DataTable();
ds.Tables.Add(dt);
try
{
BeginCase("Change DataSet CaseSensitive - check Table - true");
ds.CaseSensitive = true;
Compare(dt.CaseSensitive ,true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Change DataSet CaseSensitive - check Table - false");
ds.CaseSensitive = false;
Compare(dt.CaseSensitive ,false);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
//Add new table to DataSet with CaseSensitive,check the table case after adding it to DataSet
ds.Tables.Clear();
ds.CaseSensitive = true;
dt = new DataTable();
dt.CaseSensitive = false;
ds.Tables.Add(dt);
try
{
BeginCase("DataTable get case sensitive from DataSet - false");
Compare(dt.CaseSensitive ,false);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
ds.Tables.Clear();
ds.CaseSensitive = false;
dt = new DataTable();
dt.CaseSensitive = true;
ds.Tables.Add(dt);
try
{
BeginCase("DataTable get case sensitive from DataSet - true");
Compare(dt.CaseSensitive ,true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
//Add new table to DataSet and change the DataTable CaseSensitive
ds.Tables.Clear();
ds.CaseSensitive = true;
dt = new DataTable();
ds.Tables.Add(dt);
try
{
BeginCase("Add new table to DataSet and change the DataTable CaseSensitive - false");
dt.CaseSensitive = false;
Compare(dt.CaseSensitive ,false);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
ds.Tables.Clear();
ds.CaseSensitive = false;
dt = new DataTable();
ds.Tables.Add(dt);
try
{
BeginCase("Add new table to DataSet and change the DataTable CaseSensitive - true");
dt.CaseSensitive = true;
Compare(dt.CaseSensitive ,true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
//Add DataTable to Dataset, Change DataSet CaseSensitive, check DataTable
ds.Tables.Clear();
ds.CaseSensitive = true;
dt = new DataTable();
dt.CaseSensitive = true;
ds.Tables.Add(dt);
try
{
BeginCase("Add DataTable to Dataset, Change DataSet CaseSensitive, check DataTable - true");
ds.CaseSensitive = false;
Compare(dt.CaseSensitive ,true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
}
}
}
| |
/********************************************************************
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 BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes ([email protected]), Dan Moorehead ([email protected])
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
#region CVS Information
/*
* $Source$
* $Author: mccollum $
* $Date: 2006-09-08 17:12:07 -0700 (Fri, 08 Sep 2006) $
* $Revision: 6434 $
*/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Xml;
using DNPreBuild.Core.Attributes;
using DNPreBuild.Core.Interfaces;
using DNPreBuild.Core.Util;
namespace DNPreBuild.Core.Nodes
{
[DataNode("Options")]
public class OptionsNode : DataNode
{
#region Fields
private static Hashtable m_OptionFields = null;
[OptionNode("CompilerDefines")]
private string m_CompilerDefines = "";
[OptionNode("OptimizeCode")]
private bool m_OptimizeCode = false;
[OptionNode("CheckUnderflowOverflow")]
private bool m_CheckUnderflowOverflow = false;
[OptionNode("AllowUnsafe")]
private bool m_AllowUnsafe = false;
[OptionNode("WarningLevel")]
private int m_WarningLevel = 4;
[OptionNode("WarningsAsErrors")]
private bool m_WarningsAsErrors = false;
[OptionNode("SupressWarnings")]
private string m_SupressWarnings = "";
[OptionNode("OutputPath")]
private string m_OutputPath = "bin/";
[OptionNode("XmlDocFile")]
private string m_XmlDocFile = "";
[OptionNode("DebugInformation")]
private bool m_DebugInformation = false;
[OptionNode("RegisterCOMInterop")]
private bool m_RegisterCOMInterop = false;
[OptionNode("IncrementalBuild")]
private bool m_IncrementalBuild = false;
[OptionNode("BaseAddress")]
private string m_BaseAddress = "285212672";
[OptionNode("FileAlignment")]
private int m_FileAlignment = 4096;
[OptionNode("NoStdLib")]
private bool m_NoStdLib = false;
private StringCollection m_FieldsDefined = null;
#endregion
#region Constructors
static OptionsNode()
{
Type t = typeof(OptionsNode);
m_OptionFields = new Hashtable();
foreach(FieldInfo f in t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
object[] attrs = f.GetCustomAttributes(typeof(OptionNodeAttribute), false);
if(attrs == null || attrs.Length < 1)
continue;
OptionNodeAttribute ona = (OptionNodeAttribute)attrs[0];
m_OptionFields[ona.NodeName] = f;
}
}
public OptionsNode()
{
m_FieldsDefined = new StringCollection();
}
#endregion
#region Properties
public object this[string idx]
{
get
{
if(!m_OptionFields.ContainsKey(idx))
return null;
FieldInfo f = (FieldInfo)m_OptionFields[idx];
return f.GetValue(this);
}
}
#endregion
#region Private Methods
private void FlagDefined(string name)
{
if(!m_FieldsDefined.Contains(name))
m_FieldsDefined.Add(name);
}
private void SetOption(string nodeName, string val)
{
lock(m_OptionFields)
{
if(!m_OptionFields.ContainsKey(nodeName))
return;
FieldInfo f = (FieldInfo)m_OptionFields[nodeName];
f.SetValue(this, Helper.TranslateValue(f.FieldType, val));
FlagDefined(f.Name);
}
}
#endregion
#region Public Methods
public override void Parse(XmlNode node)
{
foreach(XmlNode child in node.ChildNodes)
SetOption(child.Name, Helper.InterpolateForEnvironmentVariables(child.InnerText));
}
public void CopyTo(OptionsNode opt)
{
if(opt == null)
return;
foreach(FieldInfo f in m_OptionFields.Values)
{
if(m_FieldsDefined.Contains(f.Name))
{
f.SetValue(opt, f.GetValue(this));
opt.m_FieldsDefined.Add(f.Name);
}
}
}
#endregion
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.10.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Knowledge Graph Search API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/knowledge-graph/'>Knowledge Graph Search API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20151215 (348)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/knowledge-graph/'>
* https://developers.google.com/knowledge-graph/</a>
* <tr><th>Discovery Name<td>kgsearch
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Knowledge Graph Search API can be found at
* <a href='https://developers.google.com/knowledge-graph/'>https://developers.google.com/knowledge-graph/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Kgsearch.v1
{
/// <summary>The Kgsearch Service.</summary>
public class KgsearchService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public KgsearchService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public KgsearchService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
entities = new EntitiesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "kgsearch"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://kgsearch.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
private readonly EntitiesResource entities;
/// <summary>Gets the Entities resource.</summary>
public virtual EntitiesResource Entities
{
get { return entities; }
}
}
///<summary>A base abstract class for Kgsearch requests.</summary>
public abstract class KgsearchBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new KgsearchBaseServiceRequest instance.</summary>
protected KgsearchBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Xgafv { get; set; }
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Alt { get; set; }
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Kgsearch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "entities" collection of methods.</summary>
public class EntitiesResource
{
private const string Resource = "entities";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public EntitiesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Searches Knowledge Graph for entities that match the constraints. A list of matched entities will
/// be returned in response, which will be in JSON-LD format and compatible with http://schema.org</summary>
public virtual SearchRequest Search()
{
return new SearchRequest(service);
}
/// <summary>Searches Knowledge Graph for entities that match the constraints. A list of matched entities will
/// be returned in response, which will be in JSON-LD format and compatible with http://schema.org</summary>
public class SearchRequest : KgsearchBaseServiceRequest<Google.Apis.Kgsearch.v1.Data.SearchResponse>
{
/// <summary>Constructs a new Search request.</summary>
public SearchRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The literal query string for search.</summary>
[Google.Apis.Util.RequestParameterAttribute("query", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Query { get; set; }
/// <summary>The list of entity id to be used for search instead of query string.</summary>
[Google.Apis.Util.RequestParameterAttribute("ids", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> Ids { get; set; }
/// <summary>The list of language codes (defined in ISO 693) to run the query with, e.g. 'en'.</summary>
[Google.Apis.Util.RequestParameterAttribute("languages", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> Languages { get; set; }
/// <summary>Restricts returned entities with these types, e.g. Person (as defined in
/// http://schema.org/Person).</summary>
[Google.Apis.Util.RequestParameterAttribute("types", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> Types { get; set; }
/// <summary>Enables indenting of json results.</summary>
[Google.Apis.Util.RequestParameterAttribute("indent", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Indent { get; set; }
/// <summary>Enables prefix match against names and aliases of entities</summary>
[Google.Apis.Util.RequestParameterAttribute("prefix", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Prefix { get; set; }
/// <summary>Limits the number of entities to be returned.</summary>
[Google.Apis.Util.RequestParameterAttribute("limit", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> Limit { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "search"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/entities:search"; }
}
/// <summary>Initializes Search parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"query", new Google.Apis.Discovery.Parameter
{
Name = "query",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"ids", new Google.Apis.Discovery.Parameter
{
Name = "ids",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"languages", new Google.Apis.Discovery.Parameter
{
Name = "languages",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"types", new Google.Apis.Discovery.Parameter
{
Name = "types",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"indent", new Google.Apis.Discovery.Parameter
{
Name = "indent",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prefix", new Google.Apis.Discovery.Parameter
{
Name = "prefix",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"limit", new Google.Apis.Discovery.Parameter
{
Name = "limit",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Kgsearch.v1.Data
{
/// <summary>Response message includes the context and a list of matching results which contain the detail of
/// associated entities.</summary>
public class SearchResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The local context applicable for the response. See more details at http://www.w3.org/TR/json-ld
/// /#context-definitions.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("context")]
public virtual object Context { get; set; }
/// <summary>The item list of search results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("itemListElement")]
public virtual System.Collections.Generic.IList<object> ItemListElement { get; set; }
/// <summary>The schema type of top-level JSON-LD object, e.g. ItemList.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual object Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.