context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using YAF.Lucene.Net.Documents;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace YAF.Lucene.Net.Index
{
/*
* 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 DocIdSetIterator = YAF.Lucene.Net.Search.DocIdSetIterator;
using FixedBitSet = YAF.Lucene.Net.Util.FixedBitSet;
using InPlaceMergeSorter = YAF.Lucene.Net.Util.InPlaceMergeSorter;
using NumericDocValuesUpdate = YAF.Lucene.Net.Index.DocValuesUpdate.NumericDocValuesUpdate;
using PackedInt32s = YAF.Lucene.Net.Util.Packed.PackedInt32s;
using PagedGrowableWriter = YAF.Lucene.Net.Util.Packed.PagedGrowableWriter;
using PagedMutable = YAF.Lucene.Net.Util.Packed.PagedMutable;
/// <summary>
/// A <see cref="DocValuesFieldUpdates"/> which holds updates of documents, of a single
/// <see cref="NumericDocValuesField"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
internal class NumericDocValuesFieldUpdates : DocValuesFieldUpdates
{
new internal sealed class Iterator : DocValuesFieldUpdates.Iterator
{
private readonly int size;
private readonly PagedGrowableWriter values;
private readonly FixedBitSet docsWithField;
private readonly PagedMutable docs;
private long idx = 0; // long so we don't overflow if size == Integer.MAX_VALUE
private int doc = -1;
private long? value = null;
internal Iterator(int size, PagedGrowableWriter values, FixedBitSet docsWithField, PagedMutable docs)
{
this.size = size;
this.values = values;
this.docsWithField = docsWithField;
this.docs = docs;
}
public override object Value
{
get { return value; }
}
public override int NextDoc()
{
if (idx >= size)
{
value = null;
return doc = DocIdSetIterator.NO_MORE_DOCS;
}
doc = (int)docs.Get(idx);
++idx;
while (idx < size && docs.Get(idx) == doc)
{
++idx;
}
if (!docsWithField.Get((int)(idx - 1)))
{
value = null;
}
else
{
// idx points to the "next" element
value = values.Get(idx - 1);
}
return doc;
}
public override int Doc
{
get { return doc; }
}
public override void Reset()
{
doc = -1;
value = null;
idx = 0;
}
}
private FixedBitSet docsWithField;
private PagedMutable docs;
private PagedGrowableWriter values;
private int size;
public NumericDocValuesFieldUpdates(string field, int maxDoc)
: base(field, DocValuesFieldUpdatesType.NUMERIC)
{
docsWithField = new FixedBitSet(64);
docs = new PagedMutable(1, 1024, PackedInt32s.BitsRequired(maxDoc - 1), PackedInt32s.COMPACT);
values = new PagedGrowableWriter(1, 1024, 1, PackedInt32s.FAST);
size = 0;
}
public override void Add(int doc, object value)
{
// TODO: if the Sorter interface changes to take long indexes, we can remove that limitation
if (size == int.MaxValue)
{
throw new InvalidOperationException("cannot support more than System.Int32.MaxValue doc/value entries");
}
long? val = (long?)value;
if (val == null)
{
val = NumericDocValuesUpdate.MISSING;
}
// grow the structures to have room for more elements
if (docs.Count == size)
{
docs = docs.Grow(size + 1);
values = values.Grow(size + 1);
docsWithField = FixedBitSet.EnsureCapacity(docsWithField, (int)docs.Count);
}
if (val != NumericDocValuesUpdate.MISSING)
{
// only mark the document as having a value in that field if the value wasn't set to null (MISSING)
docsWithField.Set(size);
}
docs.Set(size, doc);
values.Set(size, (long)val);
++size;
}
public override DocValuesFieldUpdates.Iterator GetIterator()
{
PagedMutable docs = this.docs;
PagedGrowableWriter values = this.values;
FixedBitSet docsWithField = this.docsWithField;
new InPlaceMergeSorterAnonymousInnerClassHelper(this, docs, values, docsWithField).Sort(0, size);
return new Iterator(size, values, docsWithField, docs);
}
private class InPlaceMergeSorterAnonymousInnerClassHelper : InPlaceMergeSorter
{
private readonly NumericDocValuesFieldUpdates outerInstance;
private PagedMutable docs;
private PagedGrowableWriter values;
private FixedBitSet docsWithField;
public InPlaceMergeSorterAnonymousInnerClassHelper(NumericDocValuesFieldUpdates outerInstance, PagedMutable docs, PagedGrowableWriter values, FixedBitSet docsWithField)
{
this.outerInstance = outerInstance;
this.docs = docs;
this.values = values;
this.docsWithField = docsWithField;
}
protected override void Swap(int i, int j)
{
long tmpDoc = docs.Get(j);
docs.Set(j, docs.Get(i));
docs.Set(i, tmpDoc);
long tmpVal = values.Get(j);
values.Set(j, values.Get(i));
values.Set(i, tmpVal);
bool tmpBool = docsWithField.Get(j);
if (docsWithField.Get(i))
{
docsWithField.Set(j);
}
else
{
docsWithField.Clear(j);
}
if (tmpBool)
{
docsWithField.Set(i);
}
else
{
docsWithField.Clear(i);
}
}
protected override int Compare(int i, int j)
{
int x = (int)docs.Get(i);
int y = (int)docs.Get(j);
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Merge(DocValuesFieldUpdates other)
{
Debug.Assert(other is NumericDocValuesFieldUpdates);
NumericDocValuesFieldUpdates otherUpdates = (NumericDocValuesFieldUpdates)other;
if (size + otherUpdates.size > int.MaxValue)
{
throw new InvalidOperationException("cannot support more than System.Int32.MaxValue doc/value entries; size=" + size + " other.size=" + otherUpdates.size);
}
docs = docs.Grow(size + otherUpdates.size);
values = values.Grow(size + otherUpdates.size);
docsWithField = FixedBitSet.EnsureCapacity(docsWithField, (int)docs.Count);
for (int i = 0; i < otherUpdates.size; i++)
{
int doc = (int)otherUpdates.docs.Get(i);
if (otherUpdates.docsWithField.Get(i))
{
docsWithField.Set(size);
}
docs.Set(size, doc);
values.Set(size, otherUpdates.values.Get(i));
++size;
}
}
public override bool Any()
{
return size > 0;
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
$GUI_EDITOR_DEFAULT_PROFILE_FILENAME = "art/gui/customProfiles.cs";
$GUI_EDITOR_DEFAULT_PROFILE_CATEGORY = "Other";
//=============================================================================================
// GuiEditor.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function GuiEditor::createNewProfile( %this, %name, %copySource )
{
if( %name $= "" )
return;
// Make sure the object name is unique.
if( isObject( %name ) )
%name = getUniqueName( %name );
// Create the profile.
if( %copySource !$= "" )
eval( "new GuiControlProfile( " @ %name @ " : " @ %copySource.getName() @ " );" );
else
eval( "new GuiControlProfile( " @ %name @ " );" );
// Add the item and select it.
%category = %this.getProfileCategory( %name );
%group = GuiEditorProfilesTree.findChildItemByName( 0, %category );
%id = GuiEditorProfilesTree.insertItem( %group, %name @ " (" @ %name.getId() @ ")", %name.getId(), "" );
GuiEditorProfilesTree.sort( 0, true, true, false );
GuiEditorProfilesTree.clearSelection();
GuiEditorProfilesTree.selectItem( %id );
// Mark it as needing to be saved.
%this.setProfileDirty( %name, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditor::getProfileCategory( %this, %profile )
{
if( %this.isDefaultProfile( %name ) )
return "Default";
else if( %profile.category !$= "" )
return %profile.category;
else
return $GUI_EDITOR_DEFAULT_PROFILE_CATEGORY;
}
//---------------------------------------------------------------------------------------------
function GuiEditor::showDeleteProfileDialog( %this, %profile )
{
if( %profile $= "" )
return;
if( %profile.isInUse() )
{
MessageBoxOk( "Error",
"The profile '" @ %profile.getName() @ "' is still used by Gui controls."
);
return;
}
MessageBoxYesNo( "Delete Profile?",
"Do you really want to delete '" @ %profile.getName() @ "'?",
"GuiEditor.deleteProfile( " @ %profile @ " );"
);
}
//---------------------------------------------------------------------------------------------
function GuiEditor::deleteProfile( %this, %profile )
{
if( isObject( "GuiEditorProfilesPM" ) )
new PersistenceManager( GuiEditorProfilesPM );
// Clear dirty state.
%this.setProfileDirty( %profile, false );
// Remove from tree.
%id = GuiEditorProfilesTree.findItemByValue( %profile.getId() );
GuiEditorProfilesTree.removeItem( %id );
// Remove from file.
GuiEditorProfilesPM.removeObjectFromFile( %profile );
// Delete profile object.
%profile.delete();
}
//---------------------------------------------------------------------------------------------
function GuiEditor::showSaveProfileDialog( %this, %currentFileName )
{
getSaveFileName( "TorqueScript Files|*.cs", %this @ ".doSaveProfile", %currentFileName );
}
//---------------------------------------------------------------------------------------------
function GuiEditor::doSaveProfile( %this, %fileName )
{
%path = makeRelativePath( %fileName, getMainDotCsDir() );
GuiEditorProfileFileName.setText( %path );
%this.saveProfile( GuiEditorProfilesTree.getSelectedProfile(), %path );
}
//---------------------------------------------------------------------------------------------
function GuiEditor::saveProfile( %this, %profile, %fileName )
{
if( !isObject( "GuiEditorProfilesPM" ) )
new PersistenceManager( GuiEditorProfilesPM );
if( !GuiEditorProfilesPM.isDirty( %profile )
&& ( %fileName $= "" || %fileName $= %profile.getFileName() ) )
return;
// Update the filename, if requested.
if( %fileName !$= "" )
{
%profile.setFileName( %fileName );
GuiEditorProfilesPM.setDirty( %profile, %fileName );
}
// Save the object.
GuiEditorProfilesPM.saveDirtyObject( %profile );
// Clear its dirty state.
%this.setProfileDirty( %profile, false, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditor::revertProfile( %this, %profile )
{
// Revert changes.
GuiEditorProfileChangeManager.revertEdits( %profile );
// Clear its dirty state.
%this.setProfileDirty( %profile, false );
// Refresh inspector.
if( GuiEditorProfileInspector.getInspectObject() == %profile )
GuiEditorProfileInspector.refresh();
}
//---------------------------------------------------------------------------------------------
function GuiEditor::isProfileDirty( %this, %profile )
{
if( !isObject( "GuiEditorProfilesPM" ) )
return false;
return GuiEditorProfilesPM.isDirty( %profile );
}
//---------------------------------------------------------------------------------------------
function GuiEditor::setProfileDirty( %this, %profile, %value, %noCheck )
{
if( !isObject( "GuiEditorProfilesPM" ) )
new PersistenceManager( GuiEditorProfilesPM );
if( %value )
{
if( !GuiEditorProfilesPM.isDirty( %profile ) || %noCheck )
{
// If the profile hasn't yet been associated with a file,
// put it in the default file.
if( %profile.getFileName() $= "" )
%profile.setFileName( $GUI_EDITOR_DEFAULT_PROFILE_FILENAME );
// Add the profile to the dirty set.
GuiEditorProfilesPM.setDirty( %profile );
// Show the item as dirty in the tree.
%id = GuiEditorProfilesTree.findItemByValue( %profile.getId() );
GuiEditorProfilesTree.editItem( %id, GuiEditorProfilesTree.getItemText( %id ) SPC "*", %profile.getId() );
// Count the number of unsaved profiles. If this is
// the first one, indicate in the window title that
// we have unsaved profiles.
%this.increaseNumDirtyProfiles();
}
}
else
{
if( GuiEditorProfilesPM.isDirty( %profile ) || %noCheck )
{
// Remove from dirty list.
GuiEditorProfilesPM.removeDirty( %profile );
// Clear the dirty marker in the tree.
%id = GuiEditorProfilesTree.findItemByValue( %profile.getId() );
%text = GuiEditorProfilesTree.getItemText( %id );
GuiEditorProfilesTree.editItem( %id, getSubStr( %text, 0, strlen( %text ) - 2 ), %profile.getId() );
// Count saved profiles. If this was the last unsaved profile,
// remove the unsaved changes indicator from the window title.
%this.decreaseNumDirtyProfiles();
// Remove saved edits from the change manager.
GuiEditorProfileChangeManager.clearEdits( %profile );
}
}
}
//---------------------------------------------------------------------------------------------
/// Return true if the given profile name is the default profile for a
/// GuiControl class or if it's the GuiDefaultProfile.
function GuiEditor::isDefaultProfile( %this, %name )
{
if( %name $= "GuiDefaultProfile" )
return true;
if( !endsWith( %name, "Profile" ) )
return false;
%className = getSubStr( %name, 0, strlen( %name ) - 7 ) @ "Ctrl";
if( !isClass( %className ) )
return false;
return true;
}
//---------------------------------------------------------------------------------------------
function GuiEditor::increaseNumDirtyProfiles( %this )
{
%this.numDirtyProfiles ++;
if( %this.numDirtyProfiles == 1 )
{
%tab = GuiEditorTabBook-->profilesPage;
%tab.setText( %tab.text @ " *" );
}
}
//---------------------------------------------------------------------------------------------
function GuiEditor::decreaseNumDirtyProfiles( %this )
{
%this.numDirtyProfiles --;
if( !%this.numDirtyProfiles )
{
%tab = GuiEditorTabBook-->profilesPage;
%title = %tab.text;
%title = getSubstr( %title, 0, strlen( %title ) - 2 );
%tab.setText( %title );
}
}
//=============================================================================================
// GuiEditorProfilesTree.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::init( %this )
{
%this.clear();
%defaultGroup = %this.insertItem( 0, "Default", -1 );
%otherGroup = %this.insertItem( 0, $GUI_EDITOR_DEFAULT_PROFILE_CATEGORY, -1 );
foreach( %obj in GuiDataGroup )
{
if( !%obj.isMemberOfClass( "GuiControlProfile" ) )
continue;
// If it's an Editor profile, skip if showing them is not enabled.
if( %obj.category $= "Editor" && !GuiEditor.showEditorProfiles )
continue;
// Create a visible name.
%name = %obj.getName();
if( %name $= "" )
%name = "<Unnamed>";
%text = %name @ " (" @ %obj.getId() @ ")";
// Find which group to put the control in.
%isDefaultProfile = GuiEditor.isDefaultProfile( %name );
if( %isDefaultProfile )
%group = %defaultGroup;
else if( %obj.category !$= "" )
{
%group = %this.findChildItemByName( 0, %obj.category );
if( !%group )
%group = %this.insertItem( 0, %obj.category );
}
else
%group = %otherGroup;
// Insert the item.
%this.insertItem( %group, %text, %obj.getId(), "" );
}
%this.sort( 0, true, true, false );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::onSelect( %this, %id )
{
%obj = %this.getItemValue( %id );
if( %obj == -1 )
return;
GuiEditorProfileInspector.inspect( %obj );
%fileName = %obj.getFileName();
if( %fileName $= "" )
%fileName = $GUI_EDITOR_DEFAULT_PROFILE_FILENAME;
GuiEditorProfileFileName.setText( %fileName );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::onUnselect( %this, %id )
{
GuiEditorProfileInspector.inspect( 0 );
GuiEditorProfileFileName.setText( "" );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::onProfileRenamed( %this, %profile, %newName )
{
%item = %this.findItemByValue( %profile.getId() );
if( %item == -1 )
return;
%newText = %newName @ " (" @ %profile.getId() @ ")";
if( GuiEditor.isProfileDirty( %profile ) )
%newText = %newText @ " *";
%this.editItem( %item, %newText, %profile.getId() );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::getSelectedProfile( %this )
{
return %this.getItemValue( %this.getSelectedItem() );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::setSelectedProfile( %this, %profile )
{
%id = %this.findItemByValue( %profile.getId() );
%this.selectItem( %id );
}
//=============================================================================================
// GuiEditorProfileInspector.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc )
{
GuiEditorProfileFieldInfo.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onFieldAdded( %this, %object, %fieldName )
{
GuiEditor.setProfileDirty( %object, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onFieldRemoved( %this, %object, %fieldName )
{
GuiEditor.setProfileDirty( %object, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onFieldRenamed( %this, %object, %oldFieldName, %newFieldName )
{
GuiEditor.setProfileDirty( %object, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue )
{
GuiEditor.setProfileDirty( %object, true );
// If it's the name field, make sure to sync up the treeview.
if( %fieldName $= "name" )
GuiEditorProfilesTree.onProfileRenamed( %object, %newValue );
// Add change record.
GuiEditorProfileChangeManager.registerEdit( %object, %fieldName, %arrayIndex, %oldValue );
// Add undo.
pushInstantGroup();
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%action = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %oldValue;
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
popInstantGroup();
%action.addToManager( GuiEditor.getUndoManager() );
GuiEditor.updateUndoMenu();
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onInspectorPreFieldModification( %this, %fieldName, %arrayIndex )
{
pushInstantGroup();
%undoManager = GuiEditor.getUndoManager();
%object = %this.getInspectObject();
%nameOrClass = %object.getName();
if( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%action = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %object.getFieldValue( %fieldName, %arrayIndex );
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
%this.currentFieldEditAction = %action;
popInstantGroup();
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onInspectorPostFieldModification( %this )
{
%action = %this.currentFieldEditAction;
%object = %action.objectId;
%fieldName = %action.fieldName;
%arrayIndex = %action.arrayIndex;
%oldValue = %action.fieldValue;
%newValue = %object.getFieldValue( %fieldName, %arrayIndex );
// If it's the name field, make sure to sync up the treeview.
if( %action.fieldName $= "name" )
GuiEditorProfilesTree.onProfileRenamed( %object, %newValue );
// Add change record.
GuiEditorProfileChangeManager.registerEdit( %object, %fieldName, %arrayIndex, %oldValue );
%this.currentFieldEditAction.addToManager( GuiEditor.getUndoManager() );
%this.currentFieldEditAction = "";
GuiEditor.updateUndoMenu();
GuiEditor.setProfileDirty( %object, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onInspectorDiscardFieldModification( %this )
{
%this.currentFieldEditAction.undo();
%this.currentFieldEditAction.delete();
%this.currentFieldEditAction = "";
}
//=============================================================================================
// GuiEditorProfileChangeManager.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function GuiEditorProfileChangeManager::registerEdit( %this, %profile, %fieldName, %arrayIndex, %oldValue )
{
// Early-out if we already have a registered edit on the same field.
foreach( %obj in %this )
{
if( %obj.profile != %profile )
continue;
if( %obj.fieldName $= %fieldName
&& %obj.arrayIndex $= %arrayIndex )
return;
}
// Create a new change record.
new ScriptObject()
{
parentGroup = %this;
profile = %profile;
fieldName = %fieldName;
arrayIndex = %arrayIndex;
oldValue = %oldValue;
};
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileChangeManager::clearEdits( %this, %profile )
{
for( %i = 0; %i < %this.getCount(); %i ++ )
{
%obj = %this.getObject( %i );
if( %obj.profile != %profile )
continue;
%obj.delete();
%i --;
}
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileChangeManager::revertEdits( %this, %profile )
{
for( %i = 0; %i < %this.getCount(); %i ++ )
{
%obj = %this.getObject( %i );
if( %obj.profile != %profile )
continue;
%profile.setFieldValue( %obj.fieldName, %obj.oldValue, %obj.arrayIndex );
%obj.delete();
%i --;
}
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileChangeManager::getEdits( %this, %profile )
{
%set = new SimSet();
foreach( %obj in %this )
if( %obj.profile == %profile )
%set.add( %obj );
return %set;
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org.
// ****************************************************************
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Collections.Specialized;
using NUnit.Core.Filters;
using System.Reflection;
namespace NUnit.Core
{
/// <summary>
/// SimpleTestRunner is the simplest direct-running TestRunner. It
/// passes the event listener interface that is provided on to the tests
/// to use directly and does nothing to redirect text output. Both
/// Run and BeginRun are actually synchronous, although the client
/// can usually ignore this. BeginRun + EndRun operates as expected.
/// </summary>
public class SimpleTestRunner : MarshalByRefObject, TestRunner
{
static Logger log = InternalTrace.GetLogger(typeof(SimpleTestRunner));
#region Instance Variables
/// <summary>
/// Identifier for this runner. Must be unique among all
/// active runners in order to locate tests. Default
/// value of 0 is adequate in applications with a single
/// runner or a non-branching chain of runners.
/// </summary>
private int runnerID = 0;
/// <summary>
/// The loaded test suite
/// </summary>
private Test test;
/// <summary>
/// The builder we use to load tests, created for each load
/// </summary>
private TestSuiteBuilder builder;
/// <summary>
/// Results from the last test run
/// </summary>
private TestResult testResult;
/// <summary>
/// The thread on which Run was called. Set to the
/// current thread while a run is in process.
/// </summary>
private Thread runThread;
#endregion
#region Constructor
public SimpleTestRunner() : this( 0 ) { }
public SimpleTestRunner( int runnerID )
{
this.runnerID = runnerID;
}
#endregion
#region Properties
public virtual int ID
{
get { return runnerID; }
}
public IList AssemblyInfo
{
get { return builder.AssemblyInfo; }
}
public ITest Test
{
get { return test == null ? null : new TestNode( test ); }
}
/// <summary>
/// Results from the last test run
/// </summary>
public TestResult TestResult
{
get { return testResult; }
}
public virtual bool Running
{
get { return runThread != null && runThread.IsAlive; }
}
#endregion
#region Methods for Loading Tests
/// <summary>
/// Load a TestPackage
/// </summary>
/// <param name="package">The package to be loaded</param>
/// <returns>True on success, false on failure</returns>
public bool Load( TestPackage package )
{
log.Debug("Loading package " + package.Name);
this.builder = new TestSuiteBuilder();
this.test = builder.Build( package );
if ( test == null ) return false;
test.SetRunnerID( this.runnerID, true );
return true;
}
/// <summary>
/// Unload all tests previously loaded
/// </summary>
public void Unload()
{
log.Debug("Unloading");
this.test = null; // All for now
}
#endregion
#region CountTestCases
public int CountTestCases( ITestFilter filter )
{
return test.CountTestCases( filter );
}
#endregion
#region Methods for Running Tests
public virtual TestResult Run( EventListener listener )
{
return Run( listener, TestFilter.Empty );
}
public virtual TestResult Run( EventListener listener, ITestFilter filter )
{
try
{
log.Debug("Starting test run");
// Take note of the fact that we are running
this.runThread = Thread.CurrentThread;
listener.RunStarted( this.Test.TestName.FullName, test.CountTestCases( filter ) );
testResult = test.Run( listener, filter );
// Signal that we are done
listener.RunFinished( testResult );
log.Debug("Test run complete");
// Return result array
return testResult;
}
catch( Exception exception )
{
// Signal that we finished with an exception
listener.RunFinished( exception );
// Rethrow - should we do this?
throw;
}
finally
{
runThread = null;
}
}
public void BeginRun( EventListener listener )
{
testResult = this.Run( listener );
}
public void BeginRun( EventListener listener, ITestFilter filter )
{
testResult = this.Run( listener, filter );
}
public virtual TestResult EndRun()
{
return TestResult;
}
/// <summary>
/// Wait is a NOP for SimpleTestRunner
/// </summary>
public virtual void Wait()
{
}
public virtual void CancelRun()
{
if (this.runThread != null)
{
// Cancel Synchronous run only if on another thread
if ( runThread == Thread.CurrentThread )
throw new InvalidOperationException( "May not CancelRun on same thread that is running the test" );
// Make a copy of runThread, which will be set to
// null when the thread terminates.
Thread cancelThread = this.runThread;
// Tell the thread to abort
this.runThread.Abort();
// Wake up the thread if necessary
// Figure out if we need to do an interupt
if ( (cancelThread.ThreadState & ThreadState.WaitSleepJoin ) != 0 )
cancelThread.Interrupt();
}
}
#endregion
#region InitializeLifetimeService Override
public override object InitializeLifetimeService()
{
return null;
}
#endregion
#region IDisposable Members
public void Dispose()
{
Unload();
}
#endregion
}
}
| |
//! \file MalieEncryption.cs
//! \date Tue Jun 06 20:38:57 2017
//! \brief Malie System encryption implementation.
//
// Copyright (C) 2017 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.IO;
using GameRes.Cryptography;
using GameRes.Utility;
namespace GameRes.Formats.Malie
{
public interface IMalieDecryptor
{
void DecryptBlock (long block_offset, byte[] buffer, int index);
}
public class CamelliaDecryptor : IMalieDecryptor
{
Camellia m_enc;
public CamelliaDecryptor (uint[] key)
{
m_enc = new Camellia (key);
}
public void DecryptBlock (long block_offset, byte[] buffer, int index)
{
m_enc.DecryptBlock (block_offset, buffer, index);
}
}
public class CfiDecryptor : IMalieDecryptor
{
byte[] m_key;
uint[] m_rotate_key;
public CfiDecryptor (byte[] key, uint[] rotate_key)
{
m_key = key;
m_rotate_key = rotate_key;
}
public void DecryptBlock (long block_offset, byte[] data, int index)
{
if (null == data)
throw new ArgumentNullException ("data");
if (index < 0 || index + 0x10 > data.Length)
throw new ArgumentOutOfRangeException ("index");
int offset = (int)block_offset;
int o = offset & 0xF;
byte first = data[index+o];
for (int i = 0; i < 0x10; ++i)
{
if (o != i)
data[index+i] ^= first;
}
offset >>= 4;
unsafe
{
fixed (byte* data8 = &data[index])
{
uint* data32 = (uint*)data8;
uint k = Binary.RotR (m_rotate_key[0], m_key[offset & 0x1F] ^ 0xA5);
data32[0] = Binary.RotR (data32[0] ^ k, m_key[(offset + 12) & 0x1F] ^ 0xA5);
k = Binary.RotL (m_rotate_key[1], m_key[(offset + 3) & 0x1F] ^ 0xA5);
data32[1] = Binary.RotL (data32[1] ^ k, m_key[(offset + 15) & 0x1F] ^ 0xA5);
k = Binary.RotR (m_rotate_key[2], m_key[(offset + 6) & 0x1F] ^ 0xA5);
data32[2] = Binary.RotR (data32[2] ^ k, m_key[(offset - 14) & 0x1F] ^ 0xA5);
k = Binary.RotL (m_rotate_key[3], m_key[(offset + 9) & 0x1F] ^ 0xA5);
data32[3] = Binary.RotL (data32[3] ^ k, m_key[(offset - 11) & 0x1F] ^ 0xA5);
}
}
}
}
internal class EncryptedStream : Stream
{
ArcView.Frame m_view;
IMalieDecryptor m_dec;
long m_max_offset;
long m_position = 0;
byte[] m_current_block = new byte[BlockLength];
int m_current_block_length = 0;
long m_current_block_position = 0;
public const int BlockLength = 0x1000;
public IMalieDecryptor Decryptor { get { return m_dec; } }
public EncryptedStream (ArcView mmap, IMalieDecryptor decryptor)
{
m_view = mmap.CreateFrame();
m_dec = decryptor;
m_max_offset = mmap.MaxOffset;
}
public override int Read (byte[] buf, int index, int count)
{
int total_read = 0;
bool refill_buffer = !(m_position >= m_current_block_position && m_position < m_current_block_position + m_current_block_length);
while (count > 0 && m_position < m_max_offset)
{
if (refill_buffer)
{
m_current_block_position = m_position & ~((long)BlockLength-1);
FillBuffer();
}
int src_offset = (int)m_position & (BlockLength-1);
int available = Math.Min (count, m_current_block_length - src_offset);
Buffer.BlockCopy (m_current_block, src_offset, buf, index, available);
m_position += available;
total_read += available;
index += available;
count -= available;
refill_buffer = true;
}
return total_read;
}
private void FillBuffer ()
{
m_current_block_length = m_view.Read (m_current_block_position, m_current_block, 0, (uint)BlockLength);
for (int offset = 0; offset < m_current_block_length; offset += 0x10)
{
m_dec.DecryptBlock (m_current_block_position+offset, m_current_block, offset);
}
}
#region IO.Stream methods
public override bool CanRead { get { return !m_disposed; } }
public override bool CanWrite { get { return false; } }
public override bool CanSeek { get { return !m_disposed; } }
public override long Length { get { return m_max_offset; } }
public override long Position
{
get { return m_position; }
set { m_position = value; }
}
public override long Seek (long pos, SeekOrigin whence)
{
if (SeekOrigin.Current == whence)
m_position += pos;
else if (SeekOrigin.End == whence)
m_position = m_max_offset + pos;
else
m_position = pos;
return m_position;
}
public override void Write (byte[] buf, int index, int count)
{
throw new NotSupportedException();
}
public override void SetLength (long length)
{
throw new NotSupportedException();
}
public override void Flush ()
{
}
#endregion
#region IDisposable methods
bool m_disposed = false;
protected override void Dispose (bool disposing)
{
if (!m_disposed)
{
if (disposing)
m_view.Dispose();
m_disposed = true;
base.Dispose();
}
}
#endregion
}
}
| |
#region copyright
// Copyright (c) 2012, TIGWI
// All rights reserved.
// Distributed under BSD 2-Clause license
#endregion
namespace Tigwi.UI
{
using System;
using System.Collections.Generic;
using System.Linq;
using Tigwi.Storage.Library;
/// <summary>
/// A mock implementation of IStorage. Not tested, there can be bugs !
/// </summary>
public class MockStorage : IStorage
{
public MockStorage()
{
this.UserStorage = new MockUserStorage(this);
this.AccountStorage = new MockAccountStorage(this);
this.ListStorage = new MockListStorage(this);
this.MsgStorage = new MockMsgStorage(this);
}
#region Implementation of IStorage
public IUserStorage User
{
get
{
return this.UserStorage;
}
}
public IAccountStorage Account
{
get
{
return this.AccountStorage;
}
}
public IListStorage List
{
get
{
return this.ListStorage;
}
}
public IMsgStorage Msg
{
get
{
return this.MsgStorage;
}
}
#endregion
protected MockUserStorage UserStorage { get; set; }
protected MockAccountStorage AccountStorage { get; set; }
protected MockListStorage ListStorage { get; set; }
protected MockMsgStorage MsgStorage { get; set; }
protected class MockUser : IUserInfo
{
public Guid Id { get; set; }
#region Implementation of IUserInfo
public string Login { get; set; }
public string Avatar { get; set; }
public string Email { get; set; }
public Guid MainAccountId { get; set; }
#endregion
public ISet<Guid> Accounts { get; set; }
public ISet<string> OpenIdUri { get; set; }
public IDictionary<Guid, string> ApiKey { get; set; }
public byte[] Password { get; set; }
}
protected class MockUserStorage : IUserStorage
{
public MockUserStorage(MockStorage storage)
{
this.Storage = storage;
this.IdFromLogin = new Dictionary<string, Guid>();
this.UserFromId = new Dictionary<Guid, MockUser>();
this.IdFromOpenId = new Dictionary<string, Guid>();
this.IdFromApiKey = new Dictionary<Guid, Guid>();
}
protected IDictionary<string, Guid> IdFromLogin { get; set; }
protected IDictionary<Guid, MockUser> UserFromId { get; set; }
protected IDictionary<string, Guid> IdFromOpenId { get; set; }
protected IDictionary<Guid, Guid> IdFromApiKey { get; set; }
protected MockStorage Storage { get; set; }
#region Implementation of IUserStorage
public Guid GetId(string login)
{
Guid guid;
if (!this.IdFromLogin.TryGetValue(login, out guid))
{
throw new UserNotFound();
}
return guid;
}
public IUserInfo GetInfo(Guid userId)
{
return this.GetMock(userId);
}
public MockUser GetMock(Guid userId)
{
MockUser user;
if (!this.UserFromId.TryGetValue(userId, out user))
{
throw new UserNotFound();
}
return user;
}
public void SetInfo(Guid userId, string email, Guid mainAccountId)
{
this.GetMock(userId).Email = email;
this.GetMock(userId).MainAccountId = mainAccountId;
}
public HashSet<Guid> GetAccounts(Guid userId)
{
return new HashSet<Guid>(this.GetMock(userId).Accounts);
}
public Guid Create(string login, string email, byte[] password)
{
if (this.IdFromLogin.ContainsKey(login))
{
throw new UserAlreadyExists();
}
var id = Guid.NewGuid();
this.IdFromLogin.Add(login, id);
this.UserFromId.Add(
id,
new MockUser
{
Accounts = new HashSet<Guid>(),
Avatar = string.Empty,
Email = email,
MainAccountId = new Guid(),
Login = login,
Id = id,
Password = password,
OpenIdUri = new HashSet<string>(),
ApiKey = new Dictionary<Guid, string>()
});
return id;
}
public void Delete(Guid userId)
{
MockUser user;
if (!this.UserFromId.TryGetValue(userId, out user))
{
return;
}
if (user.Accounts.Select(id => this.Storage.AccountStorage.GetAdminId(id)).Any(admin => admin == userId))
{
throw new UserIsAdmin();
}
foreach (var account in user.Accounts.Select(this.Storage.AccountStorage.GetMock))
{
account.Users.Remove(userId);
}
this.IdFromLogin.Remove(user.Login);
this.UserFromId.Remove(userId);
foreach (var oidUri in user.OpenIdUri)
{
this.IdFromOpenId.Remove(oidUri);
}
}
public Guid GetIdByOpenIdUri(string openIdUri)
{
Guid id;
if (!this.IdFromOpenId.TryGetValue(openIdUri, out id))
{
throw new UserNotFound();
}
return id;
}
public void AssociateOpenIdUri(Guid userId, string openIdUri)
{
if (this.IdFromOpenId.ContainsKey(openIdUri))
{
throw new OpenIdUriDuplicated();
}
var user = this.GetMock(userId);
user.OpenIdUri.Add(openIdUri);
this.IdFromOpenId.Add(openIdUri, userId);
}
public HashSet<string> ListOpenIdUris(Guid userId)
{
return new HashSet<string>(this.GetMock(userId).OpenIdUri);
}
public void DeassociateOpenIdUri(Guid userId, string openIdUri)
{
Guid associated;
this.GetMock(userId).OpenIdUri.Remove(openIdUri);
if (!this.IdFromOpenId.TryGetValue(openIdUri, out associated))
{
return;
}
if (associated != userId)
{
throw new OpenIdUriNotAssociated();
}
this.IdFromOpenId.Remove(openIdUri);
}
public Guid GetIdByApiKey(Guid apiKey)
{
Guid id;
if (!this.IdFromApiKey.TryGetValue(apiKey, out id))
{
throw new UserNotFound();
}
return id;
}
public Guid GenerateApiKey(Guid userId, string applicationName)
{
Guid apiKey = Guid.NewGuid();
var user = this.GetMock(userId);
user.ApiKey.Add(apiKey, applicationName);
this.IdFromApiKey.Add(apiKey, userId);
return apiKey;
}
public Dictionary<Guid, string> ListApiKeys(Guid userId)
{
return new Dictionary<Guid, string>(this.GetMock(userId).ApiKey);
}
public void DeactivateApiKey(Guid userId, Guid apiKey)
{
Guid associated;
this.GetMock(userId).ApiKey.Remove(apiKey);
if (!this.IdFromApiKey.TryGetValue(apiKey, out associated))
{
return;
}
this.IdFromApiKey.Remove(apiKey);
}
public byte[] GetPassword(Guid userId)
{
return this.GetMock(userId).Password;
}
public void SetPassword(Guid userId, byte[] password)
{
this.GetMock(userId).Password = password;
}
#endregion
}
protected class MockAccount : IAccountInfo
{
#region Implementation of IAccountInfo
public string Name { get; set; }
public string Description { get; set; }
#endregion
public ISet<Guid> Users { get; set; }
public Guid Admin { get; set; }
public Guid PersonalList { get; set; }
public ISet<Guid> AllFollowedLists { get; set; }
public ISet<Guid> PublicFollowedLists { get; set; }
public ISet<Guid> AllOwnedLists { get; set; }
public ISet<Guid> PublicOwnedLists { get; set; }
public ISet<Guid> MemberOfLists { get; set; }
public ISet<Guid> Messages { get; set; }
public ISet<Guid> TaggedMessages { get; set; }
}
protected class MockAccountStorage : IAccountStorage
{
public MockAccountStorage(MockStorage storage)
{
this.Storage = storage;
this.IdFromName = new Dictionary<string, Guid>();
this.AccountFromId = new Dictionary<Guid, MockAccount>();
}
public IDictionary<string, Guid> IdFromName { get; set; }
public IDictionary<Guid, MockAccount> AccountFromId { get; set; }
protected MockStorage Storage { get; set; }
#region Implementation of IAccountStorage
public Guid GetId(string name)
{
Guid id;
if (!this.IdFromName.TryGetValue(name, out id))
{
throw new AccountNotFound();
}
return id;
}
public IAccountInfo GetInfo(Guid accountId)
{
return this.GetMock(accountId);
}
public MockAccount GetMock(Guid accountId)
{
MockAccount account;
if (!this.AccountFromId.TryGetValue(accountId, out account))
{
throw new AccountNotFound();
}
return account;
}
public void SetInfo(Guid accountId, string description)
{
this.GetMock(accountId).Description = description;
}
public HashSet<Guid> GetUsers(Guid accountId)
{
return new HashSet<Guid>(this.GetMock(accountId).Users);
}
public Guid GetAdminId(Guid accountId)
{
return this.GetMock(accountId).Admin;
}
public void SetAdminId(Guid accountId, Guid userId)
{
this.GetMock(accountId).Admin = userId;
}
public void Add(Guid accountId, Guid userId)
{
var account = this.GetMock(accountId);
var user = this.Storage.UserStorage.GetMock(userId);
account.Users.Add(userId);
user.Accounts.Add(accountId);
}
public void Remove(Guid accountId, Guid userId)
{
try
{
var account = this.GetMock(accountId);
var user = this.Storage.UserStorage.GetMock(userId);
if (account.Admin == user.Id)
{
throw new UserIsAdmin();
}
account.Users.Remove(userId);
user.Accounts.Remove(accountId);
}
catch (UserNotFound)
{
}
catch (AccountNotFound)
{
}
}
public Guid Create(Guid adminId, string name, string description, bool bypassNameReservation = false)
{
var user = this.Storage.UserStorage.GetMock(adminId);
if (this.IdFromName.ContainsKey(name))
{
throw new AccountAlreadyExists();
}
var id = Guid.NewGuid();
user.Accounts.Add(id);
this.IdFromName.Add(name, id);
var personalList = new MockList
{
Description = "Personal list of " + name,
Followers = new HashSet<Guid> { id },
Name = name,
IsPersonnal = true,
// TODO: ?
IsPrivate = true,
Members = new HashSet<Guid> { id },
Owner = id,
Messages = new List<Guid>()
};
this.Storage.ListStorage.ListFromId.Add(id, personalList);
var account = new MockAccount
{
Admin = adminId,
Description = description,
Name = name,
Users = new HashSet<Guid> { adminId },
// TODO: Is the personal list here ?
AllFollowedLists = new HashSet<Guid> { id },
AllOwnedLists = new HashSet<Guid> { id },
MemberOfLists = new HashSet<Guid> { id },
PersonalList = id,
PublicFollowedLists = new HashSet<Guid>(),
Messages = new HashSet<Guid>(),
TaggedMessages = new HashSet<Guid>(),
PublicOwnedLists = new HashSet<Guid>()
};
this.AccountFromId.Add(id, account);
return id;
}
public void Delete(Guid accountId)
{
try
{
var account = this.GetMock(accountId);
foreach (var userId in account.Users)
{
this.Storage.UserStorage.GetMock(userId).Accounts.Remove(accountId);
}
foreach (var msgId in account.Messages)
{
this.Storage.MsgStorage.Remove(msgId);
}
foreach (var taggedMsg in account.TaggedMessages)
{
this.Storage.MsgStorage.GetMock(taggedMsg).TaggedBy.Remove(accountId);
}
foreach (var listId in account.AllFollowedLists)
{
try
{
this.Storage.ListStorage.Unfollow(listId, accountId);
}
catch (AccountIsOwner)
{
}
}
// Choosing the easy way
account.AllOwnedLists.Add(account.PersonalList);
foreach (var listId in account.AllOwnedLists)
{
this.Storage.ListStorage.Remove(listId, accountId);
}
this.IdFromName.Remove(account.Name);
this.AccountFromId.Remove(accountId);
}
catch (AccountNotFound)
{
}
}
public bool ReserveAccountName(string accountName)
{
return !this.IdFromName.ContainsKey(accountName);
}
public HashSet<string> Autocompletion(string nameBegining, int maxNameNumber)
{
throw new NotImplementedException("Autocompletion has not been implemented in MockStorage");
}
#endregion
}
protected class MockList : IListInfo
{
#region Implementation of IListInfo
public string Name { get; set; }
public string Description { get; set; }
public bool IsPrivate { get; set; }
public bool IsPersonnal { get; set; }
#endregion
public Guid Owner { get; set; }
public ISet<Guid> Members { get; set; }
public ISet<Guid> Followers { get; set; }
public IList<Guid> Messages { get; set; }
}
protected class MockListStorage : IListStorage
{
public MockListStorage(MockStorage storage)
{
this.Storage = storage;
this.ListFromId = new Dictionary<Guid, MockList>();
}
public IDictionary<Guid, MockList> ListFromId { get; set; }
protected MockStorage Storage { get; set; }
#region Implementation of IListStorage
public IListInfo GetInfo(Guid listId)
{
return this.GetMock(listId);
}
public MockList GetMock(Guid listId)
{
MockList list;
if (!this.ListFromId.TryGetValue(listId, out list))
{
throw new ListNotFound();
}
return list;
}
public void SetInfo(Guid listId, string name, string description, bool isPrivate)
{
var list = this.GetMock(listId);
if (list.IsPersonnal)
{
throw new IsPersonnalList();
}
list.Name = name;
list.Description = description;
if (isPrivate == list.IsPrivate)
{
return;
}
list.IsPrivate = isPrivate;
MockAccount owner = this.Storage.AccountStorage.GetMock(list.Owner);
if (isPrivate)
{
owner.PublicOwnedLists.Remove(listId);
}
else
{
owner.PublicOwnedLists.Add(listId);
}
foreach (var accountId in list.Followers)
{
var account = this.Storage.AccountStorage.GetMock(accountId);
if (isPrivate)
{
account.PublicFollowedLists.Remove(listId);
if (!list.Members.Contains(accountId))
{
account.AllFollowedLists.Remove(listId);
}
list.Followers.IntersectWith(list.Members);
}
else
{
account.PublicFollowedLists.Add(listId);
}
}
}
public Guid GetOwner(Guid listId)
{
return this.GetMock(listId).Owner;
}
public Guid GetPersonalList(Guid accountId)
{
return this.Storage.AccountStorage.GetMock(accountId).PersonalList;
}
public Guid Create(Guid ownerId, string name, string description, bool isPrivate)
{
var account = this.Storage.AccountStorage.GetMock(ownerId);
var list = new MockList
{
Description = description,
IsPersonnal = false,
IsPrivate = isPrivate,
Name = name,
Owner = ownerId,
Members = new HashSet<Guid> { ownerId },
Followers = new HashSet<Guid> { ownerId },
Messages = new List<Guid>()
};
var id = Guid.NewGuid();
account.AllFollowedLists.Add(id);
if (!isPrivate)
{
account.PublicOwnedLists.Add(id);
account.PublicFollowedLists.Add(id);
}
account.AllOwnedLists.Add(id);
account.MemberOfLists.Add(id);
this.ListFromId.Add(id, list);
return id;
}
public void Delete(Guid id)
{
MockList list;
if (!this.ListFromId.TryGetValue(id, out list))
{
return;
}
if (list.IsPersonnal)
{
throw new IsPersonnalList();
}
foreach (var follower in list.Followers.Select(followerId => this.Storage.AccountStorage.GetMock(followerId)))
{
follower.AllFollowedLists.Remove(id);
follower.PublicFollowedLists.Remove(id);
}
foreach (var member in list.Members.Select(memberId => this.Storage.AccountStorage.GetMock(memberId)))
{
member.MemberOfLists.Remove(id);
}
var owner = this.Storage.AccountStorage.GetMock(list.Owner);
owner.AllOwnedLists.Remove(id);
owner.PublicOwnedLists.Remove(id);
this.ListFromId.Remove(id);
}
public void Follow(Guid listId, Guid accountId)
{
var account = this.Storage.AccountStorage.GetMock(accountId);
var list = this.GetMock(listId);
list.Followers.Add(accountId);
account.AllFollowedLists.Add(listId);
if (!list.IsPrivate)
{
account.PublicFollowedLists.Add(listId);
}
}
public void Unfollow(Guid listId, Guid accountId)
{
var account = this.Storage.AccountStorage.GetMock(accountId);
var list = this.GetMock(listId);
if (accountId == list.Owner)
{
throw new AccountIsOwner();
}
list.Followers.Remove(accountId);
account.AllFollowedLists.Remove(listId);
account.PublicFollowedLists.Remove(listId);
}
public HashSet<Guid> GetAccounts(Guid listId)
{
return new HashSet<Guid>(this.GetMock(listId).Members);
}
public void SetMain(Guid listId, Guid accountId, bool isMain)
{
throw new NotImplementedException();
}
public HashSet<Guid> GetMainAccounts(Guid listId)
{
throw new NotImplementedException();
}
public void Add(Guid listId, Guid accountId)
{
var account = this.Storage.AccountStorage.GetMock(accountId);
var list = this.GetMock(listId);
list.Members.Add(accountId);
account.MemberOfLists.Add(listId);
foreach (var msg in account.Messages)
{
list.Messages.Add(msg);
}
list.Messages = new List<Guid>(list.Messages.OrderBy(msg => this.Storage.MsgStorage.GetMock(msg).Date));
}
public void Remove(Guid listId, Guid accountId)
{
var account = this.Storage.AccountStorage.GetMock(accountId);
var list = this.GetMock(listId);
account.MemberOfLists.Remove(listId);
list.Members.Remove(accountId);
foreach (var msg in account.Messages)
{
list.Messages.Remove(msg);
}
}
public HashSet<Guid> GetAccountOwnedLists(Guid accountId, bool withPrivate)
{
return
new HashSet<Guid>(
withPrivate
? this.Storage.AccountStorage.GetMock(accountId).AllOwnedLists
: this.Storage.AccountStorage.GetMock(accountId).PublicOwnedLists);
}
public HashSet<Guid> GetAccountFollowedLists(Guid accountId, bool withPrivate)
{
return
new HashSet<Guid>(
withPrivate
? this.Storage.AccountStorage.GetMock(accountId).AllFollowedLists
: this.Storage.AccountStorage.GetMock(accountId).PublicFollowedLists);
}
public HashSet<Guid> GetFollowingLists(Guid accountId)
{
return new HashSet<Guid>(this.Storage.AccountStorage.GetMock(accountId).MemberOfLists);
}
public HashSet<Guid> GetFollowingAccounts(Guid listId)
{
return new HashSet<Guid>(this.GetMock(listId).Followers);
}
#endregion
}
protected class MockMsg : IMessage
{
#region Implementation of IMessage
public Guid Id { get; set; }
public Guid PosterId { get; set; }
public string PosterName { get; set; }
public string PosterAvatar { get; set; }
public DateTime Date { get; set; }
public string Content { get; set; }
#endregion
public ISet<Guid> TaggedBy { get; set; }
}
protected class MockMsgStorage : IMsgStorage
{
public MockMsgStorage(MockStorage storage)
{
this.Storage = storage;
this.MsgFromId = new Dictionary<Guid, MockMsg>();
}
public IDictionary<Guid, MockMsg> MsgFromId { get; set; }
protected MockStorage Storage { get; set; }
public MockMsg GetMock(Guid msgId)
{
MockMsg msg;
if (!this.MsgFromId.TryGetValue(msgId, out msg))
{
throw new MessageNotFound();
}
return msg;
}
#region Implementation of IMsgStorage
public IMessage GetMessage(Guid messageId)
{
throw new NotImplementedException();
}
public List<IMessage> GetListsMsgFrom(HashSet<Guid> listsId, DateTime firstMsgDate, int msgNumber)
{
var messages = new List<IMessage>();
foreach (var listId in listsId)
{
messages.AddRange(
this.Storage.ListStorage.GetMock(listId).Messages.Select(this.GetMock).Where(
msg => msg.Date > firstMsgDate));
}
messages.Sort((msg1, msg2) => DateTime.Compare(msg1.Date, msg2.Date));
return messages.Distinct().Take(msgNumber).ToList();
}
public List<IMessage> GetListsMsgTo(HashSet<Guid> listsId, DateTime lastMsgDate, int msgNumber)
{
var messages = new List<IMessage>();
foreach (var listId in listsId)
{
messages.AddRange(
this.Storage.ListStorage.GetMock(listId).Messages.Select(this.GetMock).Where(
msg => msg.Date < lastMsgDate));
}
// Note the reversing of the parameters because we supposedly want the *lasts* messages first
messages.Sort((msg1, msg2) => DateTime.Compare(msg2.Date, msg1.Date));
return messages.Distinct().Take(msgNumber).ToList();
}
public void Tag(Guid accountId, Guid msgId)
{
var account = this.Storage.AccountStorage.GetMock(accountId);
var msg = this.GetMock(msgId);
msg.TaggedBy.Add(accountId);
account.TaggedMessages.Add(msgId);
}
public void Untag(Guid accoundId, Guid msgId)
{
try
{
var account = this.Storage.AccountStorage.GetMock(accoundId);
var msg = this.GetMock(msgId);
msg.TaggedBy.Remove(accoundId);
account.TaggedMessages.Remove(msgId);
}
catch (AccountNotFound)
{
}
catch (MessageNotFound)
{
}
}
public List<IMessage> GetTaggedFrom(Guid accoundId, DateTime firstMsgDate, int msgNumber)
{
var listsId = this.Storage.AccountStorage.GetMock(accoundId).TaggedMessages;
var messages = new List<IMessage>();
foreach (var listId in listsId)
{
messages.AddRange(
this.Storage.ListStorage.GetMock(listId).Messages.Select(this.GetMock).Where(
msg => msg.Date > firstMsgDate));
}
messages.Sort((msg1, msg2) => DateTime.Compare(msg1.Date, msg2.Date));
return messages.Take(msgNumber).ToList();
}
public List<IMessage> GetTaggedTo(Guid accountId, DateTime lastMsgDate, int msgNumber)
{
var listsId = this.Storage.AccountStorage.GetMock(accountId).TaggedMessages;
var messages = new List<IMessage>();
foreach (var listId in listsId)
{
messages.AddRange(
this.Storage.ListStorage.GetMock(listId).Messages.Select(this.GetMock).Where(
msg => msg.Date < lastMsgDate));
}
// Note the reversing of the parameters because we supposedly want the *lasts* messages first
messages.Sort((msg1, msg2) => DateTime.Compare(msg2.Date, msg1.Date));
return messages.Take(msgNumber).ToList();
}
public Guid Post(Guid accountId, string content)
{
var account = this.Storage.AccountStorage.GetMock(accountId);
var id = Guid.NewGuid();
var message = new MockMsg
{
Content = content,
Date = DateTime.Now,
Id = id,
PosterAvatar = string.Empty,
PosterId = accountId,
PosterName = account.Name,
TaggedBy = new HashSet<Guid>()
};
this.MsgFromId.Add(id, message);
account.Messages.Add(id);
foreach (var list in account.MemberOfLists.Select(this.Storage.ListStorage.GetMock))
{
list.Messages.Add(id);
list.Messages =
new List<Guid>(list.Messages.OrderBy(msgId => this.Storage.MsgStorage.GetMock(msgId).Date));
}
return id;
}
public Guid Copy(Guid accountId, Guid msgId)
{
// TODO: must *not* be implemented until we know what this really means
throw new NotImplementedException();
}
public void Remove(Guid id)
{
var msg = this.GetMock(id);
var poster = this.Storage.AccountStorage.GetMock(msg.PosterId);
poster.Messages.Remove(id);
foreach (var list in poster.MemberOfLists.Select(this.Storage.ListStorage.GetMock))
{
list.Messages.Remove(id);
}
foreach (var tagger in msg.TaggedBy.Select(this.Storage.AccountStorage.GetMock))
{
tagger.TaggedMessages.Remove(id);
}
}
public List<IMessage> GetLastMessages()
{
throw new NotImplementedException();
}
#endregion
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// UseTax
/// </summary>
[DataContract]
public partial class UseTax : IEquatable<UseTax>
{
/// <summary>
/// Initializes a new instance of the <see cref="UseTax" /> class.
/// </summary>
/// <param name="TotalTaxRate">TotalTaxRate.</param>
/// <param name="TotalTaxAmount">TotalTaxAmount.</param>
/// <param name="StateTaxRate">StateTaxRate.</param>
/// <param name="StateTaxAmount">StateTaxAmount.</param>
/// <param name="CountyTaxRate">CountyTaxRate.</param>
/// <param name="CountyTaxAmount">CountyTaxAmount.</param>
/// <param name="MunicipalTaxRate">MunicipalTaxRate.</param>
/// <param name="MunicipalTaxAmount">MunicipalTaxAmount.</param>
/// <param name="SpdsTax">SpdsTax.</param>
/// <param name="SpecialTaxRulesApplied">SpecialTaxRulesApplied (default to false).</param>
/// <param name="SpecialTaxRulesDescriptor">SpecialTaxRulesDescriptor.</param>
public UseTax(double? TotalTaxRate = null, double? TotalTaxAmount = null, double? StateTaxRate = null, double? StateTaxAmount = null, double? CountyTaxRate = null, double? CountyTaxAmount = null, double? MunicipalTaxRate = null, double? MunicipalTaxAmount = null, List<SpecialPurposeDistrictTax> SpdsTax = null, bool? SpecialTaxRulesApplied = null, string SpecialTaxRulesDescriptor = null)
{
this.TotalTaxRate = TotalTaxRate;
this.TotalTaxAmount = TotalTaxAmount;
this.StateTaxRate = StateTaxRate;
this.StateTaxAmount = StateTaxAmount;
this.CountyTaxRate = CountyTaxRate;
this.CountyTaxAmount = CountyTaxAmount;
this.MunicipalTaxRate = MunicipalTaxRate;
this.MunicipalTaxAmount = MunicipalTaxAmount;
this.SpdsTax = SpdsTax;
// use default value if no "SpecialTaxRulesApplied" provided
if (SpecialTaxRulesApplied == null)
{
this.SpecialTaxRulesApplied = false;
}
else
{
this.SpecialTaxRulesApplied = SpecialTaxRulesApplied;
}
this.SpecialTaxRulesDescriptor = SpecialTaxRulesDescriptor;
}
/// <summary>
/// Gets or Sets TotalTaxRate
/// </summary>
[DataMember(Name="totalTaxRate", EmitDefaultValue=false)]
public double? TotalTaxRate { get; set; }
/// <summary>
/// Gets or Sets TotalTaxAmount
/// </summary>
[DataMember(Name="totalTaxAmount", EmitDefaultValue=false)]
public double? TotalTaxAmount { get; set; }
/// <summary>
/// Gets or Sets StateTaxRate
/// </summary>
[DataMember(Name="stateTaxRate", EmitDefaultValue=false)]
public double? StateTaxRate { get; set; }
/// <summary>
/// Gets or Sets StateTaxAmount
/// </summary>
[DataMember(Name="stateTaxAmount", EmitDefaultValue=false)]
public double? StateTaxAmount { get; set; }
/// <summary>
/// Gets or Sets CountyTaxRate
/// </summary>
[DataMember(Name="countyTaxRate", EmitDefaultValue=false)]
public double? CountyTaxRate { get; set; }
/// <summary>
/// Gets or Sets CountyTaxAmount
/// </summary>
[DataMember(Name="countyTaxAmount", EmitDefaultValue=false)]
public double? CountyTaxAmount { get; set; }
/// <summary>
/// Gets or Sets MunicipalTaxRate
/// </summary>
[DataMember(Name="municipalTaxRate", EmitDefaultValue=false)]
public double? MunicipalTaxRate { get; set; }
/// <summary>
/// Gets or Sets MunicipalTaxAmount
/// </summary>
[DataMember(Name="municipalTaxAmount", EmitDefaultValue=false)]
public double? MunicipalTaxAmount { get; set; }
/// <summary>
/// Gets or Sets SpdsTax
/// </summary>
[DataMember(Name="spdsTax", EmitDefaultValue=false)]
public List<SpecialPurposeDistrictTax> SpdsTax { get; set; }
/// <summary>
/// Gets or Sets SpecialTaxRulesApplied
/// </summary>
[DataMember(Name="specialTaxRulesApplied", EmitDefaultValue=false)]
public bool? SpecialTaxRulesApplied { get; set; }
/// <summary>
/// Gets or Sets SpecialTaxRulesDescriptor
/// </summary>
[DataMember(Name="specialTaxRulesDescriptor", EmitDefaultValue=false)]
public string SpecialTaxRulesDescriptor { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UseTax {\n");
sb.Append(" TotalTaxRate: ").Append(TotalTaxRate).Append("\n");
sb.Append(" TotalTaxAmount: ").Append(TotalTaxAmount).Append("\n");
sb.Append(" StateTaxRate: ").Append(StateTaxRate).Append("\n");
sb.Append(" StateTaxAmount: ").Append(StateTaxAmount).Append("\n");
sb.Append(" CountyTaxRate: ").Append(CountyTaxRate).Append("\n");
sb.Append(" CountyTaxAmount: ").Append(CountyTaxAmount).Append("\n");
sb.Append(" MunicipalTaxRate: ").Append(MunicipalTaxRate).Append("\n");
sb.Append(" MunicipalTaxAmount: ").Append(MunicipalTaxAmount).Append("\n");
sb.Append(" SpdsTax: ").Append(SpdsTax).Append("\n");
sb.Append(" SpecialTaxRulesApplied: ").Append(SpecialTaxRulesApplied).Append("\n");
sb.Append(" SpecialTaxRulesDescriptor: ").Append(SpecialTaxRulesDescriptor).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as UseTax);
}
/// <summary>
/// Returns true if UseTax instances are equal
/// </summary>
/// <param name="other">Instance of UseTax to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UseTax other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.TotalTaxRate == other.TotalTaxRate ||
this.TotalTaxRate != null &&
this.TotalTaxRate.Equals(other.TotalTaxRate)
) &&
(
this.TotalTaxAmount == other.TotalTaxAmount ||
this.TotalTaxAmount != null &&
this.TotalTaxAmount.Equals(other.TotalTaxAmount)
) &&
(
this.StateTaxRate == other.StateTaxRate ||
this.StateTaxRate != null &&
this.StateTaxRate.Equals(other.StateTaxRate)
) &&
(
this.StateTaxAmount == other.StateTaxAmount ||
this.StateTaxAmount != null &&
this.StateTaxAmount.Equals(other.StateTaxAmount)
) &&
(
this.CountyTaxRate == other.CountyTaxRate ||
this.CountyTaxRate != null &&
this.CountyTaxRate.Equals(other.CountyTaxRate)
) &&
(
this.CountyTaxAmount == other.CountyTaxAmount ||
this.CountyTaxAmount != null &&
this.CountyTaxAmount.Equals(other.CountyTaxAmount)
) &&
(
this.MunicipalTaxRate == other.MunicipalTaxRate ||
this.MunicipalTaxRate != null &&
this.MunicipalTaxRate.Equals(other.MunicipalTaxRate)
) &&
(
this.MunicipalTaxAmount == other.MunicipalTaxAmount ||
this.MunicipalTaxAmount != null &&
this.MunicipalTaxAmount.Equals(other.MunicipalTaxAmount)
) &&
(
this.SpdsTax == other.SpdsTax ||
this.SpdsTax != null &&
this.SpdsTax.SequenceEqual(other.SpdsTax)
) &&
(
this.SpecialTaxRulesApplied == other.SpecialTaxRulesApplied ||
this.SpecialTaxRulesApplied != null &&
this.SpecialTaxRulesApplied.Equals(other.SpecialTaxRulesApplied)
) &&
(
this.SpecialTaxRulesDescriptor == other.SpecialTaxRulesDescriptor ||
this.SpecialTaxRulesDescriptor != null &&
this.SpecialTaxRulesDescriptor.Equals(other.SpecialTaxRulesDescriptor)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.TotalTaxRate != null)
hash = hash * 59 + this.TotalTaxRate.GetHashCode();
if (this.TotalTaxAmount != null)
hash = hash * 59 + this.TotalTaxAmount.GetHashCode();
if (this.StateTaxRate != null)
hash = hash * 59 + this.StateTaxRate.GetHashCode();
if (this.StateTaxAmount != null)
hash = hash * 59 + this.StateTaxAmount.GetHashCode();
if (this.CountyTaxRate != null)
hash = hash * 59 + this.CountyTaxRate.GetHashCode();
if (this.CountyTaxAmount != null)
hash = hash * 59 + this.CountyTaxAmount.GetHashCode();
if (this.MunicipalTaxRate != null)
hash = hash * 59 + this.MunicipalTaxRate.GetHashCode();
if (this.MunicipalTaxAmount != null)
hash = hash * 59 + this.MunicipalTaxAmount.GetHashCode();
if (this.SpdsTax != null)
hash = hash * 59 + this.SpdsTax.GetHashCode();
if (this.SpecialTaxRulesApplied != null)
hash = hash * 59 + this.SpecialTaxRulesApplied.GetHashCode();
if (this.SpecialTaxRulesDescriptor != null)
hash = hash * 59 + this.SpecialTaxRulesDescriptor.GetHashCode();
return hash;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworkGatewayConnectionsOperations operations.
/// </summary>
public partial interface IVirtualNetworkGatewayConnectionsOperations
{
/// <summary>
/// Creates or updates a virtual network gateway connection in the
/// specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network gateway
/// connection operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified virtual network gateway connection by resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network Gateway connection.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the
/// virtual network gateway connection shared key for passed virtual
/// network gateway connection in the specified resource group through
/// Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway
/// connection Shared key operation throughNetwork resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectionSharedKey>> SetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Get VirtualNetworkGatewayConnectionSharedKey operation
/// retrieves information about the specified virtual network gateway
/// connection shared key through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection shared key name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectionSharedKey>> GetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List VirtualNetworkGatewayConnections operation retrieves all
/// the virtual network gateways connections created.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets
/// the virtual network gateway connection shared key for passed
/// virtual network gateway connection in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the begin reset virtual network gateway
/// connection shared key operation through network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectionResetSharedKey>> ResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network gateway connection in the
/// specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network gateway
/// connection operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network Gateway connection.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the
/// virtual network gateway connection shared key for passed virtual
/// network gateway connection in the specified resource group through
/// Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway
/// connection Shared key operation throughNetwork resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectionSharedKey>> BeginSetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets
/// the virtual network gateway connection shared key for passed
/// virtual network gateway connection in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the begin reset virtual network gateway
/// connection shared key operation through network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectionResetSharedKey>> BeginResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List VirtualNetworkGatewayConnections operation retrieves all
/// the virtual network gateways connections created.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Layout;
using Avalonia.VisualTree;
#nullable enable
namespace Avalonia.Interactivity
{
/// <summary>
/// Base class for objects that raise routed events.
/// </summary>
public class Interactive : Layoutable, IInteractive
{
private Dictionary<RoutedEvent, List<EventSubscription>>? _eventHandlers;
/// <summary>
/// Gets the interactive parent of the object for bubbling and tunneling events.
/// </summary>
IInteractive? IInteractive.InteractiveParent => ((IVisual)this).VisualParent as IInteractive;
/// <summary>
/// Adds a handler for the specified routed event.
/// </summary>
/// <param name="routedEvent">The routed event.</param>
/// <param name="handler">The handler.</param>
/// <param name="routes">The routing strategies to listen to.</param>
/// <param name="handledEventsToo">Whether handled events should also be listened for.</param>
public void AddHandler(
RoutedEvent routedEvent,
Delegate handler,
RoutingStrategies routes = RoutingStrategies.Direct | RoutingStrategies.Bubble,
bool handledEventsToo = false)
{
routedEvent = routedEvent ?? throw new ArgumentNullException(nameof(routedEvent));
handler = handler ?? throw new ArgumentNullException(nameof(handler));
var subscription = new EventSubscription(handler, routes, handledEventsToo);
AddEventSubscription(routedEvent, subscription);
}
/// <summary>
/// Adds a handler for the specified routed event.
/// </summary>
/// <typeparam name="TEventArgs">The type of the event's args.</typeparam>
/// <param name="routedEvent">The routed event.</param>
/// <param name="handler">The handler.</param>
/// <param name="routes">The routing strategies to listen to.</param>
/// <param name="handledEventsToo">Whether handled events should also be listened for.</param>
public void AddHandler<TEventArgs>(
RoutedEvent<TEventArgs> routedEvent,
EventHandler<TEventArgs> handler,
RoutingStrategies routes = RoutingStrategies.Direct | RoutingStrategies.Bubble,
bool handledEventsToo = false) where TEventArgs : RoutedEventArgs
{
routedEvent = routedEvent ?? throw new ArgumentNullException(nameof(routedEvent));
handler = handler ?? throw new ArgumentNullException(nameof(handler));
static void InvokeAdapter(Delegate baseHandler, object sender, RoutedEventArgs args)
{
var typedHandler = (EventHandler<TEventArgs>)baseHandler;
var typedArgs = (TEventArgs)args;
typedHandler(sender, typedArgs);
}
var subscription = new EventSubscription(handler, routes, handledEventsToo, (baseHandler, sender, args) => InvokeAdapter(baseHandler, sender, args));
AddEventSubscription(routedEvent, subscription);
}
/// <summary>
/// Removes a handler for the specified routed event.
/// </summary>
/// <param name="routedEvent">The routed event.</param>
/// <param name="handler">The handler.</param>
public void RemoveHandler(RoutedEvent routedEvent, Delegate handler)
{
routedEvent = routedEvent ?? throw new ArgumentNullException(nameof(routedEvent));
handler = handler ?? throw new ArgumentNullException(nameof(handler));
if (_eventHandlers is object &&
_eventHandlers.TryGetValue(routedEvent, out var subscriptions))
{
for (var i = subscriptions.Count - 1; i >= 0; i--)
{
if (subscriptions[i].Handler == handler)
{
subscriptions.RemoveAt(i);
}
}
}
}
/// <summary>
/// Removes a handler for the specified routed event.
/// </summary>
/// <typeparam name="TEventArgs">The type of the event's args.</typeparam>
/// <param name="routedEvent">The routed event.</param>
/// <param name="handler">The handler.</param>
public void RemoveHandler<TEventArgs>(RoutedEvent<TEventArgs> routedEvent, EventHandler<TEventArgs> handler)
where TEventArgs : RoutedEventArgs
{
RemoveHandler(routedEvent, (Delegate)handler);
}
/// <summary>
/// Raises a routed event.
/// </summary>
/// <param name="e">The event args.</param>
public void RaiseEvent(RoutedEventArgs e)
{
e = e ?? throw new ArgumentNullException(nameof(e));
if (e.RoutedEvent == null)
{
throw new ArgumentException("Cannot raise an event whose RoutedEvent is null.");
}
using var route = BuildEventRoute(e.RoutedEvent);
route.RaiseEvent(this, e);
}
void IInteractive.AddToEventRoute(RoutedEvent routedEvent, EventRoute route)
{
routedEvent = routedEvent ?? throw new ArgumentNullException(nameof(routedEvent));
route = route ?? throw new ArgumentNullException(nameof(route));
if (_eventHandlers != null &&
_eventHandlers.TryGetValue(routedEvent, out var subscriptions))
{
foreach (var sub in subscriptions)
{
route.Add(this, sub.Handler, sub.Routes, sub.HandledEventsToo, sub.InvokeAdapter);
}
}
}
/// <summary>
/// Builds an event route for a routed event.
/// </summary>
/// <param name="e">The routed event.</param>
/// <returns>An <see cref="EventRoute"/> describing the route.</returns>
/// <remarks>
/// Usually, calling <see cref="RaiseEvent(RoutedEventArgs)"/> is sufficient to raise a routed
/// event, however there are situations in which the construction of the event args is expensive
/// and should be avoided if there are no handlers for an event. In these cases you can call
/// this method to build the event route and check the <see cref="EventRoute.HasHandlers"/>
/// property to see if there are any handlers registered on the route. If there are, call
/// <see cref="EventRoute.RaiseEvent(IInteractive, RoutedEventArgs)"/> to raise the event.
/// </remarks>
protected EventRoute BuildEventRoute(RoutedEvent e)
{
e = e ?? throw new ArgumentNullException(nameof(e));
var result = new EventRoute(e);
var hasClassHandlers = e.HasRaisedSubscriptions;
if (e.RoutingStrategies.HasAllFlags(RoutingStrategies.Bubble) ||
e.RoutingStrategies.HasAllFlags(RoutingStrategies.Tunnel))
{
IInteractive? element = this;
while (element != null)
{
if (hasClassHandlers)
{
result.AddClassHandler(element);
}
element.AddToEventRoute(e, result);
element = element.InteractiveParent;
}
}
else
{
if (hasClassHandlers)
{
result.AddClassHandler(this);
}
((IInteractive)this).AddToEventRoute(e, result);
}
return result;
}
private void AddEventSubscription(RoutedEvent routedEvent, EventSubscription subscription)
{
_eventHandlers ??= new Dictionary<RoutedEvent, List<EventSubscription>>();
if (!_eventHandlers.TryGetValue(routedEvent, out var subscriptions))
{
subscriptions = new List<EventSubscription>();
_eventHandlers.Add(routedEvent, subscriptions);
}
subscriptions.Add(subscription);
}
private readonly struct EventSubscription
{
public EventSubscription(
Delegate handler,
RoutingStrategies routes,
bool handledEventsToo,
Action<Delegate, object, RoutedEventArgs>? invokeAdapter = null)
{
Handler = handler;
Routes = routes;
HandledEventsToo = handledEventsToo;
InvokeAdapter = invokeAdapter;
}
public Action<Delegate, object, RoutedEventArgs>? InvokeAdapter { get; }
public Delegate Handler { get; }
public RoutingStrategies Routes { get; }
public bool HandledEventsToo { get; }
}
}
}
| |
using KSP.Localization;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
namespace KERBALISM
{
public static class DevManager
{
public static void Devman(this Panel p, Vessel v)
{
// avoid corner-case when this is called in a lambda after scene changes
v = FlightGlobals.FindVessel(v.id);
// if vessel doesn't exist anymore, leave the panel empty
if (v == null) return;
// get data
VesselData vd = v.KerbalismData();
// if not a valid vessel, leave the panel empty
if (!vd.IsSimulated) return;
// set metadata
p.Title(Lib.BuildString(Lib.Ellipsis(v.vesselName, Styles.ScaleStringLength(20)), Lib.Color(Local.UI_devman, Lib.Kolor.LightGrey)));
p.Width(Styles.ScaleWidthFloat(355.0f));
p.paneltype = Panel.PanelType.scripts;
// time-out simulation
if (!Lib.IsControlUnit(v) && p.Timeout(vd)) return;
// get devices
List<Device> devices = Computer.GetModuleDevices(v);
int deviceCount = 0;
// direct control
if (script_index == 0)
{
// draw section title and desc
p.AddSection
(
Local.UI_devices,
Description(),
() => p.Prev(ref script_index, (int)ScriptType.last),
() => p.Next(ref script_index, (int)ScriptType.last),
false
);
bool hasVesselDeviceSection = false;
bool hasModuleDeviceSection = false;
// for each device
for (int i = devices.Count - 1; i >= 0; i--)
{
Device dev = devices[i];
dev.OnUpdate();
if (!dev.IsVisible) continue;
// create vessel device section if necessary
if (dev is VesselDevice)
{
if (!hasVesselDeviceSection)
{
p.AddSection(Local.DevManager_VESSELDEVICES);//"VESSEL DEVICES"
hasVesselDeviceSection = true;
}
}
// create module device section if necessary
else
{
if (!hasModuleDeviceSection)
{
p.AddSection(Local.DevManager_MODULEDEVICES);//"MODULE DEVICES"
hasModuleDeviceSection = true;
}
}
if (dev.PartId != 0u)
p.AddContent(dev.DisplayName, dev.Status, dev.Tooltip, dev.Toggle, () => Highlighter.Set(dev.PartId, Color.cyan));
else
p.AddContent(dev.DisplayName, dev.Status, dev.Tooltip, dev.Toggle);
if (dev.Icon != null)
p.SetLeftIcon(dev.Icon.texture, dev.Icon.tooltip, dev.Icon.onClick);
deviceCount++;
}
}
// script editor
else
{
// get script
ScriptType script_type = (ScriptType)script_index;
string script_name = Name().ToUpper();
Script script = v.KerbalismData().computer.Get(script_type);
// draw section title and desc
p.AddSection
(
script_name,
Description(),
() => p.Prev(ref script_index, (int)ScriptType.last),
() => p.Next(ref script_index, (int)ScriptType.last)
);
bool hasVesselDeviceSection = false;
bool hasModuleDeviceSection = false;
// for each device
for (int i = devices.Count - 1; i >= 0; i--)
{
Device dev = devices[i];
dev.OnUpdate();
if (!dev.IsVisible) continue;
// determine tribool state
int state = !script.states.ContainsKey(dev.Id)
? -1
: !script.states[dev.Id]
? 0
: 1;
// create vessel device section if necessary
if (dev is VesselDevice)
{
if (!hasVesselDeviceSection)
{
p.AddSection(Local.DevManager_VESSELDEVICES);//"VESSEL DEVICES"
hasVesselDeviceSection = true;
}
}
// create module device section if necessary
else
{
if (!hasModuleDeviceSection)
{
p.AddSection(Local.DevManager_MODULEDEVICES);//"MODULE DEVICES"
hasModuleDeviceSection = true;
}
}
// render device entry
p.AddContent
(
dev.DisplayName,
state == -1 ? Lib.Color(Local.UI_dontcare, Lib.Kolor.DarkGrey) : Lib.Color(state == 0, Local.Generic_OFF, Lib.Kolor.Yellow, Local.Generic_ON, Lib.Kolor.Green),
string.Empty,
() =>
{
switch (state)
{
case -1: script.Set(dev, true); break;
case 0: script.Set(dev, null); break;
case 1: script.Set(dev, false); break;
}
},
() => Highlighter.Set(dev.PartId, Color.cyan)
);
deviceCount++;
}
}
// no devices case
if (deviceCount == 0)
{
p.AddContent("<i>"+Local.DevManager_nodevices +"</i>");//no devices
}
}
// return short description of a script, or the time-out message
static string Name()
{
switch ((ScriptType)script_index)
{
case ScriptType.landed: return Local.DevManager_NameTabLanded;
case ScriptType.atmo: return Local.DevManager_NameTabAtmo;
case ScriptType.space: return Local.DevManager_NameTabSpace;
case ScriptType.sunlight: return Local.DevManager_NameTabSunlight;
case ScriptType.shadow: return Local.DevManager_NameTabShadow;
case ScriptType.power_high: return Local.DevManager_NameTabPowerHigh;
case ScriptType.power_low: return Local.DevManager_NameTabPowerLow;
case ScriptType.rad_high: return Local.DevManager_NameTabRadHigh;
case ScriptType.rad_low: return Local.DevManager_NameTabRadLow;
case ScriptType.linked: return Local.DevManager_NameTabLinked;
case ScriptType.unlinked: return Local.DevManager_NameTabUnlinked;
case ScriptType.eva_out: return Local.DevManager_NameTabEVAOut;
case ScriptType.eva_in: return Local.DevManager_NameTabEVAIn;
case ScriptType.action1: return Local.DevManager_NameTabAct1;
case ScriptType.action2: return Local.DevManager_NameTabAct2;
case ScriptType.action3: return Local.DevManager_NameTabAct3;
case ScriptType.action4: return Local.DevManager_NameTabAct4;
case ScriptType.action5: return Local.DevManager_NameTabAct5;
case ScriptType.drive_full: return Local.DevManager_NameTabDriveFull;
case ScriptType.drive_empty: return Local.DevManager_NameTabDriveEmpty;
}
return string.Empty;
}
// return short description of a script, or the time-out message
static string Description()
{
if (script_index == 0) return Local.DevManager_TabManual;//Control vessel components directly
switch ((ScriptType)script_index)
{
case ScriptType.landed: return Local.DevManager_TabLanded; // <i>Called on landing</i>
case ScriptType.atmo: return Local.DevManager_TabAtmo; // <i>Called on entering atmosphere</i>
case ScriptType.space: return Local.DevManager_TabSpace; // <i>Called on reaching space</i>
case ScriptType.sunlight: return Local.DevManager_TabSunlight; // <i>Called when sun became visible</i>
case ScriptType.shadow: return Local.DevManager_TabShadow; // <i>Called when sun became occluded</i>
case ScriptType.power_high: return Local.DevManager_TabPowerHigh; // <i>Called when EC level goes above 80%</i>
case ScriptType.power_low: return Local.DevManager_TabPowerLow; // <i>Called when EC level goes below 20%</i>
case ScriptType.rad_high: return Local.DevManager_TabRadHigh; // <i>Called when radiation exceed 0.05 rad/h</i>
case ScriptType.rad_low: return Local.DevManager_TabRadLow; // <i>Called when radiation goes below 0.02 rad/h</i>
case ScriptType.linked: return Local.DevManager_TabLinked; // <i>Called when signal is regained</i>
case ScriptType.unlinked: return Local.DevManager_TabUnlinked; // <i>Called when signal is lost</i>
case ScriptType.eva_out: return Local.DevManager_TabEVAOut; // <i>Called when going out on EVA</i>
case ScriptType.eva_in: return Local.DevManager_TabEVAIn; // <i>Called when returning from EVA</i>
case ScriptType.action1: return Local.DevManager_TabAct1; // <i>Called by pressing <b>1</b> on the keyboard</i>
case ScriptType.action2: return Local.DevManager_TabAct2; // <i>Called by pressing <b>2</b> on the keyboard</i>
case ScriptType.action3: return Local.DevManager_TabAct3; // <i>Called by pressing <b>3</b> on the keyboard</i>
case ScriptType.action4: return Local.DevManager_TabAct4; // <i>Called by pressing <b>4</b> on the keyboard</i>
case ScriptType.action5: return Local.DevManager_TabAct5; // <i>Called by pressing <b>5</b> on the keyboard</i>
case ScriptType.drive_full: return Local.DevManager_TabDriveFull;
case ScriptType.drive_empty: return Local.DevManager_TabDriveEmpty;
}
return string.Empty;
}
// mode/script index
static int script_index;
}
} // KERBALISM
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.ExpressRoute;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure.Management.ExpressRoute
{
internal partial class DedicatedCircuitServiceProviderOperations : IServiceOperations<ExpressRouteManagementClient>, Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitServiceProviderOperations
{
/// <summary>
/// Initializes a new instance of the
/// DedicatedCircuitServiceProviderOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DedicatedCircuitServiceProviderOperations(ExpressRouteManagementClient client)
{
this._client = client;
}
private ExpressRouteManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.ExpressRouteManagementClient.
/// </summary>
public ExpressRouteManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The List Dedicated Circuit Service Providers operation retrieves a
/// list of available dedicated circuit service providers.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Dedicated Circuit Service Provider operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitServiceProviderListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/serviceproviders?api-version=1.0";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DedicatedCircuitServiceProviderListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitServiceProviderListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitServiceProvidersSequenceElement = responseDoc.Element(XName.Get("DedicatedCircuitServiceProviders", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitServiceProvidersSequenceElement != null)
{
foreach (XElement dedicatedCircuitServiceProvidersElement in dedicatedCircuitServiceProvidersSequenceElement.Elements(XName.Get("DedicatedCircuitServiceProvider", "http://schemas.microsoft.com/windowsazure")))
{
AzureDedicatedCircuitServiceProvider dedicatedCircuitServiceProviderInstance = new AzureDedicatedCircuitServiceProvider();
result.DedicatedCircuitServiceProviders.Add(dedicatedCircuitServiceProviderInstance);
XElement nameElement = dedicatedCircuitServiceProvidersElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
dedicatedCircuitServiceProviderInstance.Name = nameInstance;
}
XElement typeElement = dedicatedCircuitServiceProvidersElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
dedicatedCircuitServiceProviderInstance.Type = typeInstance;
}
XElement dedicatedCircuitLocationsElement = dedicatedCircuitServiceProvidersElement.Element(XName.Get("DedicatedCircuitLocations", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitLocationsElement != null)
{
string dedicatedCircuitLocationsInstance = dedicatedCircuitLocationsElement.Value;
dedicatedCircuitServiceProviderInstance.DedicatedCircuitLocations = dedicatedCircuitLocationsInstance;
}
XElement dedicatedCircuitBandwidthsSequenceElement = dedicatedCircuitServiceProvidersElement.Element(XName.Get("DedicatedCircuitBandwidths", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitBandwidthsSequenceElement != null)
{
foreach (XElement dedicatedCircuitBandwidthsElement in dedicatedCircuitBandwidthsSequenceElement.Elements(XName.Get("DedicatedCircuitBandwidth", "http://schemas.microsoft.com/windowsazure")))
{
DedicatedCircuitBandwidth dedicatedCircuitBandwidthInstance = new DedicatedCircuitBandwidth();
dedicatedCircuitServiceProviderInstance.DedicatedCircuitBandwidths.Add(dedicatedCircuitBandwidthInstance);
XElement bandwidthElement = dedicatedCircuitBandwidthsElement.Element(XName.Get("Bandwidth", "http://schemas.microsoft.com/windowsazure"));
if (bandwidthElement != null)
{
uint bandwidthInstance = uint.Parse(bandwidthElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitBandwidthInstance.Bandwidth = bandwidthInstance;
}
XElement labelElement = dedicatedCircuitBandwidthsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
if (labelElement != null)
{
string labelInstance = labelElement.Value;
dedicatedCircuitBandwidthInstance.Label = labelInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* 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.IO;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.ScriptEngine.Shared
{
[Serializable]
public class EventAbortException : Exception
{
public EventAbortException()
{
}
protected EventAbortException(
SerializationInfo info,
StreamingContext context)
{
}
}
[Serializable]
public class SelfDeleteException : Exception
{
public SelfDeleteException()
{
}
protected SelfDeleteException(
SerializationInfo info,
StreamingContext context)
{
}
}
[Serializable]
public class ScriptDeleteException : Exception
{
public ScriptDeleteException()
{
}
protected ScriptDeleteException(
SerializationInfo info,
StreamingContext context)
{
}
}
public class DetectParams
{
public DetectParams()
{
Key = UUID.Zero;
OffsetPos = new LSL_Types.Vector3();
LinkNum = 0;
Group = UUID.Zero;
Name = String.Empty;
Owner = UUID.Zero;
Position = new LSL_Types.Vector3();
Rotation = new LSL_Types.Quaternion();
Type = 0;
Velocity = new LSL_Types.Vector3();
initializeSurfaceTouch();
}
public UUID Key;
public LSL_Types.Vector3 OffsetPos;
public int LinkNum;
public UUID Group;
public string Name;
public UUID Owner;
public LSL_Types.Vector3 Position;
public LSL_Types.Quaternion Rotation;
public int Type;
public LSL_Types.Vector3 Velocity;
private LSL_Types.Vector3 touchST;
public LSL_Types.Vector3 TouchST { get { return touchST; } }
private LSL_Types.Vector3 touchNormal;
public LSL_Types.Vector3 TouchNormal { get { return touchNormal; } }
private LSL_Types.Vector3 touchBinormal;
public LSL_Types.Vector3 TouchBinormal { get { return touchBinormal; } }
private LSL_Types.Vector3 touchPos;
public LSL_Types.Vector3 TouchPos { get { return touchPos; } }
private LSL_Types.Vector3 touchUV;
public LSL_Types.Vector3 TouchUV { get { return touchUV; } }
private int touchFace;
public int TouchFace { get { return touchFace; } }
// This can be done in two places including the constructor
// so be carefull what gets added here
private void initializeSurfaceTouch()
{
touchST = new LSL_Types.Vector3(-1.0, -1.0, 0.0);
touchNormal = new LSL_Types.Vector3();
touchBinormal = new LSL_Types.Vector3();
touchPos = new LSL_Types.Vector3();
touchUV = new LSL_Types.Vector3(-1.0, -1.0, 0.0);
touchFace = -1;
}
/*
* Set up the surface touch detected values
*/
public SurfaceTouchEventArgs SurfaceTouchArgs
{
set
{
if (value == null)
{
// Initialise to defaults if no value
initializeSurfaceTouch();
}
else
{
// Set the values from the touch data provided by the client
touchST = new LSL_Types.Vector3(value.STCoord.X, value.STCoord.Y, value.STCoord.Z);
touchUV = new LSL_Types.Vector3(value.UVCoord.X, value.UVCoord.Y, value.UVCoord.Z);
touchNormal = new LSL_Types.Vector3(value.Normal.X, value.Normal.Y, value.Normal.Z);
touchBinormal = new LSL_Types.Vector3(value.Binormal.X, value.Binormal.Y, value.Binormal.Z);
touchPos = new LSL_Types.Vector3(value.Position.X, value.Position.Y, value.Position.Z);
touchFace = value.FaceIndex;
}
}
}
public void Populate(Scene scene)
{
SceneObjectPart part = scene.GetSceneObjectPart(Key);
if (part == null) // Avatar, maybe?
{
ScenePresence presence = scene.GetScenePresence(Key);
if (presence == null)
return;
Name = presence.Firstname + " " + presence.Lastname;
Owner = Key;
Position = new LSL_Types.Vector3(
presence.AbsolutePosition.X,
presence.AbsolutePosition.Y,
presence.AbsolutePosition.Z);
Rotation = new LSL_Types.Quaternion(
presence.Rotation.X,
presence.Rotation.Y,
presence.Rotation.Z,
presence.Rotation.W);
Velocity = new LSL_Types.Vector3(
presence.Velocity.X,
presence.Velocity.Y,
presence.Velocity.Z);
Type = 0x01; // Avatar
if (presence.Velocity != Vector3.Zero)
Type |= 0x02; // Active
Group = presence.ControllingClient.ActiveGroupId;
return;
}
part=part.ParentGroup.RootPart; // We detect objects only
LinkNum = 0; // Not relevant
Group = part.GroupID;
Name = part.Name;
Owner = part.OwnerID;
if (part.Velocity == Vector3.Zero)
Type = 0x04; // Passive
else
Type = 0x02; // Passive
foreach (SceneObjectPart p in part.ParentGroup.Parts)
{
if (p.Inventory.ContainsScripts())
{
Type |= 0x08; // Scripted
break;
}
}
Position = new LSL_Types.Vector3(part.AbsolutePosition.X,
part.AbsolutePosition.Y,
part.AbsolutePosition.Z);
Quaternion wr = part.ParentGroup.GroupRotation;
Rotation = new LSL_Types.Quaternion(wr.X, wr.Y, wr.Z, wr.W);
Velocity = new LSL_Types.Vector3(part.Velocity.X,
part.Velocity.Y,
part.Velocity.Z);
}
}
/// <summary>
/// Holds all the data required to execute a scripting event.
/// </summary>
public class EventParams
{
public EventParams(string eventName, Object[] eventParams, DetectParams[] detectParams)
{
EventName = eventName;
Params = eventParams;
DetectParams = detectParams;
}
public string EventName;
public Object[] Params;
public DetectParams[] DetectParams;
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region Using directives
#define USE_TRACING
using System;
using System.Xml;
using System.Globalization;
using System.ComponentModel;
using System.Runtime.InteropServices;
#endregion
//////////////////////////////////////////////////////////////////////
// contains AtomTextConstruct, the base class for all atom text representations
// atomPlainTextConstruct =
// atomCommonAttributes,
// attribute type { "text" | "html" }?,
// text
//
// atomXHTMLTextConstruct =
// atomCommonAttributes,
// attribute type { "xhtml" },
// xhtmlDiv
//
// atomTextConstruct = atomPlainTextConstruct | atomXHTMLTextConstruct
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Client
{
/// <summary>enum to define the AtomTextConstructs Type...</summary>
public enum AtomTextConstructElementType
{
/// <summary>this is a Right element</summary>
Rights,
/// <summary>this is a title element</summary>
Title,
/// <summary>this is a subtitle element</summary>
Subtitle,
/// <summary>this is a summary element</summary>
Summary,
}
/// <summary>enum to define the AtomTextConstructs Type...</summary>
public enum AtomTextConstructType
{
/// <summary>defines standard text</summary>
text,
/// <summary>defines html text</summary>
html,
/// <summary>defines xhtml text</summary>
xhtml
}
//////////////////////////////////////////////////////////////////////
/// <summary>TypeConverter, so that AtomTextConstruct shows up in the property pages
/// </summary>
//////////////////////////////////////////////////////////////////////
[ComVisible(false)]
public class AtomTextConstructConverter : ExpandableObjectConverter
{
///<summary>Standard type converter method</summary>
public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType)
{
if (destinationType == typeof(AtomTextConstruct))
return true;
return base.CanConvertTo(context, destinationType);
}
///<summary>Standard type converter method</summary>
public override object ConvertTo(ITypeDescriptorContext context,CultureInfo culture, object value, System.Type destinationType)
{
AtomTextConstruct tc = value as AtomTextConstruct;
if (destinationType == typeof(System.String) && tc != null)
{
return tc.Type + ": " + tc.Text;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>AtomTextConstruct object representation
/// A Text construct contains human-readable text, usually in small quantities.
/// The content of Text constructs is Language-Sensitive.
/// </summary>
//////////////////////////////////////////////////////////////////////
[TypeConverterAttribute(typeof(AtomTextConstructConverter)), DescriptionAttribute("Expand to see details for this object.")]
public class AtomTextConstruct: AtomBase
{
/// <summary>holds the type of the text</summary>
private AtomTextConstructType type;
/// <summary>holds the text as string</summary>
private string text;
/// <summary>holds the element type</summary>
private AtomTextConstructElementType elementType;
/// <summary>the public constructor only exists for the pleasure of property pages</summary>
public AtomTextConstruct()
{
}
//////////////////////////////////////////////////////////////////////
/// <summary>constructor indicating the elementtype</summary>
/// <param name="elementType">holds the xml elementype</param>
//////////////////////////////////////////////////////////////////////
public AtomTextConstruct(AtomTextConstructElementType elementType)
{
this.elementType = elementType;
this.type = AtomTextConstructType.text; // set the default to text
}
//////////////////////////////////////////////////////////////////////
/// <summary>constructor indicating the elementtype</summary>
/// <param name="elementType">holds the xml elementype</param>
/// <param name="text">holds the text string</param>
//////////////////////////////////////////////////////////////////////
public AtomTextConstruct(AtomTextConstructElementType elementType, string text) : this(elementType)
{
this.text = text;
}
/////////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public AtomTextConstructType Type</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public AtomTextConstructType Type
{
get {return this.type;}
set {this.Dirty = true; this.type = value;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string Text</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Text
{
get {return this.text;}
set {this.Dirty = true; this.text = value;}
}
/////////////////////////////////////////////////////////////////////////////
#region Persistence overloads
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public override string XmlName
{
get
{
switch (this.elementType)
{
case AtomTextConstructElementType.Rights:
return AtomParserNameTable.XmlRightsElement;
case AtomTextConstructElementType.Subtitle:
return AtomParserNameTable.XmlSubtitleElement;
case AtomTextConstructElementType.Title:
return AtomParserNameTable.XmlTitleElement;
case AtomTextConstructElementType.Summary:
return AtomParserNameTable.XmlSummaryElement;
}
return null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>overridden to save attributes for this(XmlWriter writer)</summary>
/// <param name="writer">the xmlwriter to save into </param>
//////////////////////////////////////////////////////////////////////
protected override void SaveXmlAttributes(XmlWriter writer)
{
WriteEncodedAttributeString(writer, AtomParserNameTable.XmlAttributeType, this.Type.ToString());
// call base later as base takes care of writing out extension elements that might close the attribute list
base.SaveXmlAttributes(writer);
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>saves the inner state of the element</summary>
/// <param name="writer">the xmlWriter to save into </param>
//////////////////////////////////////////////////////////////////////
protected override void SaveInnerXml(XmlWriter writer)
{
base.SaveInnerXml(writer);
if (this.Type == AtomTextConstructType.xhtml)
{
if (Utilities.IsPersistable(this.text))
{
writer.WriteRaw(this.text);
}
}
else
{
WriteEncodedString(writer, this.text);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>figures out if this object should be persisted</summary>
/// <returns> true, if it's worth saving</returns>
//////////////////////////////////////////////////////////////////////
public override bool ShouldBePersisted()
{
if (!base.ShouldBePersisted())
{
return Utilities.IsPersistable(this.text);
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
#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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// TplEtwProvider.cs
//
//
// EventSource for TPL.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Diagnostics.Tracing;
using System.Security;
namespace System.Threading.Tasks
{
/// <summary>Provides an event source for tracing TPL information.</summary>
[EventSource(
Name = "System.Threading.Tasks.TplEventSource",
Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5"
//TODO:Bug455853:Add support for reading localized string in the EventSource il2il transform
//,LocalizationResources = "mscorlib"
)]
internal sealed class TplEtwProvider : EventSource
{
/// <summary>
/// Defines the singleton instance for the TPL ETW provider.
/// The TPL Event provider GUID is {2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5}.
/// </summary>
public static TplEtwProvider Log = new TplEtwProvider();
/// <summary>Prevent external instantiation. All logging should go through the Log instance.</summary>
private TplEtwProvider() { }
/// <summary>Configured behavior of a task wait operation.</summary>
public enum TaskWaitBehavior : int
{
/// <summary>A synchronous wait.</summary>
Synchronous = 1,
/// <summary>An asynchronous await.</summary>
Asynchronous = 2
}
/// <summary>ETW tasks that have start/stop events.</summary>
public class Tasks // this name is important for EventSource
{
// Do not use 1, it was used for "Loop" in the past.
// Do not use 2, it was used for "Invoke" in the past.
/// <summary>Executing a Task.</summary>
public const EventTask TaskExecute = (EventTask)3;
/// <summary>Waiting on a Task.</summary>
public const EventTask TaskWait = (EventTask)4;
// Do not use 5, it was used for "ForkJoin" in the past.
}
/// <summary>Enabled for all keywords.</summary>
private const EventKeywords ALL_KEYWORDS = (EventKeywords)(-1);
//-----------------------------------------------------------------------------------
//
// TPL Event IDs (must be unique)
//
/// <summary>A task is scheduled to a task scheduler.</summary>
private const int TASKSCHEDULED_ID = 7;
/// <summary>A task is about to execute.</summary>
private const int TASKSTARTED_ID = 8;
/// <summary>A task has finished executing.</summary>
private const int TASKCOMPLETED_ID = 9;
/// <summary>A wait on a task is beginning.</summary>
private const int TASKWAITBEGIN_ID = 10;
/// <summary>A wait on a task is ending.</summary>
private const int TASKWAITEND_ID = 11;
//-----------------------------------------------------------------------------------
//
// Task Events
//
// These are all verbose events, so we need to call IsEnabled(EventLevel.Verbose, ALL_KEYWORDS)
// call. However since the IsEnabled(l,k) call is more expensive than IsEnabled(), we only want
// to incur this cost when instrumentation is enabled. So the Task codepaths that call these
// event functions still do the check for IsEnabled()
#region TaskScheduled
/// <summary>
/// Fired when a task is queued to a TaskScheduler.
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The task ID.</param>
/// <param name="CreatingTaskID">The task ID</param>
/// <param name="TaskCreationOptions">The options used to create the task.</param>
[Event(TASKSCHEDULED_ID, Level = EventLevel.Verbose)]
public void TaskScheduled(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
int TaskID, int CreatingTaskID, int TaskCreationOptions)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
// There is no explicit WriteEvent() overload matching this event's fields.
// Therefore calling WriteEvent() would hit the "params" overload, which leads to an object allocation every time this event is fired.
// To prevent that problem we will call WriteEventCore(), which works with a stack based EventData array populated with the event fields
unsafe
{
EventData* eventPayload = stackalloc EventData[5];
eventPayload[0].Size = sizeof(int);
eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
eventPayload[1].Size = sizeof(int);
eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
eventPayload[2].Size = sizeof(int);
eventPayload[2].DataPointer = ((IntPtr)(&TaskID));
eventPayload[3].Size = sizeof(int);
eventPayload[3].DataPointer = ((IntPtr)(&CreatingTaskID));
eventPayload[4].Size = sizeof(int);
eventPayload[4].DataPointer = ((IntPtr)(&TaskCreationOptions));
WriteEventCore(TASKSCHEDULED_ID, 5, eventPayload);
}
}
}
#endregion TaskScheduled
#region TaskStarted
/// <summary>
/// Fired just before a task actually starts executing.
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The task ID.</param>
[Event(TASKSTARTED_ID, Level = EventLevel.Verbose, Task = TplEtwProvider.Tasks.TaskExecute, Opcode = EventOpcode.Start)]
public void TaskStarted(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
int TaskID)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
WriteEvent(TASKSTARTED_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID);
}
}
#endregion TaskStarted
#region TaskCompleted
/// <summary>
/// Fired right after a task finished executing.
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The task ID.</param>
/// <param name="IsExceptional">Whether the task completed due to an error.</param>
[Event(TASKCOMPLETED_ID, Level = EventLevel.Verbose, Version = 1, Task = TplEtwProvider.Tasks.TaskExecute, Opcode = EventOpcode.Stop)]
public void TaskCompleted(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
int TaskID, bool IsExceptional)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
// There is no explicit WriteEvent() overload matching this event's fields.
// Therefore calling WriteEvent() would hit the "params" overload, which leads to
// an object allocation every time this event is fired. To prevent that problem we will
// call WriteEventCore(), which works with a stack based EventData array populated with the event fields
unsafe
{
EventData* eventPayload = stackalloc EventData[4];
Int32 isExceptionalInt = IsExceptional ? 1 : 0;
eventPayload[0].Size = sizeof(int);
eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
eventPayload[1].Size = sizeof(int);
eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
eventPayload[2].Size = sizeof(int);
eventPayload[2].DataPointer = ((IntPtr)(&TaskID));
eventPayload[3].Size = sizeof(int);
eventPayload[3].DataPointer = ((IntPtr)(&isExceptionalInt));
WriteEventCore(TASKCOMPLETED_ID, 4, eventPayload);
}
}
}
#endregion TaskCompleted
#region TaskWaitBegin
/// <summary>
/// Fired when starting to wait for a taks's completion explicitly or implicitly.
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The task ID.</param>
/// <param name="Behavior">Configured behavior for the wait.</param>
[Event(TASKWAITBEGIN_ID, Level = EventLevel.Verbose, Version = 1, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Start)]
public void TaskWaitBegin(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
int TaskID, TaskWaitBehavior Behavior)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
// WriteEvent(TASKWAITBEGIN_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID, Behavior);
// There is no explicit WriteEvent() overload matching this event's fields.
// Therefore calling WriteEvent() would hit the "params" overload, which leads to
// an object allocation every time this event is fired. To prevent that problem we will
// call WriteEventCore(), which works with a stack based EventData array populated with the event fields
unsafe
{
EventData* eventPayload = stackalloc EventData[4];
eventPayload[0].Size = sizeof(int);
eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
eventPayload[1].Size = sizeof(int);
eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
eventPayload[2].Size = sizeof(int);
eventPayload[2].DataPointer = ((IntPtr)(&TaskID));
eventPayload[3].Size = sizeof(int);
eventPayload[3].DataPointer = ((IntPtr)(&Behavior));
WriteEventCore(TASKWAITBEGIN_ID, 4, eventPayload);
}
}
}
#endregion TaskWaitBegin
#region TaskWaitEnd
/// <summary>
/// Fired when the wait for a tasks completion returns.
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The task ID.</param>
[Event(TASKWAITEND_ID, Level = EventLevel.Verbose, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Stop)]
public void TaskWaitEnd(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
int TaskID)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
WriteEvent(TASKWAITEND_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID);
}
}
#endregion TaskWaitEnd
} // class TplEtwProvider
} // namespace
| |
// 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.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using Internal.Runtime.CompilerServices;
#pragma warning disable SA1121 // explicitly using type aliases instead of built-in types
#if BIT64
using nuint = System.UInt64;
#else // BIT64
using nuint = System.UInt32;
#endif // BIT64
namespace System
{
/// <summary>
/// Represents a contiguous region of memory, similar to <see cref="ReadOnlySpan{T}"/>.
/// Unlike <see cref="ReadOnlySpan{T}"/>, it is not a byref-like type.
/// </summary>
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public readonly struct ReadOnlyMemory<T> : IEquatable<ReadOnlyMemory<T>>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is a pre-pinned array.
// (_index < 0) => _object is a pre-pinned array, so Pin() will not allocate a new GCHandle
// (else) => Pin() needs to allocate a new GCHandle to pin the object.
private readonly object? _object;
private readonly int _index;
private readonly int _length;
internal const int RemoveFlagsBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[]? array)
{
if (array == null)
{
this = default;
return; // returns default
}
_object = array;
_index = 0;
_length = array.Length;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[]? array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
#else
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
#endif
_object = array;
_index = start;
_length = length;
}
/// <summary>Creates a new memory over the existing object, start, and length. No validation is performed.</summary>
/// <param name="obj">The target object.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlyMemory(object? obj, int start, int length)
{
// No validation performed in release builds; caller must provide any necessary validation.
// 'obj is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert((obj == null)
|| (typeof(T) == typeof(char) && obj is string)
#if FEATURE_UTF8STRING
|| ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && obj is Utf8String)
#endif // FEATURE_UTF8STRING
|| (obj is T[])
|| (obj is MemoryManager<T>));
_object = obj;
_index = start;
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(T[]? array) => new ReadOnlyMemory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment) => new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count);
/// <summary>
/// Returns an empty <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static ReadOnlyMemory<T> Empty => default;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// For <see cref="ReadOnlyMemory{Char}"/>, returns a new instance of string that represents the characters pointed to by the memory.
/// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements.
/// </summary>
public override string ToString()
{
if (typeof(T) == typeof(char))
{
return (_object is string str) ? str.Substring(_index, _length) : Span.ToString();
}
#if FEATURE_UTF8STRING
else if (typeof(T) == typeof(Char8))
{
// TODO_UTF8STRING: Call into optimized transcoding routine when it's available.
ReadOnlySpan<T> span = Span;
return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length));
}
#endif // FEATURE_UTF8STRING
return string.Format("System.ReadOnlyMemory<{0}>[{1}]", typeof(T).Name, _length);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new ReadOnlyMemory<T>(_object, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start, int length)
{
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
#else
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
#endif
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new ReadOnlyMemory<T>(_object, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public unsafe ReadOnlySpan<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref T refToReturn = ref Unsafe.AsRef<T>(null);
int lengthOfUnderlyingSpan = 0;
// Copy this field into a local so that it can't change out from under us mid-operation.
object? tmpObject = _object;
if (tmpObject != null)
{
if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string))
{
// Special-case string since it's the most common for ROM<char>.
refToReturn = ref Unsafe.As<char, T>(ref Unsafe.As<string>(tmpObject).GetRawStringData());
lengthOfUnderlyingSpan = Unsafe.As<string>(tmpObject).Length;
}
#if FEATURE_UTF8STRING
else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject.GetType() == typeof(Utf8String))
{
refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<Utf8String>(tmpObject).DangerousGetMutableReference());
lengthOfUnderlyingSpan = Unsafe.As<Utf8String>(tmpObject).Length;
}
#endif // FEATURE_UTF8STRING
else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
{
// We know the object is not null, it's not a string, and it is variable-length. The only
// remaining option is for it to be a T[] (or a U[] which is blittable to T[], like int[]
// and uint[]). Otherwise somebody used private reflection to set this field, and we're not
// too worried about type safety violations at this point.
// 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert(tmpObject is T[]);
refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData());
lengthOfUnderlyingSpan = Unsafe.As<T[]>(tmpObject).Length;
}
else
{
// We know the object is not null, and it's not variable-length, so it must be a MemoryManager<T>.
// Otherwise somebody used private reflection to set this field, and we're not too worried about
// type safety violations at that point. Note that it can't be a MemoryManager<U>, even if U and
// T are blittable (e.g., MemoryManager<int> to MemoryManager<uint>), since there exists no
// constructor or other public API which would allow such a conversion.
Debug.Assert(tmpObject is MemoryManager<T>);
Span<T> memoryManagerSpan = Unsafe.As<MemoryManager<T>>(tmpObject).GetSpan();
refToReturn = ref MemoryMarshal.GetReference(memoryManagerSpan);
lengthOfUnderlyingSpan = memoryManagerSpan.Length;
}
// If the Memory<T> or ReadOnlyMemory<T> instance is torn, this property getter has undefined behavior.
// We try to detect this condition and throw an exception, but it's possible that a torn struct might
// appear to us to be valid, and we'll return an undesired span. Such a span is always guaranteed at
// least to be in-bounds when compared with the original Memory<T> instance, so using the span won't
// AV the process.
nuint desiredStartIndex = (uint)_index & (uint)RemoveFlagsBitMask;
int desiredLength = _length;
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)desiredStartIndex + (ulong)(uint)desiredLength > (ulong)(uint)lengthOfUnderlyingSpan)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
#else
if ((uint)desiredStartIndex > (uint)lengthOfUnderlyingSpan || (uint)desiredLength > (uint)(lengthOfUnderlyingSpan - desiredStartIndex))
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
#endif
refToReturn = ref Unsafe.Add(ref refToReturn, (IntPtr)(void*)desiredStartIndex);
lengthOfUnderlyingSpan = desiredLength;
}
return new ReadOnlySpan<T>(ref refToReturn, lengthOfUnderlyingSpan);
}
}
/// <summary>
/// Copies the contents of the read-only memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The Memory to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination is shorter than the source.
/// </exception>
/// </summary>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Copies the contents of the readonly-only memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination is shorter than the source, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Creates a handle for the memory.
/// The GC will not move the memory until the returned <see cref="MemoryHandle"/>
/// is disposed, enabling taking and using the memory's address.
/// <exception cref="System.ArgumentException">
/// An instance with nonprimitive (non-blittable) members cannot be pinned.
/// </exception>
/// </summary>
public unsafe MemoryHandle Pin()
{
// It's possible that the below logic could result in an AV if the struct
// is torn. This is ok since the caller is expecting to use raw pointers,
// and we're not required to keep this as safe as the other Span-based APIs.
object? tmpObject = _object;
if (tmpObject != null)
{
if (typeof(T) == typeof(char) && tmpObject is string s)
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
ref char stringData = ref Unsafe.Add(ref s.GetRawStringData(), _index);
return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
}
#if FEATURE_UTF8STRING
else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject is Utf8String utf8String)
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
ref byte stringData = ref utf8String.DangerousGetMutableReference(_index);
return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
}
#endif // FEATURE_UTF8STRING
else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
{
// 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert(tmpObject is T[]);
// Array is already pre-pinned
if (_index < 0)
{
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index & RemoveFlagsBitMask);
return new MemoryHandle(pointer);
}
else
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index);
return new MemoryHandle(pointer, handle);
}
}
else
{
Debug.Assert(tmpObject is MemoryManager<T>);
return Unsafe.As<MemoryManager<T>>(tmpObject).Pin(_index);
}
}
return default;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>Determines whether the specified object is equal to the current object.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj)
{
if (obj is ReadOnlyMemory<T> readOnlyMemory)
{
return Equals(readOnlyMemory);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(ReadOnlyMemory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
/// <summary>Returns the hash code for this <see cref="ReadOnlyMemory{T}"/></summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
// We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash
// code is based on object identity and referential equality, not deep equality (as common with string).
return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0;
}
/// <summary>Gets the state of the memory as individual fields.</summary>
/// <param name="start">The offset.</param>
/// <param name="length">The count.</param>
/// <returns>The object.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal object? GetObjectStartLength(out int start, out int length)
{
start = _index;
length = _length;
return _object;
}
}
}
| |
using Core.IO;
using System;
using System.Diagnostics;
namespace Core
{
public partial class Vdbe
{
#region Structs
public class VdbeSorter
{
public long WriteOffset; // Current write offset within file pTemp1
public long ReadOffset; // Current read offset within file pTemp1
public int InMemory; // Current size of pRecord list as PMA
public int PMAs; // Number of PMAs stored in pTemp1
public int MinPmaSize; // Minimum PMA size, in bytes
public int MaxPmaSize; // Maximum PMA size, in bytes. 0==no limit
public VdbeSorterIter Iters; // Array of iterators to merge
public array_t<int> Trees; // Current state of incremental merge / Used size of aTree/aIter (power of 2)
public VFile Temp1; // PMA file 1
public SorterRecord Record; // Head of in-memory record list
public UnpackedRecord Unpacked; // Used to unpack keys
}
public class VdbeSorterIter
{
public long ReadOffset; // Current read offset
public long Eof; // 1 byte past EOF for this iterator
public VFile File; // File iterator is reading from
public array_t<byte> Alloc; // Allocated space
public array_t<byte> Key; // Pointer to current key
public array_t<byte> Buffer; // Current read buffer
internal void _memset()
{
}
}
public class FileWriter
{
public int FWErr; // Non-zero if in an error state
public array_t<byte> Buffer; // Pointer to write buffer
public int BufStart; // First byte of buffer to write
public int BufEnd; // Last byte of buffer to write
public long WriteOffset; // Offset of start of buffer in file
public VFile File; // File to write to
}
public class SorterRecord
{
public object P;
public int N;
public SorterRecord Next;
}
public const int SORTER_MIN_WORKING = 10; // Minimum allowable value for the VdbeSorter.nWorking variable
public const int SORTER_MAX_MERGE_COUNT = 16; // Maximum number of segments to merge in a single pass.
#endregion
#region Sorter Iter
static void VdbeSorterIterZero(Context ctx, VdbeSorterIter iter)
{
C._tagfree(ctx, ref iter.Alloc.data);
C._tagfree(ctx, ref iter.Buffer.data);
iter._memset();
}
static RC VdbeSorterIterRead(Context ctx, VdbeSorterIter p, int bytes, ref byte[] out_)
{
Debug.Assert(p.Buffer.data != null);
// If there is no more data to be read from the buffer, read the next p->nBuffer bytes of data from the file into it. Or, if there are less
// than p->nBuffer bytes remaining in the PMA, read all remaining data.
int bufferIdx = (int)(p.ReadOffset % p.Buffer.length); // Offset within buffer to read from
if (bufferIdx == 0)
{
// Determine how many bytes of data to read.
int read = (int)((p.Eof - p.ReadOffset) > p.Buffer.length ? p.Buffer.length : p.Eof - p.ReadOffset); // Bytes to read from disk
Debug.Assert(read > 0);
// Read data from the file. Return early if an error occurs.
RC rc = p.File.Read(p.Buffer, read, p.ReadOffset);
Debug.Assert(rc != RC.IOERR_SHORT_READ);
if (rc != RC.OK) return rc;
}
int avail = p.Buffer.length - bufferIdx; // Bytes of data available in buffer
if (bytes <= avail)
{
// The requested data is available in the in-memory buffer. In this case there is no need to make a copy of the data, just return a
// pointer into the buffer to the caller.
out_ = p.Buffer[bufferIdx];
p.ReadOffset += bytes;
}
// The requested data is not all available in the in-memory buffer. In this case, allocate space at p->aAlloc[] to copy the requested
// range into. Then return a copy of pointer p->aAlloc to the caller.
else
{
// Extend the p->aAlloc[] allocation if required.
if (p.Alloc.length < bytes)
{
int newSize = p.Alloc.length * 2;
while (bytes > newSize) newSize = newSize * 2;
p.Alloc.data = (byte[])C._tagrealloc(ctx, 0, p.Alloc.data, newSize);
if (p.Alloc.data == null) return RC.NOMEM;
p.Alloc.length = newSize;
}
// Copy as much data as is available in the buffer into the start of p->aAlloc[].
C._memcpy(p.Alloc.data, p.Buffer[bufferIdx], avail);
p.ReadOffset += avail;
// The following loop copies up to p->nBuffer bytes per iteration into the p->aAlloc[] buffer.
int remaining = bytes - avail; // Bytes remaining to copy
while (remaining > 0)
{
int copy = remaining; // Number of bytes to copy
if (remaining > p.Buffer.length) copy = p.Buffer.length;
byte[] next; // Pointer to buffer to copy data from
RC rc = VdbeSorterIterRead(ctx, p, copy, ref next);
if (rc != RC.OK) return rc;
Debug.Assert(next != p.Alloc);
C._memcpy(p.Alloc[bytes - remaining], next, copy);
remaining -= copy;
}
out_ = p.Alloc;
}
return RC.OK;
}
static RC VdbeSorterIterVarint(Context ctx, VdbeSorterIter p, out ulong out_)
{
int bufferIdx = (int)(p.ReadOffset % p.Buffer.length);
if (bufferIdx != 0 && (p.Buffer.length - bufferIdx) >= 9)
p.ReadOffset += ConvertEx.GetVarint(p.Buffer[bufferIdx], out out_);
else
{
byte[] varint = new byte[16]; byte[] a;
int i = 0;
do
{
RC rc = VdbeSorterIterRead(ctx, p, 1, ref a);
if (rc != 0) return rc;
varint[(i++) & 0xf] = a[0];
} while ((a[0] & 0x80) != 0);
ConvertEx.GetVarint(varint, out out_);
}
return RC.OK;
}
static RC VdbeSorterIterNext(Context ctx, VdbeSorterIter iter)
{
if (iter.ReadOffset >= iter.Eof)
{
VdbeSorterIterZero(ctx, iter); // This is an EOF condition
return RC.OK;
}
ulong recordSize; // Size of record in bytes
RC rc = VdbeSorterIterVarint(ctx, iter, ref recordSize);
if (rc == RC.OK)
{
iter.Key.length = (int)recordSize;
rc = VdbeSorterIterRead(ctx, iter, (int)recordSize, ref iter.Key.data);
}
return rc;
}
static RC VdbeSorterIterInit(Context ctx, VdbeSorter sorter, long start, VdbeSorterIter iter, ref long bytes)
{
Debug.Assert(sorter.WriteOffset > start);
Debug.Assert(iter.Alloc.data == null);
Debug.Assert(iter.Buffer.data == null);
int bufferLength = ctx.DBs[0].Bt.GetPageSize();
iter.File = sorter.Temp1;
iter.ReadOffset = start;
iter.Alloc.length = 128;
iter.Alloc.data = (byte[])C._tagalloc(ctx, iter.Alloc.length);
iter.Buffer.length = bufferLength;
iter.Buffer.data = (byte[])C._tagalloc(ctx, bufferLength);
RC rc = RC.OK;
if (iter.Buffer.data == null)
rc = RC.NOMEM;
else
{
int bufferIdx = start % bufferLength;
if (bufferIdx != 0)
{
int read = bufferLength - bufferIdx;
if ((start + read) > sorter.WriteOffset)
read = (int)(sorter.WriteOffset - start);
rc = sorter.Temp1.Read(iter.Buffer[bufferIdx], read, start);
Debug.Assert(rc != RC.IOERR_SHORT_READ);
}
if (rc == RC.OK)
{
iter.Eof = sorter.WriteOffset;
ulong bytes2; // Size of PMA in bytes
rc = VdbeSorterIterVarint(ctx, iter, ref bytes2);
iter.Eof = iter.ReadOffset + bytes2;
bytes += bytes2;
}
}
if (rc == RC.OK)
rc = VdbeSorterIterNext(ctx, iter);
return rc;
}
#endregion
#region Sorter Compare/Merge
static void VdbeSorterCompare(VdbeCursor cursor, bool omitRowid, string key1, int key1Length, string key2, int key2Length, ref int out_)
{
KeyInfo keyInfo = cursor.KeyInfo;
VdbeSorter sorter = (VdbeSorter)cursor.Sorter;
UnpackedRecord r2 = sorter.Unpacked;
if (key2 != null)
Vdbe_RecordUnpack(keyInfo, key2Length, key2, r2);
if (omitRowid)
{
r2.Fields = keyInfo.Fields;
Debug.Assert(r2.Fields > 0);
for (int i = 0; i < r2.Fields; i++)
if ((r2.Mems[i].Flags & MEM.Null) != 0)
{
out_ = -1;
return;
}
r2.Flags |= UNPACKED.PREFIX_MATCH;
}
out_ = Vdbe_RecordCompare(key1Length, key1, r2);
}
static RC VdbeSorterDoCompare(VdbeCursor cursor, int idx)
{
VdbeSorter sorter = cursor.Sorter;
Debug.Assert(idx < sorter.Trees.length && idx > 0);
int i1;
int i2;
if (idx >= (sorter.Trees.length / 2))
{
i1 = (idx - sorter.Trees.length / 2) * 2;
i2 = i1 + 1;
}
else
{
i1 = sorter.Trees[idx * 2];
i2 = sorter.Trees[idx * 2 + 1];
}
VdbeSorterIter p1 = sorter.Iters[i1];
VdbeSorterIter p2 = sorter.Iters[i2];
int i;
if (p1.File == null)
i = i2;
else if (p2.File == null)
i = i1;
else
{
Debug.Assert(sorter.Unpacked != null); // allocated in vdbeSorterMerge()
int r;
VdbeSorterCompare(cursor, 0, p1.Key, p1.Key.length, p2.Key, p2.Key.length, ref r);
i = (r <= 0 ? i1 : i2);
}
sorter.Trees[idx] = i;
return RC.OK;
}
public RC SorterInit(Context ctx, VdbeCursor cursor)
{
Debug.Assert(cursor.KeyInfo != null && cursor.Bt == null);
VdbeSorter sorter; // The new sorter
cursor.Sorter = sorter = (VdbeSorter)C._tagalloc(ctx, sizeof(VdbeSorter));
if (sorter == null)
return RC.NOMEM;
object d;
sorter.Unpacked = AllocUnpackedRecord(cursor.KeyInfo, 0, 0, ref d);
if (sorter.Unpacked == null) return RC.NOMEM;
Debug.Assert(sorter.Unpacked == (UnpackedRecord)d);
if (ctx.TempInMemory() == null)
{
int pageSize = ctx.DBs[0].Bt.GetPageSize(); // Page size of main database
sorter.MinPmaSize = SORTER_MIN_WORKING * pageSize;
int maxCache = ctx.DBs[0].Schema.CacheSize; // Cache size
if (maxCache < SORTER_MIN_WORKING) maxCache = SORTER_MIN_WORKING;
sorter.MaxPmaSize = maxCache * pageSize;
}
return RC.OK;
}
static void VdbeSorterRecordFree(Context ctx, SorterRecord record)
{
SorterRecord next;
for (SorterRecord p = record; p != null; p = next)
{
next = p.Next;
C._tagfree(ctx, ref p);
}
}
public void SorterClose(Context ctx, VdbeCursor cursor)
{
VdbeSorter sorter = cursor.Sorter;
if (sorter != null)
{
if (sorter.Iters != null)
{
for (int i = 0; i < sorter.Trees.length; i++)
VdbeSorterIterZero(ctx, sorter.Iters[i]);
C._tagfree(ctx, ref sorter.Iters);
}
if (sorter.Temp1 != null)
sorter.Temp1.CloseAndFree();
VdbeSorterRecordFree(ctx, sorter.Record);
C._tagfree(ctx, sorter.Unpacked);
C._tagfree(ctx, sorter);
cursor.Sorter = null;
}
}
static RC VdbeSorterOpenTempFile(Context ctx, ref VFile file)
{
VSystem.OPEN outFlags;
return ctx.Vfs.OpenAndAlloc(null, file, (VSystem.OPEN)(VSystem.OPEN_TEMP_JOURNAL | VSystem.OPEN_READWRITE | VSystem.OPEN_CREATE | VSystem.OPEN_EXCLUSIVE | VSystem.OPEN_DELETEONCLOSE), ref outFlags);
}
static void VdbeSorterMerge(VdbeCursor cursor, SorterRecord p1, SorterRecord p2, ref SorterRecord out_)
{
SorterRecord result = null;
SorterRecord pp = result;
object p2P = (p2 != null ? p2.P : null);
while (p1 != null && p2 != null)
{
int r;
VdbeSorterCompare(cursor, false, p1.P, p1.N, p2P, p2.N, ref r);
if (r <= 0)
{
pp = p1;
pp = p1.Next;
p1 = p1.Next;
p2P = null;
}
else
{
pp = p2;
pp = p2.Next;
p2 = p2.Next;
if (p2 != null) break;
p2P = p2.P;
}
}
pp = (p1 != null ? p1 : p2);
out_ = result;
}
static RC VdbeSorterSort(VdbeCursor cursor)
{
SorterRecord slots = new SorterRecord[64];
if (slots == null)
return RC.NOMEM;
VdbeSorter sorter = cursor.Sorter;
SorterRecord p = sorter.Record;
int i;
while (p != null)
{
SorterRecord next = p.Next;
p.Next = null;
for (i = 0; slots[i] != null; i++)
{
VdbeSorterMerge(cursor, p, slots[i], ref p);
slots[i] = null;
}
slots[i] = p;
p = next;
}
p = null;
for (i = 0; i < 64; i++)
VdbeSorterMerge(cursor, p, slots[i], ref p);
sorter.Record = p;
C._free(ref slots);
return RC.OK;
}
#endregion
#region FileWriter
static void FileWriterInit(Context ctx, VFile file, FileWriter p, long start)
{
p._memset();
int pageSize = ctx.DBs[0].Bt.GetPageSize();
p.Buffer.data = (byte[])C._tagalloc(ctx, pageSize);
if (p.Buffer.data == null)
p.FWErr = RC.NOMEM;
else
{
p.BufEnd = p.BufStart = (start % pageSize);
p.WriteOffset = start - p.BufStart;
p.Buffer.length = pageSize;
p.File = file;
}
}
static void FileWriterWrite(FileWriter p, byte[] data, int dataLength)
{
int remain = dataLength;
while (remain > 0 && p.FWErr == 0)
{
int copy = remain;
if (copy > (p.Buffer.length - p.BufEnd))
copy = p.Buffer.length - p.BufEnd;
C._memcpy(p.Buffer[p.BufEnd], data[dataLength - remain], copy);
p.BufEnd += copy;
if (p.BufEnd == p.Buffer.length)
{
p.FWErr = p.File.Write(p.Buffer[p.BufStart], p.BufEnd - p.BufStart, p.WriteOffset + p.BufStart);
p.BufStart = p.BufEnd = 0;
p.WriteOffset += p.Buffer.length;
}
Debug.Assert(p.BufEnd < p.Buffer.length);
remain -= copy;
}
}
static RC FileWriterFinish(Context ctx, FileWriter p, ref long eof)
{
if (p.FWErr == 0 && C._ALWAYS(p.Buffer) && p.BufEnd > p.BufStart)
p.FWErr = p.File.Write(p.Buffer[p.BufStart], p.BufEnd - p.BufStart, p.WriteOffset + p.BufStart);
eof = (p.WriteOffset + p.BufEnd);
C._tagfree(ctx, ref p.Buffer.data);
RC rc = (RC)p.FWErr;
p._memset();
return rc;
}
static void FileWriterWriteVarint(FileWriter p, ulong value)
{
byte[] bytes = new byte[10];
int length = ConvertEx.PutVarint(bytes, value);
FileWriterWrite(p, bytes, length);
}
static RC VdbeSorterListToPMA(Context ctx, VdbeCursor cursor)
{
VdbeSorter sorter = cursor.Sorter;
FileWriter writer;
writer._memset();
if (sorter.InMemory == 0)
{
Debug.Assert(sorter.Record == null);
return RC.OK;
}
RC rc = VdbeSorterSort(cursor);
// If the first temporary PMA file has not been opened, open it now.
if (rc == RC.OK && sorter.Temp1 == null)
{
rc = VdbeSorterOpenTempFile(ctx, ref sorter.Temp1);
Debug.Assert(rc != RC.OK || sorter.Temp1 != null);
Debug.Assert(sorter.WriteOffset == 0);
Debug.Assert(sorter.PMAs == 0);
}
if (rc == RC.OK)
{
FileWriterInit(ctx, sorter.Temp1, writer, sorter.WriteOffset);
sorter.PMAs++;
FileWriterWriteVarint(writer, sorter.InMemory);
SorterRecord p;
SorterRecord next = null;
for (p = sorter.Record; p; p = next)
{
next = p.Next;
FileWriterWriteVarint(writer, p.N);
FileWriterWrite(writer, (byte[])p.P, p.N);
C._tagfree(ctx, ref p);
}
sorter.Record = p;
rc = FileWriterFinish(ctx, writer, sorter.WriteOffset);
}
return rc;
}
public RC SorterWrite(Context ctx, VdbeCursor cursor, Mem mem)
{
VdbeSorter sorter = cursor.Sorter;
Debug.Assert(sorter != null);
sorter.InMemory += ConvertEx.GetVarintLength(mem.N) + mem.N;
SorterRecord newRecord = (SorterRecord)C._tagalloc(ctx, mem.N + sizeof(SorterRecord)); // New list element
RC rc = RC.OK;
if (newRecord == null)
rc = RC.NOMEM;
else
{
newRecord.P = newRecord[1];
C._memcpy(newRecord.P, mem.Z, mem.N);
newRecord.N = mem.N;
newRecord.Next = sorter.Record;
sorter.Record = newRecord;
}
// See if the contents of the sorter should now be written out. They are written out when either of the following are true:
// * The total memory allocated for the in-memory list is greater than (page-size * cache-size), or
// * The total memory allocated for the in-memory list is greater than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
if (rc == RC.OK && sorter.MaxPmaSize > 0 && ((sorter.InMemory > sorter.MaxPmaSize) || (sorter.InMemory > sorter.MaxPmaSize && C._alloc_heapnearlyfull())))
{
#if DEBUG
long expect = sorter.WriteOffset + ConvertEx.GetVarintLength(sorter.InMemory) + sorter.InMemory;
#endif
rc = VdbeSorterListToPMA(ctx, cursor);
sorter.InMemory = 0;
Debug.Assert(rc != RC.OK || expect == sorter.WriteOffset);
}
return rc;
}
static RC VdbeSorterInitMerge(Context ctx, VdbeCursor cursor, ref long bytes)
{
VdbeSorter sorter = cursor, Sorter;
long bytes2 = 0; // Total bytes in all opened PMAs
RC rc = RC.OK;
// Initialize the iterators.
int i; // Used to iterator through aIter[]
for (i = 0; i < SORTER_MAX_MERGE_COUNT; i++)
{
VdbeSorterIter iter = sorter.Iters[i];
rc = VdbeSorterIterInit(ctx, sorter, sorter.ReadOffset, iter, ref bytes2);
sorter.ReadOffset = iter.Eof;
Debug.Assert(rc != RC.OK || sorter.ReadOffset <= sorter.WriteOffset);
if (rc != RC.OK || sorter.ReadOffset >= sorter.WriteOffset) break;
}
// Initialize the aTree[] array.
for (i = sorter.Trees.length - 1; rc == RC.OK && i > 0; i--)
rc = VdbeSorterDoCompare(cursor, i);
bytes = bytes2;
return rc;
}
public RC SorterRewind(Context ctx, VdbeCursor cursor, ref bool eof)
{
VdbeSorter sorter = cursor.Sorter;
Debug.Assert(sorter != null);
// If no data has been written to disk, then do not do so now. Instead, sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
// from the in-memory list.
if (sorter.PMAs == 0)
{
eof = (sorter.Record == null);
Debug.Assert(sorter.Trees.data = null);
return VdbeSorterSort(cursor);
}
// Write the current in-memory list to a PMA.
RC rc = VdbeSorterListToPMA(ctx, cursor);
if (rc != RC.OK) return rc;
// Allocate space for aIter[] and aTree[].
int iters = sorter.PMAs; // Number of iterators used
if (iters > SORTER_MAX_MERGE_COUNT) iters = SORTER_MAX_MERGE_COUNT;
Debug.Assert(iters > 0);
int n = 2; while (n < iters) n += n; // Power of 2 >= iters
int bytes = n * (sizeof(int) + sizeof(VdbeSorterIter)); // Bytes of space required for aIter/aTree
sorter.Iters = (VdbeSorterIter)C._tagalloc(ctx, bytes);
if (sorter.Iters == null) return RC.NOMEM;
sorter.Trees = sorter.Iters[n];
sorter.Trees.length = n;
int newIdx; // Index of new, merged, PMA
VFile temp2 = null; // Second temp file to use
long write2 = 0; // Write offset for pTemp2
do
{
for (newIdx = 0; rc == RC.OK && newIdx * SORTER_MAX_MERGE_COUNT < sorter.PMAs; newIdx++)
{
FileWriter writer; writer._memset(); // Object used to write to disk
// If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1, initialize an iterator for each of them and break out of the loop.
// These iterators will be incrementally merged as the VDBE layer calls sqlite3VdbeSorterNext().
//
// Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs, initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
// are merged into a single PMA that is written to file pTemp2.
long writes; // Number of bytes in new PMA
rc = VdbeSorterInitMerge(ctx, cursor, ref writes);
Debug.Assert(rc != RC.OK || sorter.Iters[sorter.Trees[1]].File);
if (rc != RC.OK || sorter.PMAs <= SORTER_MAX_MERGE_COUNT)
break;
// Open the second temp file, if it is not already open.
if (temp2 == null)
{
Debug.Assert(write2 == 0);
rc = VdbeSorterOpenTempFile(ctx, ref temp2);
}
if (rc == RC.OK)
{
bool eof = false;
FileWriterInit(ctx, temp2, ref writer, write2);
FileWriterWriteVarint(writer, writes);
while (rc == RC.OK && !eof)
{
VdbeSorterIter iter = sorter.Iters[sorter.Trees[1]];
Debug.Assert(iter.File);
FileWriterWriteVarint(writer, iter.Key.length);
FileWriterWrite(writer, iter.Key, iter.Key.length);
rc = SorterNext(ctx, cursor, eof);
}
RC rc2 = FileWriterFinish(ctx, writer, write2);
if (rc == RC.OK) rc = rc2;
}
}
if (sorter.PMAs <= SORTER_MAX_MERGE_COUNT)
break;
else
{
VFile tmp = sorter.Temp1;
sorter.PMAs = newIdx;
sorter.Temp1 = temp2;
temp2 = tmp;
sorter.WriteOffset = write2;
sorter.ReadOffset = 0;
write2 = 0;
}
} while (rc == RC.OK);
if (temp2)
temp2.CloseAndFree();
eof = (sorter.Iters[sorter.Trees[1]].File == null);
return rc;
}
public RC SorterNext(Context ctx, VdbeCursor cursor, ref bool eof)
{
VdbeSorter sorter = cursor.Sorter;
if (sorter.Trees)
{
int prevI = sorter.Trees[1]; // Index of iterator to advance
RC rc = VdbeSorterIterNext(ctx, sorter.Iters[prevI]);
for (int i = (sorter.Trees.length + prevI) / 2; rc == RC.OK && i > 0; i /= 2) // Index of aTree[] to recalculate
rc = VdbeSorterDoCompare(cursor, i);
eof = (sorter.Iters[sorter.Trees[1]].File == null);
return rc;
}
SorterRecord free = sorter.Record;
sorter.Record = free.Next;
free.Next = nullptr;
VdbeSorterRecordFree(ctx, free);
eof = (sorter.Record == null);
return RC.OK;
}
static object VdbeSorterRowkey(VdbeSorter sorter, out int keyLength)
{
if (sorter.Trees.data != null)
{
VdbeSorterIter iter = sorter.Iters[sorter.Trees.data[1]];
keyLength = iter.Key.length;
return iter.Key;
}
keyLength = sorter.Record.N;
return sorter.Record.P;
}
public RC SorterRowkey(VdbeCursor cursor, Mem mem)
{
int keyLength;
void* key = VdbeSorterRowkey(cursor.Sorter, out keyLength);
if (MemGrow(mem, keyLength, 0))
return RC.NOMEM;
mem.N = keyLength;
MemSetTypeFlag(mem, MEM.Blob);
C._memcpy(mem.Z, key, keyLength);
return RC.OK;
}
public RC SorterCompare(VdbeCursor cursor, Mem mem, out int r)
{
int keyLength;
object key = VdbeSorterRowkey(cursor.Sorter, out keyLength);
VdbeSorterCompare(cursor, 1, mem.Z, mem.N, key, keyLength, out r);
return RC.OK;
}
#endregion
}
}
| |
// Copyright (c) 2013-2018 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
#if !NET40
using Microsoft.Extensions.DependencyModel;
#endif
namespace Icu
{
/// <summary>
/// Helper class to try and get path to icu native binaries when running on
/// Windows or .NET Core.
/// </summary>
internal static class NativeMethodsHelper
{
private const string Icu4c = nameof(Icu4c);
private const string IcuRegexLinux = @"libicu\w+.so\.(?<version>[0-9]{2,})(\.[0-9])*";
private const string IcuRegexWindows = @"icu\w+(?<version>[0-9]{2,})(\.[0-9])*\.dll";
private static readonly Regex IcuBinaryRegex = new Regex($"{IcuRegexWindows}|{IcuRegexLinux}$", RegexOptions.Compiled);
private static readonly string IcuSearchPattern = Platform.OperatingSystem == OperatingSystemType.Windows ? "icu*.dll" : "libicu*.so.*";
private static readonly string NugetPackageDirectory = GetDefaultPackageDirectory(Platform.OperatingSystem);
private static IcuVersionInfo IcuVersion;
/// <summary>
/// Reset the member variables
/// </summary>
public static void Reset()
{
IcuVersion = null;
}
/// <summary>
/// Tries to get path and version to Icu when running on .NET Core or Windows.
/// </summary>
/// <returns>The path and version of icu binaries if found. Check
/// <see cref="IcuVersionInfo.Success"/> to see if the values were set.</returns>
public static IcuVersionInfo GetIcuVersionInfoForNetCoreOrWindows()
{
// We've already tried to set the path to native assets. Don't try again.
if (IcuVersion != null)
{
return IcuVersion;
}
// Set the default to IcuVersion with an empty path and no version set.
IcuVersion = new IcuVersionInfo();
if (TryPreferredDirectory())
{
return IcuVersion;
}
if (TryGetPathFromAssemblyDirectory())
{
return IcuVersion;
}
// That's odd.. I guess we use normal search paths from %PATH% then.
// One possibility is that it is not a dev machine and the application
// is a published app... but then it should have returned true in
// TryGetPathFromAssemblyDirectory.
if (string.IsNullOrEmpty(NugetPackageDirectory))
{
Trace.TraceWarning($"{nameof(NugetPackageDirectory)} is empty and application was unable to set path from current assembly directory.");
return IcuVersion;
}
#if !NET40
var context = DependencyContext.Default;
// If this is false, something went wrong. These files should have
// either been found above or we should have been able to locate the
// asset paths (for .NET Core and NuGet v3+ projects).
if (!TryGetNativeAssetPaths(context, out var nativeAssetPaths))
{
Trace.WriteLine("Could not locate icu native assets from DependencyModel.");
return IcuVersion;
}
var icuLib = context.CompileLibraries
.FirstOrDefault(x => x.Name.StartsWith(Icu4c, StringComparison.OrdinalIgnoreCase));
if (icuLib == default(CompilationLibrary))
{
Trace.TraceWarning("Could not find Icu4c compilation library. Possible that the library writer did not include the Icu4c.Win.Full.Lib or Icu4c.Win.Full.Lib NuGet package.");
return IcuVersion;
}
if (!TryResolvePackagePath(icuLib, NugetPackageDirectory, out string packagePath))
{
Trace.WriteLine("Could not resolve nuget package directory....");
return IcuVersion;
}
TrySetIcuPathFromDirectory(new DirectoryInfo(packagePath), nativeAssetPaths);
#endif
return IcuVersion;
}
private static bool TryPreferredDirectory()
{
if (string.IsNullOrEmpty(NativeMethods.PreferredDirectory))
return false;
var preferredDirectory = new DirectoryInfo(NativeMethods.PreferredDirectory);
if (TryGetIcuVersionNumber(preferredDirectory, out var version))
{
IcuVersion = new IcuVersionInfo(preferredDirectory, version);
return true;
}
return false;
}
/// <summary>
/// Tries to set the native library using the <see cref="NativeMethods.DirectoryOfThisAssembly"/>
/// as the root directory. The following scenarios could happen:
/// 1. {directoryOfAssembly}/icu*.dll
/// Occurs when the project is published using the .NET Core CLI
/// against the full .NET framework.
/// 2. {directoryOfAssembly}/lib/{arch}/icu*.dll
/// Occurs when the project is using NuGet v2, the traditional
/// .NET Framework csproj or the new VS2017 projects.
/// 3. {directoryOfAssembly}/runtimes/{runtimeId}/native/icu*.dll
/// Occurs when the project is published using the .NET Core CLI.
/// If one of the scenarios match, sets the <see cref="IcuVersion"/>.
/// </summary>
/// <returns>True if it was able to find the icu binaries within
/// <see cref="NativeMethods.DirectoryOfThisAssembly"/>, false otherwise.
/// </returns>
private static bool TryGetPathFromAssemblyDirectory()
{
var assemblyDirectory = new DirectoryInfo(NativeMethods.DirectoryOfThisAssembly);
// 1. Check in {assemblyDirectory}/
if (TryGetIcuVersionNumber(assemblyDirectory, out var version))
{
IcuVersion = new IcuVersionInfo(assemblyDirectory, version);
return true;
}
// 2. Check in {assemblyDirectory}/lib/*{architecture}*/
var libDirectory = Path.Combine(assemblyDirectory.FullName, "lib");
if (Directory.Exists(libDirectory))
{
var candidateDirectories = Directory
.EnumerateDirectories(libDirectory, $"*{Platform.ProcessArchitecture}*")
.Select(x => new DirectoryInfo(x));
foreach (var directory in candidateDirectories)
{
if (TryGetIcuVersionNumber(directory, out version))
{
IcuVersion = new IcuVersionInfo(directory, version);
return true;
}
}
}
string[] nativeAssetPaths = null;
#if !NET40
// 3. Check in {directoryOfAssembly}/runtimes/{runtimeId}/native/
if (!TryGetNativeAssetPaths(DependencyContext.Default, out nativeAssetPaths))
{
Trace.WriteLine("Could not locate icu native assets from DependencyModel.");
return false;
}
#endif
// If we found the icu*.dll files under {directoryOfAssembly}/runtimes/{rid}/native/,
// they should ALL be there... or else something went wrong in publishing the app or
// restoring the files, or packaging the NuGet package.
return TrySetIcuPathFromDirectory(assemblyDirectory, nativeAssetPaths);
}
/// <summary>
/// Iterates through the directory for files with the path icu*.dll and
/// tries to fetch the icu version number from them.
/// </summary>
/// <returns>Returns the version number if the search was successful and
/// null, otherwise.</returns>
private static bool TryGetIcuVersionNumber(DirectoryInfo directory, out int icuVersion)
{
icuVersion = int.MinValue;
if (directory == null || !directory.Exists)
return false;
var version = directory.GetFiles(IcuSearchPattern)
.Select(x =>
{
var match = IcuBinaryRegex.Match(x.Name);
if (match.Success &&
int.TryParse(match.Groups["version"].Value, out var retVal) &&
retVal >= NativeMethods.MinIcuVersion && retVal <= NativeMethods.MaxIcuVersion)
{
return retVal;
}
return new int?();
})
.OrderByDescending(x => x)
.FirstOrDefault();
if (version.HasValue)
icuVersion = version.Value;
return version.HasValue;
}
/// <summary>
/// Given a root path and a set of native asset paths, tries to see if
/// the files exist and if they do, sets <see cref="IcuVersion"/>.
/// </summary>
/// <param name="baseDirectory">Root path to append asset paths to.</param>
/// <param name="nativeAssetPaths">Set of native asset paths to check.</param>
/// <returns>true if it was able to find the directory for all the asset
/// paths given; false otherwise.</returns>
private static bool TrySetIcuPathFromDirectory(DirectoryInfo baseDirectory, string[] nativeAssetPaths)
{
if (nativeAssetPaths == null || nativeAssetPaths.Length == 0)
return false;
Trace.WriteLine("Assets: " + Environment.NewLine + string.Join(Environment.NewLine + "\t-", nativeAssetPaths));
var assetPaths = nativeAssetPaths
.Select(asset => new FileInfo(Path.Combine(baseDirectory.FullName, asset)));
var doAllAssetsExistInDirectory = assetPaths.All(x => x.Exists);
if (doAllAssetsExistInDirectory)
{
var directories = assetPaths.Select(file => file.Directory).ToArray();
if (directories.Length > 1)
Trace.TraceWarning($"There are multiple directories for these runtime assets: {string.Join(Path.PathSeparator.ToString(), directories.Select(x => x.FullName))}. There should only be one... Using first directory.");
var icuDirectory = directories.First();
if (TryGetIcuVersionNumber(icuDirectory, out int version))
{
IcuVersion = new IcuVersionInfo(icuDirectory, version);
}
}
return doAllAssetsExistInDirectory;
}
#if !NET40
/// <summary>
/// Tries to get the icu native binaries by searching the Runtime
/// ID graph to find the first set of paths that have those binaries.
/// </summary>
/// <returns>Unique relative paths to the native assets; empty if none
/// could be found.</returns>
private static bool TryGetNativeAssetPaths(DependencyContext context, out string[] nativeAssetPaths)
{
var assetPaths = Enumerable.Empty<string>();
if (context == null)
{
nativeAssetPaths = assetPaths.ToArray();
return false;
}
var defaultNativeAssets = context.GetDefaultNativeAssets().ToArray();
// This goes through the runtime graph and tries to find icu native
// asset paths matching that runtime.
foreach (var runtime in context.RuntimeGraph)
{
var nativeAssets = context.GetRuntimeNativeAssets(runtime.Runtime);
assetPaths = nativeAssets.Except(defaultNativeAssets).Where(assetPath => IcuBinaryRegex.IsMatch(assetPath));
if (assetPaths.Any())
break;
}
nativeAssetPaths = assetPaths.ToArray();
return nativeAssetPaths.Length > 0;
}
/// <summary>
/// Given a CompilationLibrary and a base path, tries to construct the
/// nuget package location and returns true if it exists.
///
/// Taken from: https://github.com/dotnet/core-setup/blob/master/src/Microsoft.Extensions.DependencyModel/Resolution/ResolverUtils.cs#L12
/// </summary>
/// <param name="library">Compilation library to try to get the rooted
/// path from.</param>
/// <param name="basePath">Rooted base path to try and get library from.</param>
/// <param name="packagePath">The path for the library if it exists;
/// null otherwise.</param>
/// <returns></returns>
private static bool TryResolvePackagePath(CompilationLibrary library, string basePath, out string packagePath)
{
var path = library.Path;
if (string.IsNullOrEmpty(path))
{
path = Path.Combine(library.Name, library.Version);
}
packagePath = Path.Combine(basePath, path);
return Directory.Exists(packagePath);
}
#endif
/// <summary>
/// Tries to fetch the default package directory for NuGet packages.
/// Taken from:
/// https://github.com/dotnet/core-setup/blob/master/src/Microsoft.Extensions.DependencyModel/Resolution/PackageCompilationAssemblyResolver.cs#L41-L64
/// </summary>
/// <param name="osPlatform">OS Platform to fetch default package
/// directory for.</param>
/// <returns>The path to the default package directory; null if none
/// could be set.</returns>
private static string GetDefaultPackageDirectory(OperatingSystemType osPlatform)
{
var packageDirectory = Environment.GetEnvironmentVariable("NUGET_PACKAGES");
if (!string.IsNullOrEmpty(packageDirectory))
{
return packageDirectory;
}
string basePath;
if (osPlatform == OperatingSystemType.Windows)
{
basePath = Environment.GetEnvironmentVariable("USERPROFILE");
}
else
{
basePath = Environment.GetEnvironmentVariable("HOME");
}
if (string.IsNullOrEmpty(basePath))
{
return null;
}
return Path.Combine(basePath, ".nuget", "packages");
}
}
}
| |
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 Kiko.Web.Areas.HelpPage.ModelDescriptions;
using Kiko.Web.Areas.HelpPage.Models;
namespace Kiko.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using Lucene.Net.Analysis.TokenAttributes;
using System.Reflection;
using Attribute = Lucene.Net.Util.Attribute;
using AttributeSource = Lucene.Net.Util.AttributeSource;
using BytesRef = Lucene.Net.Util.BytesRef;
using IAttribute = Lucene.Net.Util.IAttribute;
namespace Lucene.Net.Analysis
{
/*
* 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 CharTermAttribute = Lucene.Net.Analysis.TokenAttributes.CharTermAttribute;
using IAttributeReflector = Lucene.Net.Util.IAttributeReflector;
/// <summary>
/// A <see cref="Token"/> is an occurrence of a term from the text of a field. It consists of
/// a term's text, the start and end offset of the term in the text of the field,
/// and a type string.
/// <para/>
/// The start and end offsets permit applications to re-associate a token with
/// its source text, e.g., to display highlighted query terms in a document
/// browser, or to show matching text fragments in a KWIC (KeyWord In Context)
/// display, etc.
/// <para/>
/// The type is a string, assigned by a lexical analyzer
/// (a.k.a. tokenizer), naming the lexical or syntactic class that the token
/// belongs to. For example an end of sentence marker token might be implemented
/// with type "eos". The default token type is "word".
/// <para/>
/// A Token can optionally have metadata (a.k.a. payload) in the form of a variable
/// length byte array. Use <see cref="Index.DocsAndPositionsEnum.GetPayload()"/> to retrieve the
/// payloads from the index.
///
/// <para/><para/>
///
/// <para/><b>NOTE:</b> As of 2.9, Token implements all <see cref="IAttribute"/> interfaces
/// that are part of core Lucene and can be found in the <see cref="TokenAttributes"/> namespace.
/// Even though it is not necessary to use <see cref="Token"/> anymore, with the new <see cref="TokenStream"/> API it can
/// be used as convenience class that implements all <see cref="IAttribute"/>s, which is especially useful
/// to easily switch from the old to the new <see cref="TokenStream"/> API.
///
/// <para/><para/>
///
/// <para><see cref="Tokenizer"/>s and <see cref="TokenFilter"/>s should try to re-use a <see cref="Token"/>
/// instance when possible for best performance, by
/// implementing the <see cref="TokenStream.IncrementToken()"/> API.
/// Failing that, to create a new <see cref="Token"/> you should first use
/// one of the constructors that starts with null text. To load
/// the token from a char[] use <see cref="ICharTermAttribute.CopyBuffer(char[], int, int)"/>.
/// To load from a <see cref="string"/> use <see cref="ICharTermAttribute.SetEmpty()"/> followed by
/// <see cref="ICharTermAttribute.Append(string)"/> or <see cref="ICharTermAttribute.Append(string, int, int)"/>.
/// Alternatively you can get the <see cref="Token"/>'s termBuffer by calling either <see cref="ICharTermAttribute.Buffer"/>,
/// if you know that your text is shorter than the capacity of the termBuffer
/// or <see cref="ICharTermAttribute.ResizeBuffer(int)"/>, if there is any possibility
/// that you may need to grow the buffer. Fill in the characters of your term into this
/// buffer, with <see cref="string.ToCharArray(int, int)"/> if loading from a string,
/// or with <see cref="System.Array.Copy(System.Array, int, System.Array, int, int)"/>,
/// and finally call <see cref="ICharTermAttribute.SetLength(int)"/> to
/// set the length of the term text. See <a target="_top"
/// href="https://issues.apache.org/jira/browse/LUCENE-969">LUCENE-969</a>
/// for details.</para>
/// <para>Typical Token reuse patterns:
/// <list type="bullet">
/// <item><description> Copying text from a string (type is reset to <see cref="TypeAttribute.DEFAULT_TYPE"/> if not specified):
/// <code>
/// return reusableToken.Reinit(string, startOffset, endOffset[, type]);
/// </code>
/// </description></item>
/// <item><description> Copying some text from a string (type is reset to <see cref="TypeAttribute.DEFAULT_TYPE"/> if not specified):
/// <code>
/// return reusableToken.Reinit(string, 0, string.Length, startOffset, endOffset[, type]);
/// </code>
/// </description></item>
/// <item><description> Copying text from char[] buffer (type is reset to <see cref="TypeAttribute.DEFAULT_TYPE"/> if not specified):
/// <code>
/// return reusableToken.Reinit(buffer, 0, buffer.Length, startOffset, endOffset[, type]);
/// </code>
/// </description></item>
/// <item><description> Copying some text from a char[] buffer (type is reset to <see cref="TypeAttribute.DEFAULT_TYPE"/> if not specified):
/// <code>
/// return reusableToken.Reinit(buffer, start, end - start, startOffset, endOffset[, type]);
/// </code>
/// </description></item>
/// <item><description> Copying from one one <see cref="Token"/> to another (type is reset to <see cref="TypeAttribute.DEFAULT_TYPE"/> if not specified):
/// <code>
/// return reusableToken.Reinit(source.Buffer, 0, source.Length, source.StartOffset, source.EndOffset[, source.Type]);
/// </code>
/// </description></item>
/// </list>
/// A few things to note:
/// <list type="bullet">
/// <item><description><see cref="Clear()"/> initializes all of the fields to default values. this was changed in contrast to Lucene 2.4, but should affect no one.</description></item>
/// <item><description>Because <see cref="TokenStream"/>s can be chained, one cannot assume that the <see cref="Token"/>'s current type is correct.</description></item>
/// <item><description>The startOffset and endOffset represent the start and offset in the source text, so be careful in adjusting them.</description></item>
/// <item><description>When caching a reusable token, clone it. When injecting a cached token into a stream that can be reset, clone it again.</description></item>
/// </list>
/// </para>
/// <para>
/// <b>Please note:</b> With Lucene 3.1, the <see cref="CharTermAttribute.ToString()"/> method had to be changed to match the
/// <see cref="Support.ICharSequence"/> interface introduced by the interface <see cref="ICharTermAttribute"/>.
/// this method now only prints the term text, no additional information anymore.
/// </para>
/// </summary>
public class Token : CharTermAttribute, ITypeAttribute, IPositionIncrementAttribute, IFlagsAttribute, IOffsetAttribute, IPayloadAttribute, IPositionLengthAttribute
{
private int startOffset, endOffset;
private string type = TypeAttribute.DEFAULT_TYPE;
private int flags;
private BytesRef payload;
private int positionIncrement = 1;
private int positionLength = 1;
/// <summary>
/// Constructs a <see cref="Token"/> will null text. </summary>
public Token()
{
string s = "fooobar";
s.ToCharArray();
}
/// <summary>
/// Constructs a <see cref="Token"/> with null text and start & end
/// offsets. </summary>
/// <param name="start"> start offset in the source text </param>
/// <param name="end"> end offset in the source text </param>
public Token(int start, int end)
{
CheckOffsets(start, end);
startOffset = start;
endOffset = end;
}
/// <summary>
/// Constructs a <see cref="Token"/> with null text and start & end
/// offsets plus the <see cref="Token"/> type. </summary>
/// <param name="start"> start offset in the source text </param>
/// <param name="end"> end offset in the source text </param>
/// <param name="typ"> the lexical type of this <see cref="Token"/> </param>
public Token(int start, int end, string typ)
{
CheckOffsets(start, end);
startOffset = start;
endOffset = end;
type = typ;
}
/// <summary>
/// Constructs a <see cref="Token"/> with null text and start & end
/// offsets plus flags. NOTE: flags is EXPERIMENTAL. </summary>
/// <param name="start"> start offset in the source text </param>
/// <param name="end"> end offset in the source text </param>
/// <param name="flags"> The bits to set for this token </param>
public Token(int start, int end, int flags)
{
CheckOffsets(start, end);
startOffset = start;
endOffset = end;
this.flags = flags;
}
/// <summary>
/// Constructs a <see cref="Token"/> with the given term text, and start
/// & end offsets. The type defaults to "word."
/// <b>NOTE:</b> for better indexing speed you should
/// instead use the char[] termBuffer methods to set the
/// term text. </summary>
/// <param name="text"> term text </param>
/// <param name="start"> start offset in the source text </param>
/// <param name="end"> end offset in the source text </param>
public Token(string text, int start, int end)
{
CheckOffsets(start, end);
Append(text);
startOffset = start;
endOffset = end;
}
/// <summary>
/// Constructs a <see cref="Token"/> with the given text, start and end
/// offsets, & type. <b>NOTE:</b> for better indexing
/// speed you should instead use the char[] termBuffer
/// methods to set the term text. </summary>
/// <param name="text"> term text </param>
/// <param name="start"> start offset in the source text </param>
/// <param name="end"> end offset in the source text </param>
/// <param name="typ"> token type </param>
public Token(string text, int start, int end, string typ)
{
CheckOffsets(start, end);
Append(text);
startOffset = start;
endOffset = end;
type = typ;
}
/// <summary>
/// Constructs a <see cref="Token"/> with the given text, start and end
/// offsets, & type. <b>NOTE:</b> for better indexing
/// speed you should instead use the char[] termBuffer
/// methods to set the term text. </summary>
/// <param name="text"> term text </param>
/// <param name="start"> start offset in the source text </param>
/// <param name="end"> end offset in the source text </param>
/// <param name="flags"> token type bits </param>
public Token(string text, int start, int end, int flags)
{
CheckOffsets(start, end);
Append(text);
startOffset = start;
endOffset = end;
this.flags = flags;
}
/// <summary>
/// Constructs a <see cref="Token"/> with the given term buffer (offset
/// & length), start and end offsets
/// </summary>
/// <param name="startTermBuffer"> buffer containing term text </param>
/// <param name="termBufferOffset"> the index in the buffer of the first character </param>
/// <param name="termBufferLength"> number of valid characters in the buffer </param>
/// <param name="start"> start offset in the source text </param>
/// <param name="end"> end offset in the source text </param>
public Token(char[] startTermBuffer, int termBufferOffset, int termBufferLength, int start, int end)
{
CheckOffsets(start, end);
CopyBuffer(startTermBuffer, termBufferOffset, termBufferLength);
startOffset = start;
endOffset = end;
}
/// <summary>
/// Gets or Sets the position increment (the distance from the prior term). The default value is one.
/// </summary>
/// <exception cref="System.ArgumentException"> if value is set to a negative value. </exception>
/// <seealso cref="IPositionIncrementAttribute"/>
public virtual int PositionIncrement
{
set
{
if (value < 0)
{
throw new System.ArgumentException("Increment must be zero or greater: " + value);
}
this.positionIncrement = value;
}
get
{
return positionIncrement;
}
}
/// <summary>
/// Gets or Sets the position length of this <see cref="Token"/> (how many positions this token
/// spans).
/// <para/>
/// The default value is one.
/// </summary>
/// <exception cref="System.ArgumentException"> if value
/// is set to zero or negative. </exception>
/// <seealso cref="IPositionLengthAttribute"/>
public virtual int PositionLength
{
set
{
this.positionLength = value;
}
get
{
return positionLength;
}
}
/// <summary>
/// Returns this <see cref="Token"/>'s starting offset, the position of the first character
/// corresponding to this token in the source text.
/// <para/>
/// Note that the difference between <see cref="EndOffset"/> and <see cref="StartOffset"/>
/// may not be equal to termText.Length, as the term text may have been altered by a
/// stemmer or some other filter.
/// </summary>
/// <seealso cref="SetOffset(int, int)"/>
/// <seealso cref="IOffsetAttribute"/>
public int StartOffset
{
get { return startOffset; }
}
/// <summary>
/// Returns this <see cref="Token"/>'s ending offset, one greater than the position of the
/// last character corresponding to this token in the source text. The length
/// of the token in the source text is (<code>EndOffset</code> - <see cref="StartOffset"/>).
/// </summary>
/// <seealso cref="SetOffset(int, int)"/>
/// <seealso cref="IOffsetAttribute"/>
public int EndOffset
{
get { return endOffset; }
}
/// <summary>
/// Set the starting and ending offset.
/// </summary>
/// <exception cref="System.ArgumentException"> If <paramref name="startOffset"/> or <paramref name="endOffset"/>
/// are negative, or if <paramref name="startOffset"/> is greater than
/// <paramref name="endOffset"/> </exception>
/// <seealso cref="StartOffset"/>
/// <seealso cref="EndOffset"/>
/// <seealso cref="IOffsetAttribute"/>
public virtual void SetOffset(int startOffset, int endOffset)
{
CheckOffsets(startOffset, endOffset);
this.startOffset = startOffset;
this.endOffset = endOffset;
}
/// <summary>Gets or Sets this <see cref="Token"/>'s lexical type. Defaults to "word". </summary>
public string Type
{
get { return type; }
set { this.type = value; }
}
/// <summary>
/// Get the bitset for any bits that have been set.
/// <para/>
/// This is completely distinct from <see cref="ITypeAttribute.Type" />, although they do share similar purposes.
/// The flags can be used to encode information about the token for use by other <see cref="Lucene.Net.Analysis.TokenFilter" />s.
/// </summary>
/// <seealso cref="IFlagsAttribute"/>
public virtual int Flags
{
get
{
return flags;
}
set
{
this.flags = value;
}
}
/// <summary>
/// Gets or Sets this <see cref="Token"/>'s payload.
/// </summary>
/// <seealso cref="IPayloadAttribute"/>
public virtual BytesRef Payload
{
get
{
return this.payload;
}
set
{
this.payload = value;
}
}
/// <summary>
/// Resets the term text, payload, flags, and positionIncrement,
/// startOffset, endOffset and token type to default.
/// </summary>
public override void Clear()
{
base.Clear();
payload = null;
positionIncrement = 1;
flags = 0;
startOffset = endOffset = 0;
type = TokenAttributes.TypeAttribute.DEFAULT_TYPE;
}
public override object Clone()
{
var t = (Token)base.Clone();
// Do a deep clone
if (payload != null)
{
t.payload = (BytesRef)payload.Clone();
}
return t;
}
/// <summary>
/// Makes a clone, but replaces the term buffer &
/// start/end offset in the process. This is more
/// efficient than doing a full clone (and then calling
/// <see cref="ICharTermAttribute.CopyBuffer"/>) because it saves a wasted copy of the old
/// termBuffer.
/// </summary>
public virtual Token Clone(char[] newTermBuffer, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset)
{
var t = new Token(newTermBuffer, newTermOffset, newTermLength, newStartOffset, newEndOffset)
{
positionIncrement = positionIncrement,
flags = flags,
type = type
};
if (payload != null)
{
t.payload = (BytesRef)payload.Clone();
}
return t;
}
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
if (obj is Token)
{
var other = (Token)obj;
return (startOffset == other.startOffset &&
endOffset == other.endOffset &&
flags == other.flags &&
positionIncrement == other.positionIncrement &&
(type == null ? other.type == null : type.Equals(other.type, System.StringComparison.Ordinal)) &&
(payload == null ? other.payload == null : payload.Equals(other.payload)) &&
base.Equals(obj)
);
}
else
{
return false;
}
}
public override int GetHashCode()
{
int code = base.GetHashCode();
code = code * 31 + startOffset;
code = code * 31 + endOffset;
code = code * 31 + flags;
code = code * 31 + positionIncrement;
if (type != null)
{
code = code * 31 + type.GetHashCode();
}
if (payload != null)
{
code = code * 31 + payload.GetHashCode();
}
return code;
}
// like clear() but doesn't clear termBuffer/text
private void ClearNoTermBuffer()
{
payload = null;
positionIncrement = 1;
flags = 0;
startOffset = endOffset = 0;
type = TokenAttributes.TypeAttribute.DEFAULT_TYPE;
}
/// <summary>
/// Shorthand for calling <see cref="Clear"/>,
/// <see cref="ICharTermAttribute.CopyBuffer(char[], int, int)"/>,
/// <see cref="SetOffset"/>,
/// <see cref="Type"/> (set) </summary>
/// <returns> this <see cref="Token"/> instance </returns>
public virtual Token Reinit(char[] newTermBuffer, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset, string newType)
{
CheckOffsets(newStartOffset, newEndOffset);
ClearNoTermBuffer();
CopyBuffer(newTermBuffer, newTermOffset, newTermLength);
payload = null;
positionIncrement = 1;
startOffset = newStartOffset;
endOffset = newEndOffset;
type = newType;
return this;
}
/// <summary>
/// Shorthand for calling <see cref="Clear"/>,
/// <see cref="ICharTermAttribute.CopyBuffer(char[], int, int)"/>,
/// <see cref="SetOffset"/>,
/// <see cref="Type"/> (set) on <see cref="TypeAttribute.DEFAULT_TYPE"/> </summary>
/// <returns> this <see cref="Token"/> instance </returns>
public virtual Token Reinit(char[] newTermBuffer, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset)
{
CheckOffsets(newStartOffset, newEndOffset);
ClearNoTermBuffer();
CopyBuffer(newTermBuffer, newTermOffset, newTermLength);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = TokenAttributes.TypeAttribute.DEFAULT_TYPE;
return this;
}
/// <summary>
/// Shorthand for calling <see cref="Clear"/>,
/// <see cref="ICharTermAttribute.Append(string)"/>,
/// <see cref="SetOffset"/>,
/// <see cref="Type"/> (set) </summary>
/// <returns> this <see cref="Token"/> instance </returns>
public virtual Token Reinit(string newTerm, int newStartOffset, int newEndOffset, string newType)
{
CheckOffsets(newStartOffset, newEndOffset);
Clear();
Append(newTerm);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = newType;
return this;
}
/// <summary>
/// Shorthand for calling <see cref="Clear"/>,
/// <see cref="ICharTermAttribute.Append(string, int, int)"/>,
/// <see cref="SetOffset"/>,
/// <see cref="Type"/> (set) </summary>
/// <returns> this <see cref="Token"/> instance </returns>
public virtual Token Reinit(string newTerm, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset, string newType)
{
CheckOffsets(newStartOffset, newEndOffset);
Clear();
Append(newTerm, newTermOffset, newTermOffset + newTermLength);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = newType;
return this;
}
/// <summary>
/// Shorthand for calling <see cref="Clear"/>,
/// <see cref="ICharTermAttribute.Append(string)"/>,
/// <see cref="SetOffset"/>,
/// <see cref="Type"/> (set) on <see cref="TypeAttribute.DEFAULT_TYPE"/> </summary>
/// <returns> this <see cref="Token"/> instance </returns>
public virtual Token Reinit(string newTerm, int newStartOffset, int newEndOffset)
{
CheckOffsets(newStartOffset, newEndOffset);
Clear();
Append(newTerm);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = TokenAttributes.TypeAttribute.DEFAULT_TYPE;
return this;
}
/// <summary>
/// Shorthand for calling <see cref="Clear"/>,
/// <see cref="ICharTermAttribute.Append(string, int, int)"/>,
/// <see cref="SetOffset"/>,
/// <see cref="Type"/> (set) on <see cref="TypeAttribute.DEFAULT_TYPE"/> </summary>
/// <returns> this <see cref="Token"/> instance </returns>
public virtual Token Reinit(string newTerm, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset)
{
CheckOffsets(newStartOffset, newEndOffset);
Clear();
Append(newTerm, newTermOffset, newTermOffset + newTermLength);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = TokenAttributes.TypeAttribute.DEFAULT_TYPE;
return this;
}
/// <summary>
/// Copy the prototype token's fields into this one. Note: Payloads are shared. </summary>
/// <param name="prototype"> source <see cref="Token"/> to copy fields from </param>
public virtual void Reinit(Token prototype)
{
CopyBuffer(prototype.Buffer, 0, prototype.Length);
positionIncrement = prototype.positionIncrement;
flags = prototype.flags;
startOffset = prototype.startOffset;
endOffset = prototype.endOffset;
type = prototype.type;
payload = prototype.payload;
}
/// <summary>
/// Copy the prototype token's fields into this one, with a different term. Note: Payloads are shared. </summary>
/// <param name="prototype"> existing <see cref="Token"/> </param>
/// <param name="newTerm"> new term text </param>
public virtual void Reinit(Token prototype, string newTerm)
{
SetEmpty().Append(newTerm);
positionIncrement = prototype.positionIncrement;
flags = prototype.flags;
startOffset = prototype.startOffset;
endOffset = prototype.endOffset;
type = prototype.type;
payload = prototype.payload;
}
/// <summary>
/// Copy the prototype token's fields into this one, with a different term. Note: Payloads are shared. </summary>
/// <param name="prototype"> existing <see cref="Token"/> </param>
/// <param name="newTermBuffer"> buffer containing new term text </param>
/// <param name="offset"> the index in the buffer of the first character </param>
/// <param name="length"> number of valid characters in the buffer </param>
public virtual void Reinit(Token prototype, char[] newTermBuffer, int offset, int length)
{
CopyBuffer(newTermBuffer, offset, length);
positionIncrement = prototype.positionIncrement;
flags = prototype.flags;
startOffset = prototype.startOffset;
endOffset = prototype.endOffset;
type = prototype.type;
payload = prototype.payload;
}
public override void CopyTo(IAttribute target)
{
var to = target as Token;
if (to != null)
{
to.Reinit(this);
// reinit shares the payload, so clone it:
if (payload != null)
{
to.payload = (BytesRef)payload.Clone();
}
}
else
{
base.CopyTo(target);
((IOffsetAttribute)target).SetOffset(startOffset, endOffset);
((IPositionIncrementAttribute)target).PositionIncrement = positionIncrement;
((IPayloadAttribute)target).Payload = (payload == null) ? null : (BytesRef)payload.Clone();
((IFlagsAttribute)target).Flags = flags;
((ITypeAttribute)target).Type = type;
}
}
public override void ReflectWith(IAttributeReflector reflector)
{
base.ReflectWith(reflector);
reflector.Reflect(typeof(IOffsetAttribute), "startOffset", startOffset);
reflector.Reflect(typeof(IOffsetAttribute), "endOffset", endOffset);
reflector.Reflect(typeof(IPositionIncrementAttribute), "positionIncrement", positionIncrement);
reflector.Reflect(typeof(IPayloadAttribute), "payload", payload);
reflector.Reflect(typeof(IFlagsAttribute), "flags", flags);
reflector.Reflect(typeof(ITypeAttribute), "type", type);
}
private void CheckOffsets(int startOffset, int endOffset)
{
if (startOffset < 0 || endOffset < startOffset)
{
throw new System.ArgumentException("startOffset must be non-negative, and endOffset must be >= startOffset, " + "startOffset=" + startOffset + ",endOffset=" + endOffset);
}
}
/// <summary>
/// Convenience factory that returns <see cref="Token"/> as implementation for the basic
/// attributes and return the default impl (with "Impl" appended) for all other
/// attributes.
/// @since 3.0
/// </summary>
public static readonly AttributeSource.AttributeFactory TOKEN_ATTRIBUTE_FACTORY = new TokenAttributeFactory(AttributeSource.AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY);
/// <summary>
/// <b>Expert:</b> Creates a <see cref="TokenAttributeFactory"/> returning <see cref="Token"/> as instance for the basic attributes
/// and for all other attributes calls the given delegate factory.
/// @since 3.0
/// </summary>
public sealed class TokenAttributeFactory : AttributeSource.AttributeFactory
{
internal readonly AttributeSource.AttributeFactory @delegate;
/// <summary>
/// <b>Expert</b>: Creates an <see cref="AttributeSource.AttributeFactory"/> returning <see cref="Token"/> as instance for the basic attributes
/// and for all other attributes calls the given delegate factory.
/// </summary>
public TokenAttributeFactory(AttributeSource.AttributeFactory @delegate)
{
this.@delegate = @delegate;
}
public override Attribute CreateAttributeInstance<T>()
{
var attClass = typeof(T);
return attClass.GetTypeInfo().IsAssignableFrom(typeof(Token).GetTypeInfo()) ? new Token() : @delegate.CreateAttributeInstance<T>();
}
public override bool Equals(object other)
{
if (this == other)
{
return true;
}
var af = other as TokenAttributeFactory;
if (af != null)
{
return this.@delegate.Equals(af.@delegate);
}
return false;
}
public override int GetHashCode()
{
return @delegate.GetHashCode() ^ 0x0a45aa31;
}
}
}
}
| |
using UnityEngine;
// Glow uses the alpha channel as a source of "extra brightness".
// All builtin Unity shaders output baseTexture.alpha * color.alpha, plus
// specularHighlight * specColor.alpha into that.
// Usually you'd want either to make base textures to have zero alpha; or
// set the color to have zero alpha (by default alpha is 0.5).
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu("Image Effects/Glow (island)")]
public class GlowEffectIsland : MonoBehaviour
{
/// The brightness of the glow. Values larger than one give extra "boost".
public float glowIntensity = 1.5f;
/// Blur iterations - larger number means more blur.
public int blurIterations = 3;
/// Blur spread for each iteration. Lower values
/// give better looking blur, but require more iterations to
/// get large blurs. Value is usually between 0.5 and 1.0.
public float blurSpread = 0.7f;
/// Tint glow with this color. Alpha adds additional glow everywhere.
public Color glowTint = new Color(1,1,1,0);
// --------------------------------------------------------
// The final composition shader:
// adds (glow color * glow alpha * amount) to the original image.
// In the combiner glow amount can be only in 0..1 range; we apply extra
// amount during the blurring phase.
private static string compositeMatString =
@"Shader ""GlowCompose"" {
Properties {
_Color (""Glow Amount"", Color) = (1,1,1,1)
_MainTex ("""", RECT) = ""white"" {}
}
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off Fog { Mode Off }
Blend One One
SetTexture [_MainTex] {constantColor [_Color] combine constant * texture DOUBLE}
}
}
Fallback off
}";
static Material m_CompositeMaterial = null;
protected static Material compositeMaterial {
get {
if (m_CompositeMaterial == null) {
m_CompositeMaterial = new Material (compositeMatString);
m_CompositeMaterial.hideFlags = HideFlags.HideAndDontSave;
m_CompositeMaterial.shader.hideFlags = HideFlags.HideAndDontSave;
}
return m_CompositeMaterial;
}
}
// --------------------------------------------------------
// The blur iteration shader.
// Basically it just takes 4 texture samples and averages them.
// By applying it repeatedly and spreading out sample locations
// we get a Gaussian blur approximation.
// The alpha value in _Color would normally be 0.25 (to average 4 samples),
// however if we have glow amount larger than 1 then we increase this.
private static string blurMatString =
@"Shader ""GlowConeTap"" {
Properties {
_Color (""Blur Boost"", Color) = (0,0,0,0.25)
_MainTex ("""", RECT) = ""white"" {}
}
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off Fog { Mode Off }
SetTexture [_MainTex] {constantColor [_Color] combine texture * constant alpha}
SetTexture [_MainTex] {constantColor [_Color] combine texture * constant + previous}
SetTexture [_MainTex] {constantColor [_Color] combine texture * constant + previous}
SetTexture [_MainTex] {constantColor [_Color] combine texture * constant + previous}
}
}
Fallback off
}";
static Material m_BlurMaterial = null;
protected static Material blurMaterial {
get {
if (m_BlurMaterial == null) {
m_BlurMaterial = new Material( blurMatString );
m_BlurMaterial.hideFlags = HideFlags.HideAndDontSave;
m_BlurMaterial.shader.hideFlags = HideFlags.HideAndDontSave;
}
return m_BlurMaterial;
}
}
// --------------------------------------------------------
// The image downsample shaders for each brightness mode.
// It is in external assets as it's quite complex and uses Cg.
public Shader downsampleShader;
Material m_DownsampleMaterial = null;
protected Material downsampleMaterial {
get {
if (m_DownsampleMaterial == null) {
m_DownsampleMaterial = new Material( downsampleShader );
m_DownsampleMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_DownsampleMaterial;
}
}
// --------------------------------------------------------
// finally, the actual code
protected void OnDisable()
{
if( m_CompositeMaterial ) {
DestroyImmediate( m_CompositeMaterial.shader );
DestroyImmediate( m_CompositeMaterial );
}
if( m_BlurMaterial ) {
DestroyImmediate( m_BlurMaterial.shader );
DestroyImmediate( m_BlurMaterial );
}
if( m_DownsampleMaterial )
DestroyImmediate( m_DownsampleMaterial );
}
public bool IsSupported()
{
// Disable if we don't support image effects
if (!SystemInfo.supportsImageEffects)
return false;
if( downsampleShader == null )
{
Debug.LogWarning ("No downsample shader assigned! Disabling glow.");
return false;
}
// Disable if the shader can't run on the users graphics card
if( !blurMaterial.shader.isSupported )
return false;
if( !compositeMaterial.shader.isSupported )
return false;
if( !downsampleMaterial.shader.isSupported )
return false;
return true;
}
protected void Start()
{
if( !IsSupported() )
enabled = false;
}
// Performs one blur iteration.
public void FourTapCone (RenderTexture source, RenderTexture dest, int iteration)
{
RenderTexture.active = dest;
blurMaterial.SetTexture("_MainTex", source);
float offsetX = (.5F+iteration*blurSpread) / (float)source.width;
float offsetY = (.5F+iteration*blurSpread) / (float)source.height;
GL.PushMatrix ();
GL.LoadOrtho ();
for (int i = 0; i < blurMaterial.passCount; i++) {
blurMaterial.SetPass (i);
Render4TapQuad( dest, offsetX, offsetY );
}
GL.PopMatrix ();
}
// Downsamples the texture to a quarter resolution.
private void DownSample4x (RenderTexture source, RenderTexture dest)
{
downsampleMaterial.color = new Color( glowTint.r, glowTint.g, glowTint.b, glowTint.a/4.0f );
ImageEffects.BlitWithMaterial( downsampleMaterial, source, dest );
}
// Called by the camera to apply the image effect
void OnRenderImage (RenderTexture source, RenderTexture destination)
{
// Clamp parameters to sane values
glowIntensity = Mathf.Clamp( glowIntensity, 0.0f, 10.0f );
blurIterations = Mathf.Clamp( blurIterations, 0, 30 );
blurSpread = Mathf.Clamp( blurSpread, 0.5f, 1.0f );
RenderTexture buffer = RenderTexture.GetTemporary(source.width/4, source.height/4, 0);
RenderTexture buffer2 = RenderTexture.GetTemporary(source.width/4, source.height/4, 0);
// Copy source to the 4x4 smaller texture.
DownSample4x (source, buffer);
// Blur the small texture
float extraBlurBoost = Mathf.Clamp01( (glowIntensity - 1.0f) / 4.0f );
blurMaterial.color = new Color( 1F, 1F, 1F, 0.25f + extraBlurBoost );
bool oddEven = true;
for(int i = 0; i < blurIterations; i++)
{
if( oddEven )
FourTapCone (buffer, buffer2, i);
else
FourTapCone (buffer2, buffer, i);
oddEven = !oddEven;
}
ImageEffects.Blit(source,destination);
if( oddEven )
BlitGlow(buffer, destination);
else
BlitGlow(buffer2, destination);
RenderTexture.ReleaseTemporary(buffer);
RenderTexture.ReleaseTemporary(buffer2);
}
public void BlitGlow( RenderTexture source, RenderTexture dest )
{
compositeMaterial.color = new Color(1F, 1F, 1F, Mathf.Clamp01(glowIntensity));
ImageEffects.BlitWithMaterial( compositeMaterial, source, dest );
}
private static void Render4TapQuad( RenderTexture dest, float offsetX, float offsetY )
{
GL.Begin( GL.QUADS );
// Direct3D needs interesting texel offsets!
Vector2 off = Vector2.zero;
if( dest != null )
off = dest.GetTexelOffset() * 0.75f;
Set4TexCoords( off.x, off.y, offsetX, offsetY );
GL.Vertex3( 0,0, .1f );
Set4TexCoords( 1.0f + off.x, off.y, offsetX, offsetY );
GL.Vertex3( 1,0, .1f );
Set4TexCoords( 1.0f + off.x, 1.0f + off.y, offsetX, offsetY );
GL.Vertex3( 1,1,.1f );
Set4TexCoords( off.x, 1.0f + off.y, offsetX, offsetY );
GL.Vertex3( 0,1,.1f );
GL.End();
}
private static void Set4TexCoords( float x, float y, float offsetX, float offsetY )
{
GL.MultiTexCoord2( 0, x - offsetX, y - offsetY );
GL.MultiTexCoord2( 1, x + offsetX, y - offsetY );
GL.MultiTexCoord2( 2, x + offsetX, y + offsetY );
GL.MultiTexCoord2( 3, x - offsetX, y + offsetY );
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Runtime.InteropServices.TCEAdapterGen {
using System.Runtime.InteropServices.ComTypes;
using ubyte = System.Byte;
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Threading;
using System.Diagnostics.Contracts;
internal class EventProviderWriter
{
private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
private readonly Type[] MonitorEnterParamTypes = new Type[] { typeof(Object), Type.GetType("System.Boolean&") };
public EventProviderWriter( ModuleBuilder OutputModule, String strDestTypeName, Type EventItfType, Type SrcItfType, Type SinkHelperType )
{
m_OutputModule = OutputModule;
m_strDestTypeName = strDestTypeName;
m_EventItfType = EventItfType;
m_SrcItfType = SrcItfType;
m_SinkHelperType = SinkHelperType;
}
public Type Perform()
{
// Create the event provider class.
TypeBuilder OutputTypeBuilder = m_OutputModule.DefineType(
m_strDestTypeName,
TypeAttributes.Sealed | TypeAttributes.NotPublic,
typeof(Object),
new Type[]{m_EventItfType, typeof(IDisposable)}
);
// Create the event source field.
FieldBuilder fbCPC = OutputTypeBuilder.DefineField(
"m_ConnectionPointContainer",
typeof(IConnectionPointContainer),
FieldAttributes.Private
);
// Create array of event sink helpers.
FieldBuilder fbSinkHelper = OutputTypeBuilder.DefineField(
"m_aEventSinkHelpers",
typeof(ArrayList),
FieldAttributes.Private
);
// Define the connection point field.
FieldBuilder fbEventCP = OutputTypeBuilder.DefineField(
"m_ConnectionPoint",
typeof(IConnectionPoint),
FieldAttributes.Private
);
// Define the InitXXX method.
MethodBuilder InitSrcItfMethodBuilder =
DefineInitSrcItfMethod( OutputTypeBuilder, m_SrcItfType, fbSinkHelper, fbEventCP, fbCPC );
// Process all the methods in the event interface.
MethodInfo[] aMethods = TCEAdapterGenerator.GetNonPropertyMethods(m_SrcItfType);
for ( int cMethods = 0; cMethods < aMethods.Length; cMethods++ )
{
if ( m_SrcItfType == aMethods[cMethods].DeclaringType )
{
// Define the add_XXX method.
MethodBuilder AddEventMethodBuilder = DefineAddEventMethod(
OutputTypeBuilder, aMethods[cMethods], m_SinkHelperType, fbSinkHelper, fbEventCP, InitSrcItfMethodBuilder );
// Define the remove_XXX method.
MethodBuilder RemoveEventMethodBuilder = DefineRemoveEventMethod(
OutputTypeBuilder, aMethods[cMethods], m_SinkHelperType, fbSinkHelper, fbEventCP );
}
}
// Define the constructor.
DefineConstructor( OutputTypeBuilder, fbCPC );
// Define the finalize method.
MethodBuilder FinalizeMethod = DefineFinalizeMethod( OutputTypeBuilder, m_SinkHelperType, fbSinkHelper, fbEventCP );
// Define the Dispose method.
DefineDisposeMethod( OutputTypeBuilder, FinalizeMethod);
return OutputTypeBuilder.CreateType();
}
private MethodBuilder DefineAddEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo SrcItfMethod, Type SinkHelperClass, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP, MethodBuilder mbInitSrcItf )
{
Type[] aParamTypes;
// Find the delegate on the event sink helper.
FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
// Find the cookie on the event sink helper.
FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
// Retrieve the sink helper's constructor.
ConstructorInfo SinkHelperCons = SinkHelperClass.GetConstructor(EventProviderWriter.DefaultLookup | BindingFlags.NonPublic, null, new Type[0], null );
Contract.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper");
// Retrieve the IConnectionPoint.Advise method.
MethodInfo CPAdviseMethod = typeof(IConnectionPoint).GetMethod( "Advise" );
Contract.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise");
// Retrieve the ArrayList.Add method.
aParamTypes = new Type[1];
aParamTypes[0] = typeof(Object);
MethodInfo ArrayListAddMethod = typeof(ArrayList).GetMethod( "Add", aParamTypes, null );
Contract.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add");
// Retrieve the Monitor.Enter() method.
MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod( "Enter", MonitorEnterParamTypes, null );
Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
// Retrieve the Monitor.Exit() method.
aParamTypes[0] = typeof(Object);
MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
// Define the add_XXX method.
Type[] parameterTypes;
parameterTypes = new Type[1];
parameterTypes[0] = DelegateField.FieldType;
MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
"add_" + SrcItfMethod.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
null,
parameterTypes );
ILGenerator il = Meth.GetILGenerator();
// Define a label for the m_IFooEventsCP comparision.
Label EventCPNonNullLabel = il.DefineLabel();
// Declare the local variables.
LocalBuilder ltSinkHelper = il.DeclareLocal( SinkHelperClass );
LocalBuilder ltCookie = il.DeclareLocal( typeof(Int32) );
LocalBuilder ltLockTaken = il.DeclareLocal( typeof(bool) );
// Generate the following code:
// try {
il.BeginExceptionBlock();
// Generate the following code:
// Monitor.Enter(this, ref lockTaken);
il.Emit(OpCodes.Ldarg, (short)0);
il.Emit(OpCodes.Ldloca_S, ltLockTaken);
il.Emit(OpCodes.Call, MonitorEnterMethod);
// Generate the following code:
// if ( m_IFooEventsCP != null ) goto EventCPNonNullLabel;
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbEventCP );
il.Emit( OpCodes.Brtrue, EventCPNonNullLabel );
// Generate the following code:
// InitIFooEvents();
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Call, mbInitSrcItf );
// Mark this as label to jump to if the CP is not null.
il.MarkLabel( EventCPNonNullLabel );
// Generate the following code:
// IFooEvents_SinkHelper SinkHelper = new IFooEvents_SinkHelper;
il.Emit( OpCodes.Newobj, SinkHelperCons );
il.Emit( OpCodes.Stloc, ltSinkHelper );
// Generate the following code:
// dwCookie = 0;
il.Emit( OpCodes.Ldc_I4_0 );
il.Emit( OpCodes.Stloc, ltCookie );
// Generate the following code:
// m_IFooEventsCP.Advise( SinkHelper, dwCookie );
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbEventCP );
il.Emit( OpCodes.Ldloc, ltSinkHelper );
il.Emit( OpCodes.Castclass, typeof(Object) );
il.Emit( OpCodes.Ldloca, ltCookie );
il.Emit( OpCodes.Callvirt, CPAdviseMethod );
// Generate the following code:
// SinkHelper.m_dwCookie = dwCookie;
il.Emit( OpCodes.Ldloc, ltSinkHelper );
il.Emit( OpCodes.Ldloc, ltCookie );
il.Emit( OpCodes.Stfld, CookieField );
// Generate the following code:
// SinkHelper.m_FooDelegate = d;
il.Emit( OpCodes.Ldloc, ltSinkHelper );
il.Emit( OpCodes.Ldarg, (short)1 );
il.Emit( OpCodes.Stfld, DelegateField );
// Generate the following code:
// m_aIFooEventsHelpers.Add( SinkHelper );
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
il.Emit( OpCodes.Ldloc, ltSinkHelper );
il.Emit( OpCodes.Castclass, typeof(Object) );
il.Emit( OpCodes.Callvirt, ArrayListAddMethod );
il.Emit( OpCodes.Pop );
// Generate the following code:
// } finally {
il.BeginFinallyBlock();
// Generate the following code:
// if (lockTaken)
// Monitor.Exit(this);
Label skipExit = il.DefineLabel();
il.Emit( OpCodes.Ldloc, ltLockTaken );
il.Emit( OpCodes.Brfalse_S, skipExit );
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Call, MonitorExitMethod );
il.MarkLabel(skipExit);
// Generate the following code:
// }
il.EndExceptionBlock();
// Generate the return opcode.
il.Emit( OpCodes.Ret );
return Meth;
}
private MethodBuilder DefineRemoveEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo SrcItfMethod, Type SinkHelperClass, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP )
{
Type[] aParamTypes;
// Find the delegate on the event sink helper.
FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
// Find the cookie on the event sink helper.
FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
// Retrieve the ArrayList.RemoveAt method.
aParamTypes = new Type[1];
aParamTypes[0] = typeof(Int32);
MethodInfo ArrayListRemoveMethod = typeof(ArrayList).GetMethod( "RemoveAt", aParamTypes, null );
Contract.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()");
// Retrieve the ArrayList.Item property get method.
PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
// Retrieve the ArrayList.Count property get method.
PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
// Retrieve the Delegate.Equals() method.
aParamTypes[0] = typeof(Delegate);
MethodInfo DelegateEqualsMethod = typeof(Delegate).GetMethod( "Equals", aParamTypes, null );
Contract.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()");
// Retrieve the Monitor.Enter() method.
MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
// Retrieve the Monitor.Exit() method.
aParamTypes[0] = typeof(Object);
MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
// Retrieve the ConnectionPoint.Unadvise() method.
MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
// Retrieve the Marshal.ReleaseComObject() method.
MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
// Define the remove_XXX method.
Type[] parameterTypes;
parameterTypes = new Type[1];
parameterTypes[0] = DelegateField.FieldType;
MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
"remove_" + SrcItfMethod.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
null,
parameterTypes );
ILGenerator il = Meth.GetILGenerator();
// Declare the local variables.
LocalBuilder ltNumSinkHelpers = il.DeclareLocal( typeof(Int32) );
LocalBuilder ltSinkHelperCounter = il.DeclareLocal( typeof(Int32) );
LocalBuilder ltCurrSinkHelper = il.DeclareLocal( SinkHelperClass );
LocalBuilder ltLockTaken = il.DeclareLocal(typeof(bool));
// Generate the labels for the for loop.
Label ForBeginLabel = il.DefineLabel();
Label ForEndLabel = il.DefineLabel();
Label FalseIfLabel = il.DefineLabel();
Label MonitorExitLabel = il.DefineLabel();
// Generate the following code:
// try {
il.BeginExceptionBlock();
// Generate the following code:
// Monitor.Enter(this, ref lockTaken);
il.Emit(OpCodes.Ldarg, (short)0);
il.Emit(OpCodes.Ldloca_S, ltLockTaken);
il.Emit(OpCodes.Call, MonitorEnterMethod);
// Generate the following code:
// if ( m_aIFooEventsHelpers == null ) goto ForEndLabel;
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
il.Emit( OpCodes.Brfalse, ForEndLabel );
// Generate the following code:
// int NumEventHelpers = m_aIFooEventsHelpers.Count;
// int cEventHelpers = 0;
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
il.Emit( OpCodes.Callvirt, ArrayListSizeGetMethod );
il.Emit( OpCodes.Stloc, ltNumSinkHelpers );
il.Emit( OpCodes.Ldc_I4, 0 );
il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
// Generate the following code:
// if ( 0 >= NumEventHelpers ) goto ForEndLabel;
il.Emit( OpCodes.Ldc_I4, 0 );
il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
il.Emit( OpCodes.Bge, ForEndLabel );
// Mark this as the beginning of the for loop's body.
il.MarkLabel( ForBeginLabel );
// Generate the following code:
// CurrentHelper = (IFooEvents_SinkHelper)m_aIFooEventsHelpers.Get( cEventHelpers );
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
il.Emit( OpCodes.Callvirt, ArrayListItemGetMethod );
il.Emit( OpCodes.Castclass, SinkHelperClass );
il.Emit( OpCodes.Stloc, ltCurrSinkHelper );
// Generate the following code:
// if ( CurrentHelper.m_FooDelegate )
il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
il.Emit( OpCodes.Ldfld, DelegateField );
il.Emit( OpCodes.Ldnull );
il.Emit( OpCodes.Beq, FalseIfLabel );
// Generate the following code:
// if ( CurrentHelper.m_FooDelegate.Equals( d ) )
il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
il.Emit( OpCodes.Ldfld, DelegateField );
il.Emit( OpCodes.Ldarg, (short)1 );
il.Emit( OpCodes.Castclass, typeof(Object) );
il.Emit( OpCodes.Callvirt, DelegateEqualsMethod );
il.Emit( OpCodes.Ldc_I4, 0xff );
il.Emit( OpCodes.And );
il.Emit( OpCodes.Ldc_I4, 0 );
il.Emit( OpCodes.Beq, FalseIfLabel );
// Generate the following code:
// m_aIFooEventsHelpers.RemoveAt( cEventHelpers );
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
il.Emit( OpCodes.Callvirt, ArrayListRemoveMethod );
// Generate the following code:
// m_IFooEventsCP.Unadvise( CurrentHelper.m_dwCookie );
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbEventCP );
il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
il.Emit( OpCodes.Ldfld, CookieField );
il.Emit( OpCodes.Callvirt, CPUnadviseMethod );
// Generate the following code:
// if ( NumEventHelpers > 1) break;
il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
il.Emit( OpCodes.Ldc_I4, 1 );
il.Emit( OpCodes.Bgt, ForEndLabel );
// Generate the following code:
// Marshal.ReleaseComObject(m_IFooEventsCP);
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbEventCP );
il.Emit( OpCodes.Call, ReleaseComObjectMethod );
il.Emit( OpCodes.Pop );
// Generate the following code:
// m_IFooEventsCP = null;
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldnull );
il.Emit( OpCodes.Stfld, fbEventCP );
// Generate the following code:
// m_aIFooEventsHelpers = null;
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldnull );
il.Emit( OpCodes.Stfld, fbSinkHelperArray );
// Generate the following code:
// break;
il.Emit( OpCodes.Br, ForEndLabel );
// Mark this as the label to jump to when the if statement is false.
il.MarkLabel( FalseIfLabel );
// Generate the following code:
// cEventHelpers++;
il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
il.Emit( OpCodes.Ldc_I4, 1 );
il.Emit( OpCodes.Add );
il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
// Generate the following code:
// if ( cEventHelpers < NumEventHelpers ) goto ForBeginLabel;
il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
il.Emit( OpCodes.Blt, ForBeginLabel );
// Mark this as the end of the for loop's body.
il.MarkLabel( ForEndLabel );
// Generate the following code:
// } finally {
il.BeginFinallyBlock();
// Generate the following code:
// if (lockTaken)
// Monitor.Exit(this);
Label skipExit = il.DefineLabel();
il.Emit(OpCodes.Ldloc, ltLockTaken);
il.Emit(OpCodes.Brfalse_S, skipExit);
il.Emit(OpCodes.Ldarg, (short)0);
il.Emit(OpCodes.Call, MonitorExitMethod);
il.MarkLabel(skipExit);
// Generate the following code:
// }
il.EndExceptionBlock();
// Generate the return opcode.
il.Emit( OpCodes.Ret );
return Meth;
}
private MethodBuilder DefineInitSrcItfMethod( TypeBuilder OutputTypeBuilder, Type SourceInterface, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP, FieldBuilder fbCPC )
{
// Retrieve the constructor info for the array list's default constructor.
ConstructorInfo DefaultArrayListCons = typeof(ArrayList).GetConstructor(EventProviderWriter.DefaultLookup, null, new Type[0], null );
Contract.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList");
// Temp byte array for Guid
ubyte[] rgByteGuid = new ubyte[16];
// Retrieve the constructor info for the Guid constructor.
Type[] aParamTypes = new Type[1];
aParamTypes[0] = typeof(Byte[]);
ConstructorInfo ByteArrayGUIDCons = typeof(Guid).GetConstructor(EventProviderWriter.DefaultLookup, null, aParamTypes, null );
Contract.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument");
// Retrieve the IConnectionPointContainer.FindConnectionPoint() method.
MethodInfo CPCFindCPMethod = typeof(IConnectionPointContainer).GetMethod( "FindConnectionPoint" );
Contract.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()");
// Define the Init method itself.
MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
"Init",
MethodAttributes.Private,
null,
null );
ILGenerator il = Meth.GetILGenerator();
// Declare the local variables.
LocalBuilder ltCP = il.DeclareLocal( typeof(IConnectionPoint) );
LocalBuilder ltEvGuid = il.DeclareLocal( typeof(Guid) );
LocalBuilder ltByteArrayGuid = il.DeclareLocal( typeof(Byte[]) );
// Generate the following code:
// IConnectionPoint CP = NULL;
il.Emit( OpCodes.Ldnull );
il.Emit( OpCodes.Stloc, ltCP );
// Get unsigned byte array for the GUID of the event interface.
rgByteGuid = SourceInterface.GUID.ToByteArray();
// Generate the following code:
// ubyte rgByteArray[] = new ubyte [16];
il.Emit( OpCodes.Ldc_I4, 0x10 );
il.Emit( OpCodes.Newarr, typeof(Byte) );
il.Emit( OpCodes.Stloc, ltByteArrayGuid );
// Generate the following code:
// rgByteArray[i] = rgByteGuid[i];
for (int i = 0; i < 16; i++ )
{
il.Emit( OpCodes.Ldloc, ltByteArrayGuid );
il.Emit( OpCodes.Ldc_I4, i );
il.Emit( OpCodes.Ldc_I4, (int) (rgByteGuid[i]) );
il.Emit( OpCodes.Stelem_I1);
}
// Generate the following code:
// EventItfGuid = Guid( ubyte b[] );
il.Emit( OpCodes.Ldloca, ltEvGuid );
il.Emit( OpCodes.Ldloc, ltByteArrayGuid );
il.Emit( OpCodes.Call, ByteArrayGUIDCons );
// Generate the following code:
// m_ConnectionPointContainer.FindConnectionPoint( EventItfGuid, CP );
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbCPC );
il.Emit( OpCodes.Ldloca, ltEvGuid );
il.Emit( OpCodes.Ldloca, ltCP );
il.Emit( OpCodes.Callvirt, CPCFindCPMethod );
// Generate the following code:
// m_ConnectionPoint = (IConnectionPoint)CP;
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldloc, ltCP );
il.Emit( OpCodes.Castclass, typeof(IConnectionPoint) );
il.Emit( OpCodes.Stfld, fbEventCP );
// Generate the following code:
// m_aEventSinkHelpers = new ArrayList;
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Newobj, DefaultArrayListCons );
il.Emit( OpCodes.Stfld, fbSinkHelperArray );
// Generate the return opcode.
il.Emit( OpCodes.Ret );
return Meth;
}
private void DefineConstructor( TypeBuilder OutputTypeBuilder, FieldBuilder fbCPC )
{
// Retrieve the constructor info for the base class's constructor.
ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[0], null );
Contract.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor");
// Define the default constructor.
MethodAttributes ctorAttributes = MethodAttributes.SpecialName | (DefaultBaseClsCons.Attributes & MethodAttributes.MemberAccessMask);
MethodBuilder Cons = OutputTypeBuilder.DefineMethod(
".ctor",
ctorAttributes,
null,
new Type[]{typeof(Object)} );
ILGenerator il = Cons.GetILGenerator();
// Generate the call to the base class constructor.
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Call, DefaultBaseClsCons );
// Generate the following code:
// m_ConnectionPointContainer = (IConnectionPointContainer)EventSource;
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldarg, (short)1 );
il.Emit( OpCodes.Castclass, typeof(IConnectionPointContainer) );
il.Emit( OpCodes.Stfld, fbCPC );
// Generate the return opcode.
il.Emit( OpCodes.Ret );
}
private MethodBuilder DefineFinalizeMethod( TypeBuilder OutputTypeBuilder, Type SinkHelperClass, FieldBuilder fbSinkHelper, FieldBuilder fbEventCP )
{
// Find the cookie on the event sink helper.
FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
// Retrieve the ArrayList.Item property get method.
PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
// Retrieve the ArrayList.Count property get method.
PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
// Retrieve the ConnectionPoint.Unadvise() method.
MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
// Retrieve the Marshal.ReleaseComObject() method.
MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
// Retrieve the Monitor.Enter() method.
MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
// Retrieve the Monitor.Exit() method.
Type[] aParamTypes = new Type[1];
aParamTypes[0] = typeof(Object);
MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
// Define the Finalize method itself.
MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Finalize", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
ILGenerator il = Meth.GetILGenerator();
// Declare the local variables.
LocalBuilder ltNumSinkHelpers = il.DeclareLocal( typeof(Int32) );
LocalBuilder ltSinkHelperCounter = il.DeclareLocal( typeof(Int32) );
LocalBuilder ltCurrSinkHelper = il.DeclareLocal( SinkHelperClass );
LocalBuilder ltLockTaken = il.DeclareLocal(typeof(bool));
// Generate the following code:
// try {
il.BeginExceptionBlock();
// Generate the following code:
// Monitor.Enter(this, ref lockTaken);
il.Emit(OpCodes.Ldarg, (short)0);
il.Emit(OpCodes.Ldloca_S, ltLockTaken);
il.Emit(OpCodes.Call, MonitorEnterMethod);
// Generate the labels.
Label ForBeginLabel = il.DefineLabel();
Label ReleaseComObjectLabel = il.DefineLabel();
Label AfterReleaseComObjectLabel = il.DefineLabel();
// Generate the following code:
// if ( m_IFooEventsCP == null ) goto AfterReleaseComObjectLabel;
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbEventCP );
il.Emit( OpCodes.Brfalse, AfterReleaseComObjectLabel );
// Generate the following code:
// int NumEventHelpers = m_aIFooEventsHelpers.Count;
// int cEventHelpers = 0;
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbSinkHelper );
il.Emit( OpCodes.Callvirt, ArrayListSizeGetMethod );
il.Emit( OpCodes.Stloc, ltNumSinkHelpers );
il.Emit( OpCodes.Ldc_I4, 0 );
il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
// Generate the following code:
// if ( 0 >= NumEventHelpers ) goto ReleaseComObjectLabel;
il.Emit( OpCodes.Ldc_I4, 0 );
il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
il.Emit( OpCodes.Bge, ReleaseComObjectLabel );
// Mark this as the beginning of the for loop's body.
il.MarkLabel( ForBeginLabel );
// Generate the following code:
// CurrentHelper = (IFooEvents_SinkHelper)m_aIFooEventsHelpers.Get( cEventHelpers );
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbSinkHelper );
il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
il.Emit( OpCodes.Callvirt, ArrayListItemGetMethod );
il.Emit( OpCodes.Castclass, SinkHelperClass );
il.Emit( OpCodes.Stloc, ltCurrSinkHelper );
// Generate the following code:
// m_IFooEventsCP.Unadvise( CurrentHelper.m_dwCookie );
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbEventCP );
il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
il.Emit( OpCodes.Ldfld, CookieField );
il.Emit( OpCodes.Callvirt, CPUnadviseMethod );
// Generate the following code:
// cEventHelpers++;
il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
il.Emit( OpCodes.Ldc_I4, 1 );
il.Emit( OpCodes.Add );
il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
// Generate the following code:
// if ( cEventHelpers < NumEventHelpers ) goto ForBeginLabel;
il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
il.Emit( OpCodes.Blt, ForBeginLabel );
// Mark this as the end of the for loop's body.
il.MarkLabel( ReleaseComObjectLabel );
// Generate the following code:
// Marshal.ReleaseComObject(m_IFooEventsCP);
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbEventCP );
il.Emit( OpCodes.Call, ReleaseComObjectMethod );
il.Emit( OpCodes.Pop );
// Mark this as the end of the for loop's body.
il.MarkLabel( AfterReleaseComObjectLabel );
// Generate the following code:
// } catch {
il.BeginCatchBlock(typeof(System.Exception));
il.Emit( OpCodes.Pop );
// Generate the following code:
// } finally {
il.BeginFinallyBlock();
// Generate the following code:
// if (lockTaken)
// Monitor.Exit(this);
Label skipExit = il.DefineLabel();
il.Emit(OpCodes.Ldloc, ltLockTaken);
il.Emit(OpCodes.Brfalse_S, skipExit);
il.Emit(OpCodes.Ldarg, (short)0);
il.Emit(OpCodes.Call, MonitorExitMethod);
il.MarkLabel(skipExit);
// Generate the following code:
// }
il.EndExceptionBlock();
// Generate the return opcode.
il.Emit( OpCodes.Ret );
return Meth;
}
private void DefineDisposeMethod( TypeBuilder OutputTypeBuilder, MethodBuilder FinalizeMethod )
{
// Retrieve the method info for GC.SuppressFinalize().
MethodInfo SuppressFinalizeMethod = typeof(GC).GetMethod("SuppressFinalize");
Contract.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize");
// Define the Finalize method itself.
MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Dispose", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
ILGenerator il = Meth.GetILGenerator();
// Generate the following code:
// Finalize()
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Callvirt, FinalizeMethod );
// Generate the following code:
// GC.SuppressFinalize()
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Call, SuppressFinalizeMethod );
// Generate the return opcode.
il.Emit( OpCodes.Ret );
}
private ModuleBuilder m_OutputModule;
private String m_strDestTypeName;
private Type m_EventItfType;
private Type m_SrcItfType;
private Type m_SinkHelperType;
}
}
| |
// ReSharper disable InconsistentNaming
// Disregarding naming convention in polyfill code
#if NET35
#pragma warning disable 0420
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ConcurrentQueue.cs
//
// <OWNER>Microsoft</OWNER>
//
// A lock-free, concurrent queue primitive, and its associated debugger view type.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Threading;
namespace System.Collections.Concurrent
{
/// <summary>
/// Represents a thread-safe first-in, first-out collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the queue.</typeparam>
/// <remarks>
/// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
[ComVisible(false)]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))]
[HostProtection(Synchronization = true, ExternalThreading = true)]
[Serializable]
internal class ConcurrentQueue<T> : IProducerConsumerCollection<T>//, IReadOnlyCollection<T>
{
//fields of ConcurrentQueue
[NonSerialized]
private volatile Segment m_head;
[NonSerialized]
private volatile Segment m_tail;
private T[] m_serializationArray; // Used for custom serialization.
private const int SEGMENT_SIZE = 32;
//number of snapshot takers, GetEnumerator(), ToList() and ToArray() operations take snapshot.
[NonSerialized]
internal volatile int m_numSnapshotTakers = 0;
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class.
/// </summary>
public ConcurrentQueue()
{
m_head = m_tail = new Segment(0, this);
}
/// <summary>
/// Initializes the contents of the queue from an existing collection.
/// </summary>
/// <param name="collection">A collection from which to copy elements.</param>
private void InitializeFromCollection(IEnumerable<T> collection)
{
Segment localTail = new Segment(0, this);//use this local variable to avoid the extra volatile read/write. this is safe because it is only called from ctor
m_head = localTail;
int index = 0;
foreach (T element in collection)
{
// Contract.Assert(index >= 0 && index < SEGMENT_SIZE);
localTail.UnsafeAdd(element);
index++;
if (index >= SEGMENT_SIZE)
{
localTail = localTail.UnsafeGrow();
index = 0;
}
}
m_tail = localTail;
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/>
/// class that contains elements copied from the specified collection
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new <see
/// cref="ConcurrentQueue{T}"/>.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is
/// null.</exception>
public ConcurrentQueue(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
InitializeFromCollection(collection);
}
/// <summary>
/// Get the data array to be serialized
/// </summary>
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
// save the data into the serialization array to be saved
m_serializationArray = ToArray();
}
/// <summary>
/// Construct the queue from a previously seiralized one
/// </summary>
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
// Contract.Assert(m_serializationArray != null);
InitializeFromCollection(m_serializationArray);
m_serializationArray = null;
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see
/// cref="T:System.Array"/>, starting at a particular
/// <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="T:System.Collections.Concurrent.ConcurrentBag"/>. The <see
/// cref="T:System.Array">Array</see> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="array"/> is multidimensional. -or-
/// <paramref name="array"/> does not have zero-based indexing. -or-
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is
/// greater than the available space from <paramref name="index"/> to the end of the destination
/// <paramref name="array"/>. -or- The type of the source <see
/// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the
/// destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
// Validate arguments.
if (array == null)
{
throw new ArgumentNullException("array");
}
// We must be careful not to corrupt the array, so we will first accumulate an
// internal list of elements that we will then copy to the array. This requires
// some extra allocation, but is necessary since we don't know up front whether
// the array is sufficiently large to hold the stack's contents.
((ICollection)ToList()).CopyTo(array, index);
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
/// synchronized with the SyncRoot.
/// </summary>
/// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always
/// returns false.</value>
bool ICollection.IsSynchronized
{
// Gets a value indicating whether access to this collection is synchronized. Always returns
// false. The reason is subtle. While access is in face thread safe, it's not the case that
// locking on the SyncRoot would have prevented concurrent pushes and pops, as this property
// would typically indicate; that's because we internally use CAS operations vs. true locks.
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see
/// cref="T:System.Collections.ICollection"/>. This property is not supported.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception>
object ICollection.SyncRoot
{
get
{
throw new NotSupportedException("ConcurrentCollection SyncRoot Not Supported");
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
/// <summary>
/// Attempts to add an object to the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
/// reference (Nothing in Visual Basic) for reference types.
/// </param>
/// <returns>true if the object was added successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the
/// end of the <see cref="ConcurrentQueue{T}"/>
/// and return true.</remarks>
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
Enqueue(item);
return true;
}
/// <summary>
/// Attempts to remove and return an object from the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">
/// When this method returns, if the operation was successful, <paramref name="item"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object
/// from the beginning of the <see cref="ConcurrentQueue{T}"/>.
/// </remarks>
bool IProducerConsumerCollection<T>.TryTake(out T item)
{
return TryDequeue(out item);
}
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of this property is recommended
/// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
/// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
/// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
/// the result.
/// </remarks>
public bool IsEmpty
{
get
{
Segment head = m_head;
if (!head.IsEmpty)
//fast route 1:
//if current head is not empty, then queue is not empty
return false;
else if (head.Next == null)
//fast route 2:
//if current head is empty and it's the last segment
//then queue is empty
return true;
else
//slow route:
//current head is empty and it is NOT the last segment,
//it means another thread is growing new segment
{
SpinWait spin = new SpinWait();
while (head.IsEmpty)
{
if (head.Next == null)
return true;
spin.SpinOnce();
head = m_head;
}
return false;
}
}
}
/// <summary>
/// Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array.
/// </summary>
/// <returns>A new array containing a snapshot of elements copied from the <see
/// cref="ConcurrentQueue{T}"/>.</returns>
public T[] ToArray()
{
return ToList().ToArray();
}
/// <summary>
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to a new <see
/// cref="T:System.Collections.Generic.List{T}"/>.
/// </summary>
/// <returns>A new <see cref="T:System.Collections.Generic.List{T}"/> containing a snapshot of
/// elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns>
private List<T> ToList()
{
// Increments the number of active snapshot takers. This increment must happen before the snapshot is
// taken. At the same time, Decrement must happen after list copying is over. Only in this way, can it
// eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0.
Interlocked.Increment(ref m_numSnapshotTakers);
List<T> list = new List<T>();
try
{
//store head and tail positions in buffer,
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
if (head == tail)
{
head.AddToList(list, headLow, tailHigh);
}
else
{
head.AddToList(list, headLow, SEGMENT_SIZE - 1);
Segment curr = head.Next;
while (curr != tail)
{
curr.AddToList(list, 0, SEGMENT_SIZE - 1);
curr = curr.Next;
}
//Add tail segment
tail.AddToList(list, 0, tailHigh);
}
}
finally
{
// This Decrement must happen after copying is over.
Interlocked.Decrement(ref m_numSnapshotTakers);
}
return list;
}
/// <summary>
/// Store the position of the current head and tail positions.
/// </summary>
/// <param name="head">return the head segment</param>
/// <param name="tail">return the tail segment</param>
/// <param name="headLow">return the head offset, value range [0, SEGMENT_SIZE]</param>
/// <param name="tailHigh">return the tail offset, value range [-1, SEGMENT_SIZE-1]</param>
private void GetHeadTailPositions(out Segment head, out Segment tail,
out int headLow, out int tailHigh)
{
head = m_head;
tail = m_tail;
headLow = head.Low;
tailHigh = tail.High;
SpinWait spin = new SpinWait();
//we loop until the observed values are stable and sensible.
//This ensures that any update order by other methods can be tolerated.
while (
//if head and tail changed, retry
head != m_head || tail != m_tail
//if low and high pointers, retry
|| headLow != head.Low || tailHigh != tail.High
//if head jumps ahead of tail because of concurrent grow and dequeue, retry
|| head.m_index > tail.m_index)
{
spin.SpinOnce();
head = m_head;
tail = m_tail;
headLow = head.Low;
tailHigh = tail.High;
}
}
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
/// property is recommended rather than retrieving the number of items from the <see cref="Count"/>
/// property and comparing it to 0.
/// </remarks>
public int Count
{
get
{
//store head and tail positions in buffer,
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
if (head == tail)
{
return tailHigh - headLow + 1;
}
//head segment
int count = SEGMENT_SIZE - headLow;
//middle segment(s), if any, are full.
//We don't deal with overflow to be consistent with the behavior of generic types in CLR.
count += SEGMENT_SIZE * ((int)(tail.m_index - head.m_index - 1));
//tail segment
count += tailHigh + 1;
return count;
}
}
/// <summary>
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see
/// cref="T:System.Array">Array</see>, starting at the specified array index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="ConcurrentQueue{T}"/>. The <see cref="T:System.Array">Array</see> must have zero-based
/// indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
/// length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="ConcurrentQueue{T}"/> is greater than the
/// available space from <paramref name="index"/> to the end of the destination <paramref
/// name="array"/>.
/// </exception>
public void CopyTo(T[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
// We must be careful not to corrupt the array, so we will first accumulate an
// internal list of elements that we will then copy to the array. This requires
// some extra allocation, but is necessary since we don't know up front whether
// the array is sufficiently large to hold the stack's contents.
ToList().CopyTo(array, index);
}
/// <summary>
/// Returns an enumerator that iterates through the <see
/// cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentQueue{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the queue. It does not reflect any updates to the collection after
/// GetEnumerator was called. The enumerator is safe to use
/// concurrently with reads from and writes to the queue.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
// Increments the number of active snapshot takers. This increment must happen before the snapshot is
// taken. At the same time, Decrement must happen after the enumeration is over. Only in this way, can it
// eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0.
Interlocked.Increment(ref m_numSnapshotTakers);
// Takes a snapshot of the queue.
// A design flaw here: if a Thread.Abort() happens, we cannot decrement m_numSnapshotTakers. But we cannot
// wrap the following with a try/finally block, otherwise the decrement will happen before the yield return
// statements in the GetEnumerator (head, tail, headLow, tailHigh) method.
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
//If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of
// the queue is not taken when GetEnumerator is initialized but when MoveNext() is first called.
// This is inconsistent with existing generic collections. In order to prevent it, we capture the
// value of m_head in a buffer and call out to a helper method.
//The old way of doing this was to return the ToList().GetEnumerator(), but ToList() was an
// unnecessary perfomance hit.
return GetEnumerator(head, tail, headLow, tailHigh);
}
/// <summary>
/// Helper method of GetEnumerator to seperate out yield return statement, and prevent lazy evaluation.
/// </summary>
private IEnumerator<T> GetEnumerator(Segment head, Segment tail, int headLow, int tailHigh)
{
try
{
SpinWait spin = new SpinWait();
if (head == tail)
{
for (int i = headLow; i <= tailHigh; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!head.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return head.m_array[i];
}
}
else
{
//iterate on head segment
for (int i = headLow; i < SEGMENT_SIZE; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!head.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return head.m_array[i];
}
//iterate on middle segments
Segment curr = head.Next;
while (curr != tail)
{
for (int i = 0; i < SEGMENT_SIZE; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!curr.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return curr.m_array[i];
}
curr = curr.Next;
}
//iterate on tail segment
for (int i = 0; i <= tailHigh; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!tail.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return tail.m_array[i];
}
}
}
finally
{
// This Decrement must happen after the enumeration is over.
Interlocked.Decrement(ref m_numSnapshotTakers);
}
}
/// <summary>
/// Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <param name="item">The object to add to the end of the <see
/// cref="ConcurrentQueue{T}"/>. The value can be a null reference
/// (Nothing in Visual Basic) for reference types.
/// </param>
public void Enqueue(T item)
{
SpinWait spin = new SpinWait();
while (true)
{
Segment tail = m_tail;
if (tail.TryAppend(item))
return;
spin.SpinOnce();
}
}
/// <summary>
/// Attempts to remove and return the object at the beginning of the <see
/// cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <param name="result">
/// When this method returns, if the operation was successful, <paramref name="result"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned from the beggining of the <see
/// cref="ConcurrentQueue{T}"/>
/// succesfully; otherwise, false.</returns>
public bool TryDequeue(out T result)
{
while (!IsEmpty)
{
Segment head = m_head;
if (head.TryRemove(out result))
return true;
//since method IsEmpty spins, we don't need to spin in the while loop
}
result = default(T);
return false;
}
/// <summary>
/// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/>
/// without removing it.
/// </summary>
/// <param name="result">When this method returns, <paramref name="result"/> contains an object from
/// the beginning of the <see cref="T:System.Collections.Concurrent.ConccurrentQueue{T}"/> or an
/// unspecified value if the operation failed.</param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
public bool TryPeek(out T result)
{
Interlocked.Increment(ref m_numSnapshotTakers);
while (!IsEmpty)
{
Segment head = m_head;
if (head.TryPeek(out result))
{
Interlocked.Decrement(ref m_numSnapshotTakers);
return true;
}
//since method IsEmpty spins, we don't need to spin in the while loop
}
result = default(T);
Interlocked.Decrement(ref m_numSnapshotTakers);
return false;
}
/// <summary>
/// private class for ConcurrentQueue.
/// a queue is a linked list of small arrays, each node is called a segment.
/// A segment contains an array, a pointer to the next segment, and m_low, m_high indices recording
/// the first and last valid elements of the array.
/// </summary>
private class Segment
{
//we define two volatile arrays: m_array and m_state. Note that the accesses to the array items
//do not get volatile treatment. But we don't need to worry about loading adjacent elements or
//store/load on adjacent elements would suffer reordering.
// - Two stores: these are at risk, but CLRv2 memory model guarantees store-release hence we are safe.
// - Two loads: because one item from two volatile arrays are accessed, the loads of the array references
// are sufficient to prevent reordering of the loads of the elements.
internal volatile T[] m_array;
// For each entry in m_array, the corresponding entry in m_state indicates whether this position contains
// a valid value. m_state is initially all false.
internal volatile VolatileBool[] m_state;
//pointer to the next segment. null if the current segment is the last segment
private volatile Segment m_next;
//We use this zero based index to track how many segments have been created for the queue, and
//to compute how many active segments are there currently.
// * The number of currently active segments is : m_tail.m_index - m_head.m_index + 1;
// * m_index is incremented with every Segment.Grow operation. We use Int64 type, and we can safely
// assume that it never overflows. To overflow, we need to do 2^63 increments, even at a rate of 4
// billion (2^32) increments per second, it takes 2^31 seconds, which is about 64 years.
internal readonly long m_index;
//indices of where the first and last valid values
// - m_low points to the position of the next element to pop from this segment, range [0, infinity)
// m_low >= SEGMENT_SIZE implies the segment is disposable
// - m_high points to the position of the latest pushed element, range [-1, infinity)
// m_high == -1 implies the segment is new and empty
// m_high >= SEGMENT_SIZE-1 means this segment is ready to grow.
// and the thread who sets m_high to SEGMENT_SIZE-1 is responsible to grow the segment
// - Math.Min(m_low, SEGMENT_SIZE) > Math.Min(m_high, SEGMENT_SIZE-1) implies segment is empty
// - initially m_low =0 and m_high=-1;
private volatile int m_low;
private volatile int m_high;
private volatile ConcurrentQueue<T> m_source;
/// <summary>
/// Create and initialize a segment with the specified index.
/// </summary>
internal Segment(long index, ConcurrentQueue<T> source)
{
m_array = new T[SEGMENT_SIZE];
m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false
m_high = -1;
// Contract.Assert(index >= 0);
m_index = index;
m_source = source;
}
/// <summary>
/// return the next segment
/// </summary>
internal Segment Next
{
get { return m_next; }
}
/// <summary>
/// return true if the current segment is empty (doesn't have any element available to dequeue,
/// false otherwise
/// </summary>
internal bool IsEmpty
{
get { return (Low > High); }
}
/// <summary>
/// Add an element to the tail of the current segment
/// exclusively called by ConcurrentQueue.InitializedFromCollection
/// InitializeFromCollection is responsible to guaratee that there is no index overflow,
/// and there is no contention
/// </summary>
/// <param name="value"></param>
internal void UnsafeAdd(T value)
{
// Contract.Assert(m_high < SEGMENT_SIZE - 1);
m_high++;
m_array[m_high] = value;
m_state[m_high].m_value = true;
}
/// <summary>
/// Create a new segment and append to the current one
/// Does not update the m_tail pointer
/// exclusively called by ConcurrentQueue.InitializedFromCollection
/// InitializeFromCollection is responsible to guaratee that there is no index overflow,
/// and there is no contention
/// </summary>
/// <returns>the reference to the new Segment</returns>
internal Segment UnsafeGrow()
{
// Contract.Assert(m_high >= SEGMENT_SIZE - 1);
Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
m_next = newSegment;
return newSegment;
}
/// <summary>
/// Create a new segment and append to the current one
/// Update the m_tail pointer
/// This method is called when there is no contention
/// </summary>
internal void Grow()
{
//no CAS is needed, since there is no contention (other threads are blocked, busy waiting)
Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
m_next = newSegment;
// Contract.Assert(m_source.m_tail == this);
m_source.m_tail = m_next;
}
/// <summary>
/// Try to append an element at the end of this segment.
/// </summary>
/// <param name="value">the element to append</param>
/// <returns>true if the element is appended, false if the current segment is full</returns>
/// <remarks>if appending the specified element succeeds, and after which the segment is full,
/// then grow the segment</remarks>
internal bool TryAppend(T value)
{
//quickly check if m_high is already over the boundary, if so, bail out
if (m_high >= SEGMENT_SIZE - 1)
{
return false;
}
//Now we will use a CAS to increment m_high, and store the result in newhigh.
//Depending on how many free spots left in this segment and how many threads are doing this Increment
//at this time, the returning "newhigh" can be
// 1) < SEGMENT_SIZE - 1 : we took a spot in this segment, and not the last one, just insert the value
// 2) == SEGMENT_SIZE - 1 : we took the last spot, insert the value AND grow the segment
// 3) > SEGMENT_SIZE - 1 : we failed to reserve a spot in this segment, we return false to
// Queue.Enqueue method, telling it to try again in the next segment.
int newhigh = SEGMENT_SIZE; //initial value set to be over the boundary
//We need do Interlocked.Increment and value/state update in a finally block to ensure that they run
//without interuption. This is to prevent anything from happening between them, and another dequeue
//thread maybe spinning forever to wait for m_state[] to be true;
try
{ }
finally
{
newhigh = Interlocked.Increment(ref m_high);
if (newhigh <= SEGMENT_SIZE - 1)
{
m_array[newhigh] = value;
m_state[newhigh].m_value = true;
}
//if this thread takes up the last slot in the segment, then this thread is responsible
//to grow a new segment. Calling Grow must be in the finally block too for reliability reason:
//if thread abort during Grow, other threads will be left busy spinning forever.
if (newhigh == SEGMENT_SIZE - 1)
{
Grow();
}
}
//if newhigh <= SEGMENT_SIZE-1, it means the current thread successfully takes up a spot
return newhigh <= SEGMENT_SIZE - 1;
}
/// <summary>
/// try to remove an element from the head of current segment
/// </summary>
/// <param name="result">The result.</param>
/// <returns>return false only if the current segment is empty</returns>
internal bool TryRemove(out T result)
{
SpinWait spin = new SpinWait();
int lowLocal = Low, highLocal = High;
while (lowLocal <= highLocal)
{
//try to update m_low
if (Interlocked.CompareExchange(ref m_low, lowLocal + 1, lowLocal) == lowLocal)
{
//if the specified value is not available (this spot is taken by a push operation,
// but the value is not written into yet), then spin
SpinWait spinLocal = new SpinWait();
while (!m_state[lowLocal].m_value)
{
spinLocal.SpinOnce();
}
result = m_array[lowLocal];
// If there is no other thread taking snapshot (GetEnumerator(), ToList(), etc), reset the deleted entry to null.
// It is ok if after this conditional check m_numSnapshotTakers becomes > 0, because new snapshots won't include
// the deleted entry at m_array[lowLocal].
if (m_source.m_numSnapshotTakers <= 0)
{
m_array[lowLocal] = default(T); //release the reference to the object.
}
//if the current thread sets m_low to SEGMENT_SIZE, which means the current segment becomes
//disposable, then this thread is responsible to dispose this segment, and reset m_head
if (lowLocal + 1 >= SEGMENT_SIZE)
{
// Invariant: we only dispose the current m_head, not any other segment
// In usual situation, disposing a segment is simply seting m_head to m_head.m_next
// But there is one special case, where m_head and m_tail points to the same and ONLY
//segment of the queue: Another thread A is doing Enqueue and finds that it needs to grow,
//while the *current* thread is doing *this* Dequeue operation, and finds that it needs to
//dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its
//Grow operation, this is the reason of having the following while loop
spinLocal = new SpinWait();
while (m_next == null)
{
spinLocal.SpinOnce();
}
// Contract.Assert(m_source.m_head == this);
m_source.m_head = m_next;
}
return true;
}
else
{
//CAS failed due to contention: spin briefly and retry
spin.SpinOnce();
lowLocal = Low; highLocal = High;
}
}//end of while
result = default(T);
return false;
}
/// <summary>
/// try to peek the current segment
/// </summary>
/// <param name="result">holds the return value of the element at the head position,
/// value set to default(T) if there is no such an element</param>
/// <returns>true if there are elements in the current segment, false otherwise</returns>
internal bool TryPeek(out T result)
{
result = default(T);
int lowLocal = Low;
if (lowLocal > High)
return false;
SpinWait spin = new SpinWait();
while (!m_state[lowLocal].m_value)
{
spin.SpinOnce();
}
result = m_array[lowLocal];
return true;
}
/// <summary>
/// Adds part or all of the current segment into a List.
/// </summary>
/// <param name="list">the list to which to add</param>
/// <param name="start">the start position</param>
/// <param name="end">the end position</param>
internal void AddToList(List<T> list, int start, int end)
{
for (int i = start; i <= end; i++)
{
SpinWait spin = new SpinWait();
while (!m_state[i].m_value)
{
spin.SpinOnce();
}
list.Add(m_array[i]);
}
}
/// <summary>
/// return the position of the head of the current segment
/// Value range [0, SEGMENT_SIZE], if it's SEGMENT_SIZE, it means this segment is exhausted and thus empty
/// </summary>
internal int Low
{
get
{
return Math.Min(m_low, SEGMENT_SIZE);
}
}
/// <summary>
/// return the logical position of the tail of the current segment
/// Value range [-1, SEGMENT_SIZE-1]. When it's -1, it means this is a new segment and has no elemnet yet
/// </summary>
internal int High
{
get
{
//if m_high > SEGMENT_SIZE, it means it's out of range, we should return
//SEGMENT_SIZE-1 as the logical position
return Math.Min(m_high, SEGMENT_SIZE - 1);
}
}
}
}//end of class Segment
/// <summary>
/// A wrapper struct for volatile bool, please note the copy of the struct it self will not be volatile
/// for example this statement will not include in volatilness operation volatileBool1 = volatileBool2 the jit will copy the struct and will ignore the volatile
/// </summary>
struct VolatileBool
{
public VolatileBool(bool value)
{
m_value = value;
}
public volatile bool m_value;
}
}
#endif
| |
//---------------------------------------------------------------------------
//
// <copyright file="DrawingCollection.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media
{
/// <summary>
/// A collection of Drawing objects.
/// </summary>
public sealed partial class DrawingCollection : Animatable, IList, IList<Drawing>
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new DrawingCollection Clone()
{
return (DrawingCollection)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new DrawingCollection CloneCurrentValue()
{
return (DrawingCollection)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region IList<T>
/// <summary>
/// Adds "value" to the list
/// </summary>
public void Add(Drawing value)
{
AddHelper(value);
}
/// <summary>
/// Removes all elements from the list
/// </summary>
public void Clear()
{
WritePreamble();
// As part of Clear()'ing the collection, we will iterate it and call
// OnFreezablePropertyChanged and OnRemove for each item.
// However, OnRemove assumes that the item to be removed has already been
// pulled from the underlying collection. To statisfy this condition,
// we store the old collection and clear _collection before we call these methods.
// As Clear() semantics do not include TrimToFit behavior, we create the new
// collection storage at the same size as the previous. This is to provide
// as close as possible the same perf characteristics as less complicated collections.
FrugalStructList<Drawing> oldCollection = _collection;
_collection = new FrugalStructList<Drawing>(_collection.Capacity);
for (int i = oldCollection.Count - 1; i >= 0; i--)
{
OnFreezablePropertyChanged(/* oldValue = */ oldCollection[i], /* newValue = */ null);
// Fire the OnRemove handlers for each item. We're not ensuring that
// all OnRemove's get called if a resumable exception is thrown.
// At this time, these call-outs are not public, so we do not handle exceptions.
OnRemove( /* oldValue */ oldCollection[i]);
}
++_version;
WritePostscript();
}
/// <summary>
/// Determines if the list contains "value"
/// </summary>
public bool Contains(Drawing value)
{
ReadPreamble();
return _collection.Contains(value);
}
/// <summary>
/// Returns the index of "value" in the list
/// </summary>
public int IndexOf(Drawing value)
{
ReadPreamble();
return _collection.IndexOf(value);
}
/// <summary>
/// Inserts "value" into the list at the specified position
/// </summary>
public void Insert(int index, Drawing value)
{
if (value == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
WritePreamble();
OnFreezablePropertyChanged(/* oldValue = */ null, /* newValue = */ value);
_collection.Insert(index, value);
OnInsert(value);
++_version;
WritePostscript();
}
/// <summary>
/// Removes "value" from the list
/// </summary>
public bool Remove(Drawing value)
{
WritePreamble();
// By design collections "succeed silently" if you attempt to remove an item
// not in the collection. Therefore we need to first verify the old value exists
// before calling OnFreezablePropertyChanged. Since we already need to locate
// the item in the collection we keep the index and use RemoveAt(...) to do
// the work. (Windows OS #1016178)
// We use the public IndexOf to guard our UIContext since OnFreezablePropertyChanged
// is only called conditionally. IList.IndexOf returns -1 if the value is not found.
int index = IndexOf(value);
if (index >= 0)
{
Drawing oldValue = _collection[index];
OnFreezablePropertyChanged(oldValue, null);
_collection.RemoveAt(index);
OnRemove(oldValue);
++_version;
WritePostscript();
return true;
}
// Collection_Remove returns true, calls WritePostscript,
// increments version, and does UpdateResource if it succeeds
return false;
}
/// <summary>
/// Removes the element at the specified index
/// </summary>
public void RemoveAt(int index)
{
RemoveAtWithoutFiringPublicEvents(index);
// RemoveAtWithoutFiringPublicEvents incremented the version
WritePostscript();
}
/// <summary>
/// Removes the element at the specified index without firing
/// the public Changed event.
/// The caller - typically a public method - is responsible for calling
/// WritePostscript if appropriate.
/// </summary>
internal void RemoveAtWithoutFiringPublicEvents(int index)
{
WritePreamble();
Drawing oldValue = _collection[ index ];
OnFreezablePropertyChanged(oldValue, null);
_collection.RemoveAt(index);
OnRemove(oldValue);
++_version;
// No WritePostScript to avoid firing the Changed event.
}
/// <summary>
/// Indexer for the collection
/// </summary>
public Drawing this[int index]
{
get
{
ReadPreamble();
return _collection[index];
}
set
{
if (value == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
WritePreamble();
if (!Object.ReferenceEquals(_collection[ index ], value))
{
Drawing oldValue = _collection[ index ];
OnFreezablePropertyChanged(oldValue, value);
_collection[ index ] = value;
OnSet(oldValue, value);
}
++_version;
WritePostscript();
}
}
#endregion
#region ICollection<T>
/// <summary>
/// The number of elements contained in the collection.
/// </summary>
public int Count
{
get
{
ReadPreamble();
return _collection.Count;
}
}
/// <summary>
/// Copies the elements of the collection into "array" starting at "index"
/// </summary>
public void CopyTo(Drawing[] array, int index)
{
ReadPreamble();
if (array == null)
{
throw new ArgumentNullException("array");
}
// This will not throw in the case that we are copying
// from an empty collection. This is consistent with the
// BCL Collection implementations. (Windows 1587365)
if (index < 0 || (index + _collection.Count) > array.Length)
{
throw new ArgumentOutOfRangeException("index");
}
_collection.CopyTo(array, index);
}
bool ICollection<Drawing>.IsReadOnly
{
get
{
ReadPreamble();
return IsFrozen;
}
}
#endregion
#region IEnumerable<T>
/// <summary>
/// Returns an enumerator for the collection
/// </summary>
public Enumerator GetEnumerator()
{
ReadPreamble();
return new Enumerator(this);
}
IEnumerator<Drawing> IEnumerable<Drawing>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IList
bool IList.IsReadOnly
{
get
{
return ((ICollection<Drawing>)this).IsReadOnly;
}
}
bool IList.IsFixedSize
{
get
{
ReadPreamble();
return IsFrozen;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
// Forwards to typed implementation
this[index] = Cast(value);
}
}
int IList.Add(object value)
{
// Forward to typed helper
return AddHelper(Cast(value));
}
bool IList.Contains(object value)
{
return Contains(value as Drawing);
}
int IList.IndexOf(object value)
{
return IndexOf(value as Drawing);
}
void IList.Insert(int index, object value)
{
// Forward to IList<T> Insert
Insert(index, Cast(value));
}
void IList.Remove(object value)
{
Remove(value as Drawing);
}
#endregion
#region ICollection
void ICollection.CopyTo(Array array, int index)
{
ReadPreamble();
if (array == null)
{
throw new ArgumentNullException("array");
}
// This will not throw in the case that we are copying
// from an empty collection. This is consistent with the
// BCL Collection implementations. (Windows 1587365)
if (index < 0 || (index + _collection.Count) > array.Length)
{
throw new ArgumentOutOfRangeException("index");
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Get(SRID.Collection_BadRank));
}
// Elsewhere in the collection we throw an AE when the type is
// bad so we do it here as well to be consistent
try
{
int count = _collection.Count;
for (int i = 0; i < count; i++)
{
array.SetValue(_collection[i], index + i);
}
}
catch (InvalidCastException e)
{
throw new ArgumentException(SR.Get(SRID.Collection_BadDestArray, this.GetType().Name), e);
}
}
bool ICollection.IsSynchronized
{
get
{
ReadPreamble();
return IsFrozen || Dispatcher != null;
}
}
object ICollection.SyncRoot
{
get
{
ReadPreamble();
return this;
}
}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Internal Helpers
/// <summary>
/// A frozen empty DrawingCollection.
/// </summary>
internal static DrawingCollection Empty
{
get
{
if (s_empty == null)
{
DrawingCollection collection = new DrawingCollection();
collection.Freeze();
s_empty = collection;
}
return s_empty;
}
}
/// <summary>
/// Helper to return read only access.
/// </summary>
internal Drawing Internal_GetItem(int i)
{
return _collection[i];
}
/// <summary>
/// Freezable collections need to notify their contained Freezables
/// about the change in the InheritanceContext
/// </summary>
internal override void OnInheritanceContextChangedCore(EventArgs args)
{
base.OnInheritanceContextChangedCore(args);
for (int i=0; i<this.Count; i++)
{
DependencyObject inheritanceChild = _collection[i];
if (inheritanceChild!= null && inheritanceChild.InheritanceContext == this)
{
inheritanceChild.OnInheritanceContextChanged(args);
}
}
}
#endregion
#region Private Helpers
private Drawing Cast(object value)
{
if( value == null )
{
throw new System.ArgumentNullException("value");
}
if (!(value is Drawing))
{
throw new System.ArgumentException(SR.Get(SRID.Collection_BadType, this.GetType().Name, value.GetType().Name, "Drawing"));
}
return (Drawing) value;
}
// IList.Add returns int and IList<T>.Add does not. This
// is called by both Adds and IList<T>'s just ignores the
// integer
private int AddHelper(Drawing value)
{
int index = AddWithoutFiringPublicEvents(value);
// AddAtWithoutFiringPublicEvents incremented the version
WritePostscript();
return index;
}
internal int AddWithoutFiringPublicEvents(Drawing value)
{
int index = -1;
if (value == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
WritePreamble();
Drawing newValue = value;
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
index = _collection.Add(newValue);
OnInsert(newValue);
++_version;
// No WritePostScript to avoid firing the Changed event.
return index;
}
internal event ItemInsertedHandler ItemInserted;
internal event ItemRemovedHandler ItemRemoved;
private void OnInsert(object item)
{
if (ItemInserted != null)
{
ItemInserted(this, item);
}
}
private void OnRemove(object oldValue)
{
if (ItemRemoved != null)
{
ItemRemoved(this, oldValue);
}
}
private void OnSet(object oldValue, object newValue)
{
OnInsert(newValue);
OnRemove(oldValue);
}
#endregion Private Helpers
private static DrawingCollection s_empty;
#region Public Properties
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new DrawingCollection();
}
/// <summary>
/// Implementation of Freezable.CloneCore()
/// </summary>
protected override void CloneCore(Freezable source)
{
DrawingCollection sourceDrawingCollection = (DrawingCollection) source;
base.CloneCore(source);
int count = sourceDrawingCollection._collection.Count;
_collection = new FrugalStructList<Drawing>(count);
for (int i = 0; i < count; i++)
{
Drawing newValue = (Drawing) sourceDrawingCollection._collection[i].Clone();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of Freezable.CloneCurrentValueCore()
/// </summary>
protected override void CloneCurrentValueCore(Freezable source)
{
DrawingCollection sourceDrawingCollection = (DrawingCollection) source;
base.CloneCurrentValueCore(source);
int count = sourceDrawingCollection._collection.Count;
_collection = new FrugalStructList<Drawing>(count);
for (int i = 0; i < count; i++)
{
Drawing newValue = (Drawing) sourceDrawingCollection._collection[i].CloneCurrentValue();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of Freezable.GetAsFrozenCore()
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
DrawingCollection sourceDrawingCollection = (DrawingCollection) source;
base.GetAsFrozenCore(source);
int count = sourceDrawingCollection._collection.Count;
_collection = new FrugalStructList<Drawing>(count);
for (int i = 0; i < count; i++)
{
Drawing newValue = (Drawing) sourceDrawingCollection._collection[i].GetAsFrozen();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of Freezable.GetCurrentValueAsFrozenCore()
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
DrawingCollection sourceDrawingCollection = (DrawingCollection) source;
base.GetCurrentValueAsFrozenCore(source);
int count = sourceDrawingCollection._collection.Count;
_collection = new FrugalStructList<Drawing>(count);
for (int i = 0; i < count; i++)
{
Drawing newValue = (Drawing) sourceDrawingCollection._collection[i].GetCurrentValueAsFrozen();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
int count = _collection.Count;
for (int i = 0; i < count && canFreeze; i++)
{
canFreeze &= Freezable.Freeze(_collection[i], isChecking);
}
return canFreeze;
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal FrugalStructList<Drawing> _collection;
internal uint _version = 0;
#endregion Internal Fields
#region Enumerator
/// <summary>
/// Enumerates the items in a DrawingCollection
/// </summary>
public struct Enumerator : IEnumerator, IEnumerator<Drawing>
{
#region Constructor
internal Enumerator(DrawingCollection list)
{
Debug.Assert(list != null, "list may not be null.");
_list = list;
_version = list._version;
_index = -1;
_current = default(Drawing);
}
#endregion
#region Methods
void IDisposable.Dispose()
{
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element,
/// false if the enumerator has passed the end of the collection.
/// </returns>
public bool MoveNext()
{
_list.ReadPreamble();
if (_version == _list._version)
{
if (_index > -2 && _index < _list._collection.Count - 1)
{
_current = _list._collection[++_index];
return true;
}
else
{
_index = -2; // -2 indicates "past the end"
return false;
}
}
else
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged));
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the
/// first element in the collection.
/// </summary>
public void Reset()
{
_list.ReadPreamble();
if (_version == _list._version)
{
_index = -1;
}
else
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged));
}
}
#endregion
#region Properties
object IEnumerator.Current
{
get
{
return this.Current;
}
}
/// <summary>
/// Current element
///
/// The behavior of IEnumerable<T>.Current is undefined
/// before the first MoveNext and after we have walked
/// off the end of the list. However, the IEnumerable.Current
/// contract requires that we throw exceptions
/// </summary>
public Drawing Current
{
get
{
if (_index > -1)
{
return _current;
}
else if (_index == -1)
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_NotStarted));
}
else
{
Debug.Assert(_index == -2, "expected -2, got " + _index + "\n");
throw new InvalidOperationException(SR.Get(SRID.Enumerator_ReachedEnd));
}
}
}
#endregion
#region Data
private Drawing _current;
private DrawingCollection _list;
private uint _version;
private int _index;
#endregion
}
#endregion
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary>
/// Initializes a new instance that is empty.
/// </summary>
public DrawingCollection()
{
_collection = new FrugalStructList<Drawing>();
}
/// <summary>
/// Initializes a new instance that is empty and has the specified initial capacity.
/// </summary>
/// <param name="capacity"> int - The number of elements that the new list is initially capable of storing. </param>
public DrawingCollection(int capacity)
{
_collection = new FrugalStructList<Drawing>(capacity);
}
/// <summary>
/// Creates a DrawingCollection with all of the same elements as collection
/// </summary>
public DrawingCollection(IEnumerable<Drawing> collection)
{
// The WritePreamble and WritePostscript aren't technically necessary
// in the constructor as of 1/20/05 but they are put here in case
// their behavior changes at a later date
WritePreamble();
if (collection != null)
{
bool needsItemValidation = true;
ICollection<Drawing> icollectionOfT = collection as ICollection<Drawing>;
if (icollectionOfT != null)
{
_collection = new FrugalStructList<Drawing>(icollectionOfT);
}
else
{
ICollection icollection = collection as ICollection;
if (icollection != null) // an IC but not and IC<T>
{
_collection = new FrugalStructList<Drawing>(icollection);
}
else // not a IC or IC<T> so fall back to the slower Add
{
_collection = new FrugalStructList<Drawing>();
foreach (Drawing item in collection)
{
if (item == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
Drawing newValue = item;
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
needsItemValidation = false;
}
}
if (needsItemValidation)
{
foreach (Drawing item in collection)
{
if (item == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
OnFreezablePropertyChanged(/* oldValue = */ null, item);
OnInsert(item);
}
}
WritePostscript();
}
else
{
throw new ArgumentNullException("collection");
}
}
#endregion Constructors
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Moq;
using Xunit;
namespace SourceCode.Clay.Net.Tests
{
public static class HttpClientUrlTemplateExtensionsTests
{
private readonly struct Data
{
public int A => 1;
public int B => 2;
public int C => 3;
}
private const string Expected = "http://test/1/2/3";
private static readonly UrlTemplate s_boxedTemplate = "http://test/{A}/{B}/{C}";
private static readonly UrlTemplate<Data> s_genericTemplate = "http://test/{A}/{B}/{C}";
private static readonly object s_boxed = new { A = 1, B = 2, C = 3 };
[Fact]
public static void HttpClientUrlTemplateExtensions_CreateRequestMessage_Boxed()
{
using (var cli = new HttpClient())
{
HttpRequestMessage message = cli.CreateRequestMessage(HttpMethod.Get, s_boxedTemplate, s_boxed);
Assert.Equal(HttpMethod.Get.Method, message.Method.Method);
Assert.Equal(Expected, message.RequestUri.ToString());
}
}
[Fact]
public static void HttpClientUrlTemplateExtensions_CreateRequestMessage_Generic()
{
using (var cli = new HttpClient())
{
HttpRequestMessage message = cli.CreateRequestMessage(HttpMethod.Get, s_genericTemplate, default);
Assert.Equal(HttpMethod.Get.Method, message.Method.Method);
Assert.Equal(Expected, message.RequestUri.ToString());
}
}
[Fact]
public static void HttpClientUrlTemplateExtensions_CreateRequestMessage_Boxed_Args()
{
Assert.Throws<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.CreateRequestMessage(null, HttpMethod.Delete, s_boxedTemplate, null));
Assert.Throws<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.CreateRequestMessage(new HttpClient(), null, s_boxedTemplate, null));
Assert.Throws<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.CreateRequestMessage(new HttpClient(), HttpMethod.Delete, default(UrlTemplate), null));
}
[Fact]
public static void HttpClientUrlTemplateExtensions_CreateRequestMessage_Generic_Args()
{
Assert.Throws<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.CreateRequestMessage(null, HttpMethod.Delete, s_genericTemplate, default));
Assert.Throws<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.CreateRequestMessage(new HttpClient(), null, s_genericTemplate, default));
Assert.Throws<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.CreateRequestMessage(new HttpClient(), HttpMethod.Delete, default(UrlTemplate<Data>), default));
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_DeleteAsync_Boxed()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Delete, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK))
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.DeleteAsync(s_boxedTemplate, s_boxed);
}
mock.VerifyAll();
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_DeleteAsync_Generic()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Delete, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK))
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.DeleteAsync(s_genericTemplate, default);
}
mock.VerifyAll();
}
[Fact]
public static void HttpClientUrlTemplateExtensions_DeleteAsync_Boxed_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.DeleteAsync(null, s_boxedTemplate, null));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.DeleteAsync(new HttpClient(), default(UrlTemplate), null));
}
[Fact]
public static void HttpClientUrlTemplateExtensions_DeleteAsync_Generic_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.DeleteAsync(null, s_genericTemplate, default));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.DeleteAsync(new HttpClient(), default(UrlTemplate<Data>), default));
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_GetAsync_Boxed()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Get, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK))
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.GetAsync(s_boxedTemplate, s_boxed);
}
mock.VerifyAll();
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_GetAsync_Generic()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Get, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK))
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.GetAsync(s_genericTemplate, default);
}
mock.VerifyAll();
}
[Fact]
public static void HttpClientUrlTemplateExtensions_GetAsync_Boxed_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetAsync(null, s_boxedTemplate, null));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetAsync(new HttpClient(), default(UrlTemplate), null));
}
[Fact]
public static void HttpClientUrlTemplateExtensions_GetAsync_Generic_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetAsync(null, s_genericTemplate, default));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetAsync(new HttpClient(), default(UrlTemplate<Data>), default));
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_GetAsync_Boxed_CompletionOption()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Get, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK))
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.GetAsync(s_boxedTemplate, s_boxed, HttpCompletionOption.ResponseHeadersRead);
}
mock.VerifyAll();
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_GetAsync_Generic_CompletionOption()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Get, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK))
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.GetAsync(s_genericTemplate, default, HttpCompletionOption.ResponseHeadersRead);
}
mock.VerifyAll();
}
[Fact]
public static void HttpClientUrlTemplateExtensions_GetAsync_Boxed_CompletionOption_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetAsync(null, s_boxedTemplate, null, HttpCompletionOption.ResponseContentRead));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetAsync(new HttpClient(), default(UrlTemplate), null, HttpCompletionOption.ResponseContentRead));
}
[Fact]
public static void HttpClientUrlTemplateExtensions_GetAsync_Generic_CompletionOption_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetAsync(null, s_genericTemplate, default, HttpCompletionOption.ResponseContentRead));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetAsync(new HttpClient(), default(UrlTemplate<Data>), default, HttpCompletionOption.ResponseContentRead));
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_GetByteArrayAsync_Boxed()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Get, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(Array.Empty<byte>())
})
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.GetByteArrayAsync(s_boxedTemplate, s_boxed);
}
mock.VerifyAll();
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_GetByteArrayAsync_Generic()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Get, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(Array.Empty<byte>())
})
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.GetByteArrayAsync(s_genericTemplate, default);
}
mock.VerifyAll();
}
[Fact]
public static void HttpClientUrlTemplateExtensions_GetByteArrayAsync_Boxed_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetByteArrayAsync(null, s_boxedTemplate, null));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetByteArrayAsync(new HttpClient(), default(UrlTemplate), null));
}
[Fact]
public static void HttpClientUrlTemplateExtensions_GetByteArrayAsync_Generic_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetByteArrayAsync(null, s_genericTemplate, default));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetByteArrayAsync(new HttpClient(), default(UrlTemplate<Data>), default));
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_GetStreamAsync_Boxed()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Get, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(new MemoryStream())
})
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.GetStreamAsync(s_boxedTemplate, s_boxed);
}
mock.VerifyAll();
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_GetStreamAsync_Generic()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Get, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(new MemoryStream())
})
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.GetStreamAsync(s_genericTemplate, default);
}
mock.VerifyAll();
}
[Fact]
public static void HttpClientUrlTemplateExtensions_GetStreamAsync_Boxed_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetStreamAsync(null, s_boxedTemplate, null));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetStreamAsync(new HttpClient(), default(UrlTemplate), null));
}
[Fact]
public static void HttpClientUrlTemplateExtensions_GetStreamAsync_Generic_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetStreamAsync(null, s_genericTemplate, default));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetStreamAsync(new HttpClient(), default(UrlTemplate<Data>), default));
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_GetStringAsync_Boxed()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Get, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Hello")
})
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.GetStringAsync(s_boxedTemplate, s_boxed);
}
mock.VerifyAll();
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_GetStringAsync_Generic()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Get, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Hello")
})
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.GetStringAsync(s_genericTemplate, default);
}
mock.VerifyAll();
}
[Fact]
public static void HttpClientUrlTemplateExtensions_GetStringAsync_Boxed_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetStringAsync(null, s_boxedTemplate, null));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetStringAsync(new HttpClient(), default(UrlTemplate), null));
}
[Fact]
public static void HttpClientUrlTemplateExtensions_GetStringAsync_Generic_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetStringAsync(null, s_genericTemplate, default));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.GetStringAsync(new HttpClient(), default(UrlTemplate<Data>), default));
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_PostAsync_Boxed()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Post, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK))
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.PostAsync(s_boxedTemplate, s_boxed, new StringContent("Test"));
}
mock.VerifyAll();
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_PostAsync_Generic()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Post, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK))
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.PostAsync(s_genericTemplate, default, new StringContent("Test"));
}
mock.VerifyAll();
}
[Fact]
public static void HttpClientUrlTemplateExtensions_PostAsync_Boxed_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.PostAsync(null, s_boxedTemplate, null, null));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.PostAsync(new HttpClient(), default(UrlTemplate), null, null));
}
[Fact]
public static void HttpClientUrlTemplateExtensions_PostAsync_Generic_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.PostAsync(null, s_genericTemplate, default, null));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.PostAsync(new HttpClient(), default(UrlTemplate<Data>), default, null));
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_PutAsync_Boxed()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Put, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK))
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.PutAsync(s_boxedTemplate, s_boxed, new StringContent("Test"));
}
mock.VerifyAll();
}
[Fact]
public static async Task HttpClientUrlTemplateExtensions_PutAsync_Generic()
{
var mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mock.SetupHttp(HttpMethod.Put, Expected)
.ReturnsAsync(req => new HttpResponseMessage(HttpStatusCode.OK))
.Verifiable();
using (HttpClient cli = mock.HttpClient())
{
await cli.PutAsync(s_genericTemplate, default, new StringContent("Test"));
}
mock.VerifyAll();
}
[Fact]
public static void HttpClientUrlTemplateExtensions_PutAsync_Boxed_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.PutAsync(null, s_boxedTemplate, null, null));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.PutAsync(new HttpClient(), default(UrlTemplate), null, null));
}
[Fact]
public static void HttpClientUrlTemplateExtensions_PutAsync_Generic_Args()
{
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.PutAsync(null, s_genericTemplate, default, null));
Assert.ThrowsAsync<ArgumentNullException>(() => HttpClientUrlTemplateExtensions
.PutAsync(new HttpClient(), default(UrlTemplate<Data>), default, null));
}
}
}
| |
using System;
using System.Collections.Generic;
using Rynchodon.Attached;
using Rynchodon.Threading;
using Rynchodon.Utility.Vectors;
using Rynchodon.Utility;
using Sandbox.Common.ObjectBuilders;
using Sandbox.Game.Entities;
using Sandbox.ModAPI;
using Sandbox.ModAPI.Interfaces;
using VRage;
using VRage.Game.ModAPI;
using VRage.Library.Utils;
using VRageMath;
namespace Rynchodon.Autopilot.Movement
{
/// <remarks>
/// Space engineers only uses the smallest inverse of the moments of inertia so GyroProfiler does not calculate the products of inertia.
/// </remarks>
public class GyroProfiler
{
private static readonly ThreadManager Thread = new ThreadManager(2, true, "GyroProfiler");
private static ITerminalProperty<bool> TP_GyroOverrideToggle;
private readonly IMyCubeGrid myGrid;
private PositionGrid m_centreOfMass;
private float m_mass;
private Vector3 m_inertiaMoment;
private Vector3 m_invertedInertiaMoment;
private Vector3 m_calcInertiaMoment;
private bool m_updating;
private FastResourceLock m_lock = new FastResourceLock();
public float GyroForce { get; private set; }
private Logable Log { get { return new Logable(myGrid); } }
/// <summary>The three moments of inertial for the coordinate axes</summary>
public Vector3 InertiaMoment
{
get
{
using (m_lock.AcquireSharedUsing())
return m_inertiaMoment;
}
}
/// <summary>Inverse of InertiaMoment</summary>
public Vector3 InvertedInertiaMoment
{
get
{
using (m_lock.AcquireSharedUsing())
return m_invertedInertiaMoment;
}
}
public GyroProfiler(IMyCubeGrid grid)
{
this.myGrid = grid;
ClearOverrides();
}
private void CalcGyroForce()
{
float force = 0f;
CubeGridCache cache = CubeGridCache.GetFor(myGrid);
if (cache == null)
return;
foreach (MyGyro g in cache.BlocksOfType(typeof(MyObjectBuilder_Gyro)))
if (g.IsWorking)
force += g.MaxGyroForce; // MaxGyroForce accounts for power ratio and modules
GyroForce = force;
}
public void Update()
{
CalcGyroForce();
PositionGrid centre = ((PositionWorld)myGrid.Physics.CenterOfMassWorld).ToGrid(myGrid);
if (Vector3.DistanceSquared(centre, m_centreOfMass) > 1f || Math.Abs(myGrid.Physics.Mass - m_mass) > 1000f)
{
using (m_lock.AcquireExclusiveUsing())
{
if (m_updating)
{
Log.DebugLog("already updating", Logger.severity.DEBUG);
return;
}
m_updating = true;
}
m_centreOfMass = centre;
m_mass = myGrid.Physics.Mass;
Thread.EnqueueAction(CalculateInertiaMoment);
}
}
#region Inertia Moment
private void CalculateInertiaMoment()
{
Log.DebugLog("recalculating inertia moment", Logger.severity.INFO);
m_calcInertiaMoment = Vector3.Zero;
foreach (IMySlimBlock slim in (AttachedGrid.AttachedSlimBlocks(myGrid, AttachedGrid.AttachmentKind.Physics, true)))
AddToInertiaMoment(slim);
using (m_lock.AcquireExclusiveUsing())
{
m_inertiaMoment = m_calcInertiaMoment;
m_invertedInertiaMoment = 1f / m_inertiaMoment;
}
Log.DebugLog("Inertia moment: " + m_inertiaMoment, Logger.severity.DEBUG);
Log.DebugLog("Inverted inertia moment: " + m_invertedInertiaMoment, Logger.severity.DEBUG);
m_updating = false;
}
private void AddToInertiaMoment(IMySlimBlock block)
{
float stepSize = myGrid.GridSize * 0.5f;
Vector3 Min, Max;
IMyCubeBlock fatblock = block.FatBlock;
if (fatblock != null)
{
Min = ((Vector3)fatblock.Min - 0.5f) * myGrid.GridSize + stepSize * 0.5f;
Max = ((Vector3)fatblock.Max + 0.5f) * myGrid.GridSize - stepSize * 0.5f;
}
else
{
Vector3 position = block.Position;
Min = (position - 0.5f) * myGrid.GridSize + stepSize * 0.5f;
Max = (position + 0.5f) * myGrid.GridSize - stepSize * 0.5f;
}
Vector3 size = (Max - Min) / stepSize + 1f;
float mass = block.Mass / size.Volume;
//Log.DebugLog("block: " + block.getBestName() + ", block mass: " + block.Mass + ", min: " + Min + ", max: " + Max + ", step: " + stepSize + ", size: " + size + ", volume: " + size.Volume + ", sub mass: " + mass, "AddToInertiaMoment()");
Vector3 current = Vector3.Zero;
for (current.X = Min.X; current.X <= Max.X + stepSize * 0.5f; current.X += stepSize)
for (current.Y = Min.Y; current.Y <= Max.Y + stepSize * 0.5f; current.Y += stepSize)
for (current.Z = Min.Z; current.Z <= Max.Z + stepSize * 0.5f; current.Z += stepSize)
AddToInertiaMoment(current, mass);
}
private void AddToInertiaMoment(Vector3 point, float mass)
{
Vector3 relativePosition = point - m_centreOfMass;
Vector3 moment = mass * relativePosition.LengthSquared() * Vector3.One - relativePosition * relativePosition;
m_calcInertiaMoment += moment;
}
#endregion Inertia Moment
#region Override
///// <summary>
///// Sets the overrides of gyros to match RotateVelocity. Should be called on game thread.
///// </summary>
//public void SetOverrides(ref DirectionWorld RotateVelocity)
//{
// ReadOnlyList<IMyCubeBlock> gyros = CubeGridCache.GetFor(myGrid).GetBlocksOfType(typeof(MyObjectBuilder_Gyro));
// if (gyros == null)
// return;
// foreach (MyGyro gyro in gyros)
// {
// if (!gyro.GyroOverride)
// SetOverride(gyro, true);
// gyro.SetGyroTorque(RotateVelocity.ToBlock(gyro));
// }
//}
/// <summary>
/// Disable overrides for every gyro. Should be called on game thread.
/// </summary>
public void ClearOverrides()
{
foreach (MyGyro gyro in CubeGridCache.GetFor(myGrid).BlocksOfType(typeof(MyObjectBuilder_Gyro)))
if (gyro.GyroOverride)
{
SetOverride(gyro, false);
gyro.SetGyroTorque(Vector3.Zero);
}
}
private void SetOverride(IMyTerminalBlock gyro, bool enable)
{
if (TP_GyroOverrideToggle == null)
TP_GyroOverrideToggle = gyro.GetProperty("Override") as ITerminalProperty<bool>;
TP_GyroOverrideToggle.SetValue(gyro, enable);
}
#endregion Override
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using Pb.Collections;
namespace Pbtk
{
namespace TileMap2D
{
/// <summary>
/// Converts TMX files into TileMap2D tile maps
/// </summary>
public static class TMXConverter
{
private static PropertyMap ReadProperties(XmlReader reader)
{
PropertyMap properties = new PropertyMap();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "properties")
break;
if (reader.NodeType == XmlNodeType.Element && reader.Name == "property")
{
string name = reader.GetAttribute("name");
string val = reader.GetAttribute("value");
if (val == null)
val = reader.ReadElementContentAsString();
properties.Add(name, val);
}
}
return properties;
}
private static TileAnimation ReadTileAnimation(XmlReader reader)
{
TileAnimation animation = new TileAnimation();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "animation")
break;
if (reader.NodeType == XmlNodeType.Element && reader.Name == "frame")
animation.AddFrame(int.Parse(reader.GetAttribute("tileid")), int.Parse(reader.GetAttribute("duration")));
}
return animation;
}
private static int GetIntAttribute(XmlReader reader, string name, int default_value)
{
string attr = reader.GetAttribute(name);
if (attr == null)
return default_value;
return int.Parse(attr);
}
private static float GetFloatAttribute(XmlReader reader, string name, float default_value)
{
string attr = reader.GetAttribute(name);
if (attr == null)
return default_value;
return float.Parse(attr);
}
private static TileSet ReadTileSet(XmlReader reader, string tile_sets_dir, float pixels_per_unit, bool force_rebuild_tile_sets, string relative_dir)
{
int slice_size_x = int.Parse(reader.GetAttribute("tilewidth"));
int slice_size_y = int.Parse(reader.GetAttribute("tileheight"));
int spacing = GetIntAttribute(reader, "spacing", 0);
int margin = GetIntAttribute(reader, "margin", 0);
float draw_offset_x = 0;
float draw_offset_y = 0;
TileSet tile_set = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "tileset")
break;
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "tileoffset":
draw_offset_x = GetIntAttribute(reader, "x", 0) / pixels_per_unit;
draw_offset_y = GetIntAttribute(reader, "y", 0) / pixels_per_unit;
break;
case "image":
string image_path = Pb.Path.Combine(relative_dir, reader.GetAttribute("source"));
Color32 transparent_color = new Color32(0, 0, 0, 0);
string transparent_attr = reader.GetAttribute("trans");
if (transparent_attr != null)
transparent_color = Pb.Math.HexToRGB(transparent_attr);
tile_set = ConverterUtility.SliceTileSetFromImage(
image_path,
tile_sets_dir,
pixels_per_unit,
margin, margin,
spacing, spacing,
slice_size_x, slice_size_y,
draw_offset_x, draw_offset_y,
transparent_color,
false,
true,
force_rebuild_tile_sets
);
break;
case "tile":
int id = GetIntAttribute(reader, "id", 0);
if (!reader.IsEmptyElement)
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "tile")
break;
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "animation":
tile_set.tiles[id].animation = ReadTileAnimation(reader);
break;
case "properties":
tile_set.tiles[id].properties = ReadProperties(reader);
break;
default:
break;
}
}
}
}
break;
default:
break;
}
}
}
return tile_set;
}
/// <summary>
/// Converts a TMX file into a TileMap2D tile map and returns the map
/// </summary>
/// <param name="input_system_path">The path to the TMX file</param>
/// <param name="output_name">The name of the output tile map</param>
/// <param name="tile_sets_dir">The directory to look for tile sets in</param>
/// <param name="pixels_per_unit">The number of pixels per unit to render the tile sets at</param>
/// <param name="chunk_size_x">The size of each chunk along the X axis</param>
/// <param name="chunk_size_y">The size of each chunk along the Y axis</param>
/// <param name="force_rebuild_tile_sets">Whether to force tile sets to be rebuilt</param>
/// <returns>The converted TileMap2D tile map</returns>
public static TileMap ConvertTMX(
string input_system_path,
string output_name,
string tile_sets_dir,
float pixels_per_unit,
int chunk_size_x,
int chunk_size_y,
bool force_rebuild_tile_sets,
TMXImportDelegate import_delegate
)
{
string input_system_dir = Path.GetDirectoryName(input_system_path);
string output_path = Pb.Path.Combine("Assets", output_name + ".asset");
TileMap tile_map = Pb.Utility.Asset.GetAndEdit<TileMap>(output_path);
List<int[]> layers = new List<int[]>();
int map_width = 0;
int map_height = 0;
List<TMXObjectLayer> object_layers = new List<TMXObjectLayer>();
XmlReader reader = XmlReader.Create(input_system_path);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "map":
map_width = GetIntAttribute(reader, "width", map_width);
map_height = GetIntAttribute(reader, "height", map_height);
if (chunk_size_x < 1)
chunk_size_x = map_width;
if (chunk_size_y < 1)
chunk_size_y = map_height;
switch (reader.GetAttribute("orientation"))
{
case "orthogonal":
tile_map.geometry.tiling = Pb.TileMap.Tiling.Rectangular;
break;
case "isometric":
tile_map.geometry.tiling = Pb.TileMap.Tiling.Isometric;
break;
case "staggered":
tile_map.geometry.tiling = Pb.TileMap.Tiling.StaggeredOdd;
break;
default:
throw new System.ArgumentException("Invalid TMX attribute 'orientation'");
}
tile_map.geometry.orientation = Pb.TileMap.Orientation.RightDown;
tile_map.geometry.size = new Vector3(GetIntAttribute(reader, "tilewidth", 1) / pixels_per_unit, GetIntAttribute(reader, "tileheight", 1) / pixels_per_unit, 1.0f);
break;
case "properties":
tile_map.properties = ReadProperties(reader);
break;
case "tileset":
int first_id = GetIntAttribute(reader, "firstgid", 0);
string source = reader.GetAttribute("source");
TileSet tile_set = null;
if (source == null)
tile_set = ReadTileSet(reader, tile_sets_dir, pixels_per_unit, force_rebuild_tile_sets, input_system_dir);
else
{
string tsx_system_path = Pb.Path.Combine(input_system_dir, source);
string tsx_system_dir = Path.GetDirectoryName(tsx_system_path);
XmlReader tsx_reader = XmlReader.Create(tsx_system_path);
while (tsx_reader.Read())
if (tsx_reader.NodeType == XmlNodeType.Element)
if (tsx_reader.Name == "tileset")
tile_set = ReadTileSet(tsx_reader, tile_sets_dir, pixels_per_unit, force_rebuild_tile_sets, tsx_system_dir);
}
if (tile_map.library.AddTileSet(tile_set, first_id) < 0)
throw new System.ArgumentException("Conflicting first GIDs for tilesets!");
break;
case "layer":
LayerInfo info = new LayerInfo();
info.name = reader.GetAttribute("name");
info.default_alpha = GetFloatAttribute(reader, "opacity", 1.0f);
info.unity_sorting_layer_name = Pb.Utility.SortingLayers.StandardSortingLayerName(layers.Count);
info.unity_sorting_layer_unique_id = Pb.Utility.SortingLayers.StandardSortingLayerID(layers.Count);
int[] ids = new int[map_height * map_width];
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "layer")
break;
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "data":
string encoding = reader.GetAttribute("encoding");
string compression = reader.GetAttribute("compression");
if (encoding == "base64")
{
int bytes_total = 4 * map_height * map_width;
byte[] buffer = new byte[bytes_total];
string base64 = reader.ReadElementContentAsString();
byte[] input = System.Convert.FromBase64String(base64);
if (compression == "zlib")
Pb.Utility.Decompress.Zlib(input, buffer, bytes_total);
else if (compression == "gzip")
Pb.Utility.Decompress.GZip(input, buffer, bytes_total);
else
buffer = input;
for (int i = 0; i < map_height * map_width; ++i)
ids[i] =
buffer[4 * i] |
(buffer[4 * i + 1] << 8) |
(buffer[4 * i + 2] << 16) |
(buffer[4 * i + 3] << 24);
}
else if (encoding == "csv")
{
string[] indices = reader.ReadElementContentAsString().Split(new char[] { ',' });
for (int i = 0; i < map_height * map_width; ++i)
ids[i] = (int)uint.Parse(indices[i]);
}
else
{
int i = 0;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "data")
break;
if (reader.NodeType == XmlNodeType.Element && reader.Name == "tile")
ids[i++] = (int)uint.Parse(reader.GetAttribute("gid"));
}
}
break;
case "properties":
info.properties = ReadProperties(reader);
break;
default:
break;
}
}
}
layers.Add(ids);
tile_map.layers.Add(info);
break;
case "objectgroup":
TMXObjectLayer object_layer = new TMXObjectLayer();
object_layer.name = reader.GetAttribute("name");
object_layer.default_alpha = GetFloatAttribute(reader, "opacity", 1.0f);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "objectgroup")
break;
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "object":
TMXObject obj = new TMXObject();
obj.name = reader.GetAttribute("name");
obj.rotation = GetFloatAttribute(reader, "rotation", 0.0f);
IVector2 position = new IVector2(GetIntAttribute(reader, "x", 0), GetIntAttribute(reader, "y", 0));
IVector2 size = new IVector2(GetIntAttribute(reader, "width", 0), GetIntAttribute(reader, "height", 0));
if (!reader.IsEmptyElement)
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "object")
break;
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "ellipse":
obj.type = TMXObjectType.Ellipse;
obj.points.Add(position);
obj.points.Add(size);
break;
case "polygon":
{
obj.type = TMXObjectType.Polygon;
string points_str = reader.GetAttribute("points");
foreach (string point_str in points_str.Split(new char[] { ' ' }))
{
string[] coords = point_str.Split(new char[] { ',' });
obj.points.Add(position + new IVector2(int.Parse(coords[0]), int.Parse(coords[1])));
}
break;
}
case "polyline":
{
obj.type = TMXObjectType.Polyline;
string points_str = reader.GetAttribute("points");
foreach (string point_str in points_str.Split(new char[] { ' ' }))
{
string[] coords = point_str.Split(new char[] { ',' });
obj.points.Add(position + new IVector2(int.Parse(coords[0]), int.Parse(coords[1])));
}
break;
}
case "properties":
obj.properties = ReadProperties(reader);
break;
}
}
}
}
if (obj.type == TMXObjectType.None)
{
obj.type = TMXObjectType.Rectangle;
obj.points.Add(position);
obj.points.Add(size);
}
object_layer.objects.Add(obj);
break;
case "properties":
object_layer.properties = ReadProperties(reader);
break;
default:
break;
}
}
}
object_layers.Add(object_layer);
break;
}
}
}
tile_map.chunk_manager = ConverterUtility.BuildStaticChunks(map_width, map_height, layers, chunk_size_x, chunk_size_y, output_name);
tile_map.chunk_renderer = Pb.Utility.Asset.GetAndEdit<ChunkRenderer>(Pb.Path.Combine("Assets", output_name + "_renderer.asset"));
import_delegate.ImportObjects(tile_map, object_layers);
return tile_map;
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmOrderWizard
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmOrderWizard() : base()
{
FormClosed += frmOrderWizard_FormClosed;
Resize += frmOrderWizard_Resize;
Load += frmOrderWizard_Load;
KeyPress += frmOrderWizard_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdUpdate;
public System.Windows.Forms.Button cmdUpdate {
get { return withEventsField_cmdUpdate; }
set {
if (withEventsField_cmdUpdate != null) {
withEventsField_cmdUpdate.Click -= cmdUpdate_Click;
}
withEventsField_cmdUpdate = value;
if (withEventsField_cmdUpdate != null) {
withEventsField_cmdUpdate.Click += cmdUpdate_Click;
}
}
}
private System.Windows.Forms.ListView withEventsField_lvData;
public System.Windows.Forms.ListView lvData {
get { return withEventsField_lvData; }
set {
if (withEventsField_lvData != null) {
withEventsField_lvData.ItemCheck -= lvData_ItemCheck;
}
withEventsField_lvData = value;
if (withEventsField_lvData != null) {
withEventsField_lvData.ItemCheck += lvData_ItemCheck;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdBuild;
public System.Windows.Forms.Button cmdBuild {
get { return withEventsField_cmdBuild; }
set {
if (withEventsField_cmdBuild != null) {
withEventsField_cmdBuild.Click -= cmdBuild_Click;
}
withEventsField_cmdBuild = value;
if (withEventsField_cmdBuild != null) {
withEventsField_cmdBuild.Click += cmdBuild_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdFilter;
public System.Windows.Forms.Button cmdFilter {
get { return withEventsField_cmdFilter; }
set {
if (withEventsField_cmdFilter != null) {
withEventsField_cmdFilter.Click -= cmdFilter_Click;
}
withEventsField_cmdFilter = value;
if (withEventsField_cmdFilter != null) {
withEventsField_cmdFilter.Click += cmdFilter_Click;
}
}
}
public System.Windows.Forms.Label Label1;
public System.Windows.Forms.Label _lbl_1;
public System.Windows.Forms.Label _lbl_0;
public System.Windows.Forms.Label lblFilter;
public System.Windows.Forms.Label lblDayEnd;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0;
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
public RectangleShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmOrderWizard));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.cmdExit = new System.Windows.Forms.Button();
this.cmdUpdate = new System.Windows.Forms.Button();
this.lvData = new System.Windows.Forms.ListView();
this.cmdBuild = new System.Windows.Forms.Button();
this.cmdFilter = new System.Windows.Forms.Button();
this.Label1 = new System.Windows.Forms.Label();
this._lbl_1 = new System.Windows.Forms.Label();
this._lbl_0 = new System.Windows.Forms.Label();
this.lblFilter = new System.Windows.Forms.Label();
this.lblDayEnd = new System.Windows.Forms.Label();
this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this.Shape1 = new RectangleShapeArray(components);
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Stock Re-order Wizard";
this.ClientSize = new System.Drawing.Size(695, 468);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmOrderWizard";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdExit.Size = new System.Drawing.Size(79, 34);
this.cmdExit.Location = new System.Drawing.Point(609, 3);
this.cmdExit.TabIndex = 9;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
this.cmdUpdate.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdUpdate.Text = "&Update";
this.cmdUpdate.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdUpdate.Size = new System.Drawing.Size(79, 34);
this.cmdUpdate.Location = new System.Drawing.Point(609, 45);
this.cmdUpdate.TabIndex = 5;
this.cmdUpdate.TabStop = false;
this.cmdUpdate.BackColor = System.Drawing.SystemColors.Control;
this.cmdUpdate.CausesValidation = true;
this.cmdUpdate.Enabled = true;
this.cmdUpdate.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdUpdate.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdUpdate.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdUpdate.Name = "cmdUpdate";
this.lvData.Size = new System.Drawing.Size(664, 337);
this.lvData.Location = new System.Drawing.Point(15, 114);
this.lvData.TabIndex = 7;
this.lvData.View = System.Windows.Forms.View.Details;
this.lvData.LabelEdit = false;
this.lvData.LabelWrap = true;
this.lvData.HideSelection = true;
this.lvData.CheckBoxes = true;
this.lvData.FullRowSelect = true;
this.lvData.ForeColor = System.Drawing.SystemColors.WindowText;
this.lvData.BackColor = System.Drawing.SystemColors.Window;
this.lvData.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lvData.Name = "lvData";
this.cmdBuild.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdBuild.Text = "&Build";
this.cmdBuild.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdBuild.Size = new System.Drawing.Size(79, 34);
this.cmdBuild.Location = new System.Drawing.Point(522, 3);
this.cmdBuild.TabIndex = 4;
this.cmdBuild.TabStop = false;
this.cmdBuild.BackColor = System.Drawing.SystemColors.Control;
this.cmdBuild.CausesValidation = true;
this.cmdBuild.Enabled = true;
this.cmdBuild.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdBuild.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdBuild.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdBuild.Name = "cmdBuild";
this.cmdFilter.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdFilter.Text = "&Filter";
this.cmdFilter.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdFilter.Size = new System.Drawing.Size(79, 34);
this.cmdFilter.Location = new System.Drawing.Point(522, 45);
this.cmdFilter.TabIndex = 8;
this.cmdFilter.TabStop = false;
this.cmdFilter.BackColor = System.Drawing.SystemColors.Control;
this.cmdFilter.CausesValidation = true;
this.cmdFilter.Enabled = true;
this.cmdFilter.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdFilter.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdFilter.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdFilter.Name = "cmdFilter";
this.Label1.Text = "&1. Affected Stock Items";
this.Label1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Label1.Size = new System.Drawing.Size(135, 13);
this.Label1.Location = new System.Drawing.Point(18, 90);
this.Label1.TabIndex = 6;
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label1.BackColor = System.Drawing.Color.Transparent;
this.Label1.Enabled = true;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = true;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_1.Text = "Applied Filter ";
this._lbl_1.Size = new System.Drawing.Size(45, 31);
this._lbl_1.Location = new System.Drawing.Point(6, 54);
this._lbl_1.TabIndex = 2;
this._lbl_1.BackColor = System.Drawing.Color.Transparent;
this._lbl_1.Enabled = true;
this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_1.UseMnemonic = true;
this._lbl_1.Visible = true;
this._lbl_1.AutoSize = false;
this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_1.Name = "_lbl_1";
this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_0.Text = "Day End Selection Criteria ";
this._lbl_0.Size = new System.Drawing.Size(51, 40);
this._lbl_0.Location = new System.Drawing.Point(0, 0);
this._lbl_0.TabIndex = 0;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Enabled = true;
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.UseMnemonic = true;
this._lbl_0.Visible = true;
this._lbl_0.AutoSize = false;
this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_0.Name = "_lbl_0";
this.lblFilter.BackColor = System.Drawing.Color.White;
this.lblFilter.Text = "Label1";
this.lblFilter.Size = new System.Drawing.Size(460, 37);
this.lblFilter.Location = new System.Drawing.Point(54, 42);
this.lblFilter.TabIndex = 3;
this.lblFilter.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblFilter.Enabled = true;
this.lblFilter.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblFilter.Cursor = System.Windows.Forms.Cursors.Default;
this.lblFilter.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblFilter.UseMnemonic = true;
this.lblFilter.Visible = true;
this.lblFilter.AutoSize = false;
this.lblFilter.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblFilter.Name = "lblFilter";
this.lblDayEnd.BackColor = System.Drawing.Color.White;
this.lblDayEnd.Text = "Label1";
this.lblDayEnd.Size = new System.Drawing.Size(460, 37);
this.lblDayEnd.Location = new System.Drawing.Point(54, 0);
this.lblDayEnd.TabIndex = 1;
this.lblDayEnd.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblDayEnd.Enabled = true;
this.lblDayEnd.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblDayEnd.Cursor = System.Windows.Forms.Cursors.Default;
this.lblDayEnd.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblDayEnd.UseMnemonic = true;
this.lblDayEnd.Visible = true;
this.lblDayEnd.AutoSize = false;
this.lblDayEnd.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblDayEnd.Name = "lblDayEnd";
this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_0.Size = new System.Drawing.Size(682, 355);
this._Shape1_0.Location = new System.Drawing.Point(6, 105);
this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_0.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_0.BorderWidth = 1;
this._Shape1_0.FillColor = System.Drawing.Color.Black;
this._Shape1_0.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_0.Visible = true;
this._Shape1_0.Name = "_Shape1_0";
this.Controls.Add(cmdExit);
this.Controls.Add(cmdUpdate);
this.Controls.Add(lvData);
this.Controls.Add(cmdBuild);
this.Controls.Add(cmdFilter);
this.Controls.Add(Label1);
this.Controls.Add(_lbl_1);
this.Controls.Add(_lbl_0);
this.Controls.Add(lblFilter);
this.Controls.Add(lblDayEnd);
this.ShapeContainer1.Shapes.Add(_Shape1_0);
this.Controls.Add(ShapeContainer1);
//Me.lbl.SetIndex(_lbl_1, CType(1, Short))
//Me.lbl.SetIndex(_lbl_0, CType(0, Short))
this.Shape1.SetIndex(_Shape1_0, Convert.ToInt16(0));
((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit();
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections.Generic;
using System.Reflection;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Connectors;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
public class RemoteGridServicesConnector :
GridServicesConnector, ISharedRegionModule, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private IGridService m_LocalGridService;
public RemoteGridServicesConnector()
{
}
public RemoteGridServicesConnector(IConfigSource source)
{
InitialiseServices(source);
}
#region ISharedRegionmodule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "RemoteGridServicesConnector"; }
}
public override void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("GridServices", "");
if (name == Name)
{
InitialiseServices(source);
m_Enabled = true;
m_log.Info("[REMOTE GRID CONNECTOR]: Remote grid enabled");
}
}
}
private void InitialiseServices(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[REMOTE GRID CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
base.Initialise(source);
m_LocalGridService = new LocalGridServicesConnector(source);
}
public void PostInitialise()
{
if (m_LocalGridService != null)
((ISharedRegionModule)m_LocalGridService).PostInitialise();
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (m_Enabled)
scene.RegisterModuleInterface<IGridService>(this);
if (m_LocalGridService != null)
((ISharedRegionModule)m_LocalGridService).AddRegion(scene);
}
public void RemoveRegion(Scene scene)
{
if (m_LocalGridService != null)
((ISharedRegionModule)m_LocalGridService).RemoveRegion(scene);
}
public void RegionLoaded(Scene scene)
{
}
#endregion
#region IGridService
public override string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
string msg = m_LocalGridService.RegisterRegion(scopeID, regionInfo);
if (msg == String.Empty)
return base.RegisterRegion(scopeID, regionInfo);
return msg;
}
public override bool DeregisterRegion(UUID regionID)
{
if (m_LocalGridService.DeregisterRegion(regionID))
return base.DeregisterRegion(regionID);
return false;
}
public override List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
return base.GetNeighbours(scopeID, regionID);
}
public override GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
GridRegion rinfo = m_LocalGridService.GetRegionByUUID(scopeID, regionID);
if (rinfo == null)
rinfo = base.GetRegionByUUID(scopeID, regionID);
return rinfo;
}
public override GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
GridRegion rinfo = m_LocalGridService.GetRegionByPosition(scopeID, x, y);
if (rinfo == null)
rinfo = base.GetRegionByPosition(scopeID, x, y);
return rinfo;
}
public override GridRegion GetRegionByName(UUID scopeID, string regionName)
{
GridRegion rinfo = m_LocalGridService.GetRegionByName(scopeID, regionName);
if (rinfo == null)
rinfo = base.GetRegionByName(scopeID, regionName);
return rinfo;
}
public override List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
List<GridRegion> rinfo = m_LocalGridService.GetRegionsByName(scopeID, name, maxNumber);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionsByName {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = base.GetRegionsByName(scopeID, name, maxNumber);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionsByName {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
return rinfo;
}
// Let's not override GetRegionRange -- let's get them all from the grid server
public override int GetRegionFlags(UUID scopeID, UUID regionID)
{
int flags = m_LocalGridService.GetRegionFlags(scopeID, regionID);
if (flags == -1)
flags = base.GetRegionFlags(scopeID, regionID);
return flags;
}
#endregion
}
}
| |
#region License
// Pomona is open source software released under the terms of the LICENSE specified in the
// project's repository, or alternatively at http://pomona.io/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Pomona.Common.Internals;
using Pomona.Common.Serialization;
using Pomona.Common.TypeSystem;
namespace Pomona.Routing
{
public class UrlSegment : IResourceNode, ITreeNodeWithRoot<UrlSegment>
{
private readonly int pathSegmentIndex;
private readonly string[] pathSegments;
private readonly RouteMatchTree tree;
private TypeSpec actualResultType;
private ReadOnlyCollection<UrlSegment> children;
private UrlSegment selectedChild;
private object value;
private bool valueIsLoaded;
internal UrlSegment(Route route, string[] pathSegments, RouteMatchTree tree)
: this(route, pathSegments, -1, null, tree)
{
}
private UrlSegment(Route route,
string[] pathSegments,
int pathSegmentIndex,
UrlSegment parent,
RouteMatchTree tree = null)
{
if (route == null)
throw new ArgumentNullException(nameof(route));
tree = tree ?? (parent != null ? parent.tree : null);
if (tree == null)
throw new ArgumentNullException(nameof(tree));
if (parent != null && route.Parent != parent.Route)
{
throw new ArgumentException(
"match child-parent relation must be same equivalent to route child-parent relation");
}
this.tree = tree;
Route = route;
this.pathSegments = pathSegments;
this.pathSegmentIndex = pathSegmentIndex;
Parent = parent;
}
/// <summary>
/// The actual result type, not only the expected one.
/// </summary>
public TypeSpec ActualResultType
{
get
{
if (this.actualResultType == null)
{
this.actualResultType = ResultItemType
.Maybe()
.Switch(x => x.Case<ResourceType>(y => !y.MergedTypes.Any()).Then(y => (TypeSpec)y))
.OrDefault(
() => Value != null ? Session.TypeMapper.FromType(Value.GetType()) : ResultType);
}
return this.actualResultType;
}
}
public ICollection<UrlSegment> Children
{
get
{
if (this.children == null)
this.children = CreateChildren().ToList().AsReadOnly();
return this.children;
}
}
public string Description => ToString();
public bool Exists => Value != null;
public IEnumerable<UrlSegment> FinalMatchCandidates
{
get { return Leafs.Where(x => x.IsLastSegment); }
}
public TypeSpec InputType => Route.InputType;
public bool IsLastSegment => this.pathSegmentIndex == (this.pathSegments.Length - 1);
public bool IsLeaf => Children.Count == 0;
public bool IsRoot => Parent != null;
public IEnumerable<UrlSegment> Leafs
{
get
{
if (IsLeaf)
return this.WrapAsArray();
return Children.SelectMany(x => x.Leafs);
}
}
public UrlSegment NextConflict
{
get { return this.WalkTree(x => x.SelectedChild).Skip(1).LastOrDefault(x => !x.IsLastSegment && x.SelectedChild == null); }
}
public string PathSegment => this.pathSegmentIndex >= 0 ? this.pathSegments[this.pathSegmentIndex] : string.Empty;
public string RelativePath => string.Join("/", this.pathSegments.Take(this.pathSegmentIndex + 1));
public TypeSpec ResultItemType => Route.ResultItemType;
public Route Route { get; }
public UrlSegment SelectedChild
{
get { return this.selectedChild ?? Children.SingleOrDefaultIfMultiple(); }
set
{
if (this.selectedChild != null && this.selectedChild.Parent != this)
throw new InvalidOperationException("Parent route of selected child is incorrect.");
this.selectedChild = value;
}
}
public UrlSegment SelectedFinalMatch
{
get { return this.WalkTree(x => x.SelectedChild).LastOrDefault(x => x.IsLastSegment); }
}
public IPomonaSession Session => this.tree.Session;
public object Get()
{
return Session.Get(this);
}
public IQueryable Query()
{
return Session.Query(this);
}
public override string ToString()
{
return string.Join("/",
this.AscendantsAndSelf().Select(
x =>
$"{x.GetPrefix()}{x.PathSegment}({x.GetTypeStringOfRoute()})").Reverse());
}
private IEnumerable<UrlSegment> CreateChildren()
{
var childPathSegmentIndex = this.pathSegmentIndex + 1;
if (childPathSegmentIndex < this.pathSegments.Length)
{
return
Route.MatchChildren(this.pathSegments[childPathSegmentIndex]).Select(
x => new UrlSegment(x, this.pathSegments, childPathSegmentIndex, this)).Where(
x => x.Leafs.Any(y => y.IsLastSegment));
}
return Enumerable.Empty<UrlSegment>();
}
private string GetPrefix()
{
if (Route is ResourcePropertyRoute)
return "p:";
if (Route is GetByIdRoute)
return "id:";
return string.Empty;
}
private string GetTypeStringOfRoute()
{
return $"{(Route.InputType != null ? Route.InputType.Name : "void")}=>{Route.ResultItemType.Name}{(Route.IsSingle ? "?" : "*")}";
}
public UrlSegment Parent { get; }
public TypeSpec ResultType => Route.ResultType;
public UrlSegment Root => this.tree.Root;
public object Value
{
get
{
if (!this.valueIsLoaded)
{
this.value = Get();
this.valueIsLoaded = true;
}
return this.value;
}
}
IEnumerable<UrlSegment> ITreeNode<UrlSegment>.Children => Children;
IResourceNode IResourceNode.Parent => Parent;
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Media;
using Avalonia.Visuals.Platform;
using Xunit;
namespace Avalonia.Visuals.UnitTests.Media
{
using System.Globalization;
using System.IO;
using Avalonia.Platform;
using Moq;
public class PathMarkupParserTests
{
[Fact]
public void Parses_Move()
{
var pathGeometry = new PathGeometry();
using (var context = new PathGeometryContext(pathGeometry))
using (var parser = new PathMarkupParser(context))
{
parser.Parse("M10 10");
var figure = pathGeometry.Figures[0];
Assert.Equal(new Point(10, 10), figure.StartPoint);
}
}
[Fact]
public void Parses_Line()
{
var pathGeometry = new PathGeometry();
using (var context = new PathGeometryContext(pathGeometry))
using (var parser = new PathMarkupParser(context))
{
parser.Parse("M0 0L10 10");
var figure = pathGeometry.Figures[0];
var segment = figure.Segments[0];
Assert.IsType<LineSegment>(segment);
var lineSegment = (LineSegment)segment;
Assert.Equal(new Point(10, 10), lineSegment.Point);
}
}
[Fact]
public void Parses_Close()
{
var pathGeometry = new PathGeometry();
using (var context = new PathGeometryContext(pathGeometry))
using (var parser = new PathMarkupParser(context))
{
parser.Parse("M0 0L10 10z");
var figure = pathGeometry.Figures[0];
Assert.True(figure.IsClosed);
}
}
[Fact]
public void Parses_FillMode_Before_Move()
{
var pathGeometry = new PathGeometry();
using (var context = new PathGeometryContext(pathGeometry))
using (var parser = new PathMarkupParser(context))
{
parser.Parse("F 1M0,0");
Assert.Equal(FillRule.NonZero, pathGeometry.FillRule);
}
}
[Theory]
[InlineData("M0 0 10 10 20 20")]
[InlineData("M0,0 10,10 20,20")]
[InlineData("M0,0,10,10,20,20")]
public void Parses_Implicit_Line_Command_After_Move(string pathData)
{
var pathGeometry = new PathGeometry();
using (var context = new PathGeometryContext(pathGeometry))
using (var parser = new PathMarkupParser(context))
{
parser.Parse(pathData);
var figure = pathGeometry.Figures[0];
var segment = figure.Segments[0];
Assert.IsType<LineSegment>(segment);
var lineSegment = (LineSegment)segment;
Assert.Equal(new Point(10, 10), lineSegment.Point);
figure = pathGeometry.Figures[1];
segment = figure.Segments[0];
Assert.IsType<LineSegment>(segment);
lineSegment = (LineSegment)segment;
Assert.Equal(new Point(20, 20), lineSegment.Point);
}
}
[Theory]
[InlineData("m0 0 10 10 20 20")]
[InlineData("m0,0 10,10 20,20")]
[InlineData("m0,0,10,10,20,20")]
public void Parses_Implicit_Line_Command_After_Relative_Move(string pathData)
{
var pathGeometry = new PathGeometry();
using (var context = new PathGeometryContext(pathGeometry))
using (var parser = new PathMarkupParser(context))
{
parser.Parse(pathData);
var figure = pathGeometry.Figures[0];
var segment = figure.Segments[0];
Assert.IsType<LineSegment>(segment);
var lineSegment = (LineSegment)segment;
Assert.Equal(new Point(10, 10), lineSegment.Point);
segment = figure.Segments[1];
Assert.IsType<LineSegment>(segment);
lineSegment = (LineSegment)segment;
Assert.Equal(new Point(30, 30), lineSegment.Point);
}
}
[Fact]
public void Parses_Scientific_Notation_Double()
{
var pathGeometry = new PathGeometry();
using (var context = new PathGeometryContext(pathGeometry))
using (var parser = new PathMarkupParser(context))
{
parser.Parse("M -1.01725E-005 -1.01725e-005");
var figure = pathGeometry.Figures[0];
Assert.Equal(
new Point(
double.Parse("-1.01725E-005", NumberStyles.Float, CultureInfo.InvariantCulture),
double.Parse("-1.01725E-005", NumberStyles.Float, CultureInfo.InvariantCulture)),
figure.StartPoint);
}
}
[Theory]
[InlineData("M5.5.5 5.5.5 5.5.5")]
[InlineData("F1M9.0771,11C9.1161,10.701,9.1801,10.352,9.3031,10L9.0001,10 9.0001,6.166 3.0001,9.767 3.0001,10 "
+ "9.99999999997669E-05,10 9.99999999997669E-05,0 3.0001,0 3.0001,0.234 9.0001,3.834 9.0001,0 "
+ "12.0001,0 12.0001,8.062C12.1861,8.043 12.3821,8.031 12.5941,8.031 15.3481,8.031 15.7961,9.826 "
+ "15.9201,11L16.0001,16 9.0001,16 9.0001,12.562 9.0001,11z")] // issue #1708
[InlineData(" M0 0")]
[InlineData("F1 M24,14 A2,2,0,1,1,20,14 A2,2,0,1,1,24,14 z")] // issue #1107
[InlineData("M0 0L10 10z")]
[InlineData("M50 50 L100 100 L150 50")]
[InlineData("M50 50L100 100L150 50")]
[InlineData("M50,50 L100,100 L150,50")]
[InlineData("M50 50 L-10 -10 L10 50")]
[InlineData("M50 50L-10-10L10 50")]
[InlineData("M50 50 L100 100 L150 50zM50 50 L70 70 L120 50z")]
[InlineData("M 50 50 L 100 100 L 150 50")]
[InlineData("M50 50 L100 100 L150 50 H200 V100Z")]
[InlineData("M 80 200 A 100 50 45 1 0 100 50")]
[InlineData(
"F1 M 16.6309 18.6563C 17.1309 8.15625 29.8809 14.1563 29.8809 14.1563C 30.8809 11.1563 34.1308 11.4063" +
" 34.1308 11.4063C 33.5 12 34.6309 13.1563 34.6309 13.1563C 32.1309 13.1562 31.1309 14.9062 31.1309 14.9" +
"062C 41.1309 23.9062 32.6309 27.9063 32.6309 27.9062C 24.6309 24.9063 21.1309 22.1562 16.6309 18.6563 Z" +
" M 16.6309 19.9063C 21.6309 24.1563 25.1309 26.1562 31.6309 28.6562C 31.6309 28.6562 26.3809 39.1562 18" +
".3809 36.1563C 18.3809 36.1563 18 38 16.3809 36.9063C 15 36 16.3809 34.9063 16.3809 34.9063C 16.3809 34" +
".9063 10.1309 30.9062 16.6309 19.9063 Z ")]
[InlineData(
"F1M16,12C16,14.209 14.209,16 12,16 9.791,16 8,14.209 8,12 8,11.817 8.03,11.644 8.054,11.467L6.585,10 4,10 " +
"4,6.414 2.5,7.914 0,5.414 0,3.586 3.586,0 4.414,0 7.414,3 7.586,3 9,1.586 11.914,4.5 10.414,6 " +
"12.461,8.046C14.45,8.278,16,9.949,16,12")]
public void Should_Parse(string pathData)
{
var pathGeometry = new PathGeometry();
using (var context = new PathGeometryContext(pathGeometry))
using (var parser = new PathMarkupParser(context))
{
parser.Parse(pathData);
Assert.True(true);
}
}
[Theory]
[InlineData("M0 0L10 10")]
[InlineData("M0 0L10 10z")]
[InlineData("M0 0L10 10 \n ")]
[InlineData("M0 0L10 10z \n ")]
[InlineData("M0 0L10 10 ")]
[InlineData("M0 0L10 10z ")]
public void Should_AlwaysEndFigure(string pathData)
{
var context = new Mock<IGeometryContext>();
using (var parser = new PathMarkupParser(context.Object))
{
parser.Parse(pathData);
}
context.Verify(v => v.EndFigure(It.IsAny<bool>()), Times.AtLeastOnce());
}
[Theory]
[InlineData("0 0")]
[InlineData("j")]
public void Throws_InvalidDataException_On_None_Defined_Command(string pathData)
{
var pathGeometry = new PathGeometry();
using (var context = new PathGeometryContext(pathGeometry))
using (var parser = new PathMarkupParser(context))
{
Assert.Throws<InvalidDataException>(() => parser.Parse(pathData));
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Counters;
namespace Orleans.Runtime.Scheduler
{
[DebuggerDisplay("OrleansTaskScheduler RunQueue={RunQueue.Length}")]
internal class OrleansTaskScheduler : TaskScheduler, ITaskScheduler, IHealthCheckParticipant
{
private readonly LoggerImpl logger = LogManager.GetLogger("Scheduler.OrleansTaskScheduler", LoggerType.Runtime);
private readonly ConcurrentDictionary<ISchedulingContext, WorkItemGroup> workgroupDirectory; // work group directory
private bool applicationTurnsStopped;
internal WorkQueue RunQueue { get; private set; }
internal WorkerPool Pool { get; private set; }
internal static TimeSpan TurnWarningLengthThreshold { get; set; }
// This is the maximum number of pending work items for a single activation before we write a warning log.
internal LimitValue MaxPendingItemsLimit { get; private set; }
internal TimeSpan DelayWarningThreshold { get; private set; }
public int RunQueueLength { get { return RunQueue.Length; } }
public static OrleansTaskScheduler CreateTestInstance(int maxActiveThreads, ICorePerformanceMetrics performanceMetrics)
{
return new OrleansTaskScheduler(
maxActiveThreads,
TimeSpan.FromMilliseconds(100),
TimeSpan.FromMilliseconds(100),
TimeSpan.FromMilliseconds(100),
NodeConfiguration.ENABLE_WORKER_THREAD_INJECTION,
LimitManager.GetDefaultLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS),
performanceMetrics);
}
public OrleansTaskScheduler(NodeConfiguration config, ICorePerformanceMetrics performanceMetrics)
: this(config.MaxActiveThreads, config.DelayWarningThreshold, config.ActivationSchedulingQuantum,
config.TurnWarningLengthThreshold, config.EnableWorkerThreadInjection, config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS),
performanceMetrics)
{
}
private OrleansTaskScheduler(int maxActiveThreads, TimeSpan delayWarningThreshold, TimeSpan activationSchedulingQuantum,
TimeSpan turnWarningLengthThreshold, bool injectMoreWorkerThreads, LimitValue maxPendingItemsLimit, ICorePerformanceMetrics performanceMetrics)
{
DelayWarningThreshold = delayWarningThreshold;
WorkItemGroup.ActivationSchedulingQuantum = activationSchedulingQuantum;
TurnWarningLengthThreshold = turnWarningLengthThreshold;
applicationTurnsStopped = false;
MaxPendingItemsLimit = maxPendingItemsLimit;
workgroupDirectory = new ConcurrentDictionary<ISchedulingContext, WorkItemGroup>();
RunQueue = new WorkQueue();
logger.Info("Starting OrleansTaskScheduler with {0} Max Active application Threads and 1 system thread.", maxActiveThreads);
Pool = new WorkerPool(this, performanceMetrics, maxActiveThreads, injectMoreWorkerThreads);
IntValueStatistic.FindOrCreate(StatisticNames.SCHEDULER_WORKITEMGROUP_COUNT, () => WorkItemGroupCount);
IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_INSTANTANEOUS_PER_QUEUE, "Scheduler.LevelOne"), () => RunQueueLength);
if (!StatisticsCollector.CollectShedulerQueuesStats) return;
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageRunQueueLengthLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageEnqueuedLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageArrivalRateLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumRunQueueLengthLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumEnqueuedLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumArrivalRateLevelTwo);
}
public int WorkItemGroupCount { get { return workgroupDirectory.Count; } }
private float AverageRunQueueLengthLevelTwo
{
get
{
if (workgroupDirectory.IsEmpty)
return 0;
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght) / (float)workgroupDirectory.Values.Count;
}
}
private float AverageEnqueuedLevelTwo
{
get
{
if (workgroupDirectory.IsEmpty)
return 0;
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests) / (float)workgroupDirectory.Values.Count;
}
}
private float AverageArrivalRateLevelTwo
{
get
{
if (workgroupDirectory.IsEmpty)
return 0;
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate) / (float)workgroupDirectory.Values.Count;
}
}
private float SumRunQueueLengthLevelTwo
{
get
{
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght);
}
}
private float SumEnqueuedLevelTwo
{
get
{
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests);
}
}
private float SumArrivalRateLevelTwo
{
get
{
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate);
}
}
public void Start()
{
Pool.Start();
}
public void StopApplicationTurns()
{
#if DEBUG
if (logger.IsVerbose) logger.Verbose("StopApplicationTurns");
#endif
// Do not RunDown the application run queue, since it is still used by low priority system targets.
applicationTurnsStopped = true;
foreach (var group in workgroupDirectory.Values)
{
if (!group.IsSystemGroup)
group.Stop();
}
}
public void Stop()
{
RunQueue.RunDown();
Pool.Stop();
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return new Task[0];
}
protected override void QueueTask(Task task)
{
var contextObj = task.AsyncState;
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("QueueTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current);
#endif
var context = contextObj as ISchedulingContext;
var workItemGroup = GetWorkItemGroup(context);
if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup)
{
// Drop the task on the floor if it's an application work item and application turns are stopped
logger.Warn(ErrorCode.SchedulerAppTurnsStopped_2, string.Format("Dropping Task {0} because application turns are stopped", task));
return;
}
if (workItemGroup == null)
{
var todo = new TaskWorkItem(this, task, context);
RunQueue.Add(todo);
}
else
{
var error = String.Format("QueueTask was called on OrleansTaskScheduler for task {0} on Context {1}."
+ " Should only call OrleansTaskScheduler.QueueTask with tasks on the null context.",
task.Id, context);
logger.Error(ErrorCode.SchedulerQueueTaskWrongCall, error);
throw new InvalidOperationException(error);
}
}
// Enqueue a work item to a given context
public void QueueWorkItem(IWorkItem workItem, ISchedulingContext context)
{
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("QueueWorkItem " + context);
#endif
if (workItem is TaskWorkItem)
{
var error = String.Format("QueueWorkItem was called on OrleansTaskScheduler for TaskWorkItem {0} on Context {1}."
+ " Should only call OrleansTaskScheduler.QueueWorkItem on WorkItems that are NOT TaskWorkItem. Tasks should be queued to the scheduler via QueueTask call.",
workItem.ToString(), context);
logger.Error(ErrorCode.SchedulerQueueWorkItemWrongCall, error);
throw new InvalidOperationException(error);
}
var workItemGroup = GetWorkItemGroup(context);
if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup)
{
// Drop the task on the floor if it's an application work item and application turns are stopped
var msg = string.Format("Dropping work item {0} because application turns are stopped", workItem);
logger.Warn(ErrorCode.SchedulerAppTurnsStopped_1, msg);
return;
}
workItem.SchedulingContext = context;
// We must wrap any work item in Task and enqueue it as a task to the right scheduler via Task.Start.
// This will make sure the TaskScheduler.Current is set correctly on any task that is created implicitly in the execution of this workItem.
if (workItemGroup == null)
{
Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem, context, this);
t.Start(this);
}
else
{
// Create Task wrapper for this work item
Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem, context, workItemGroup.TaskRunner);
t.Start(workItemGroup.TaskRunner);
}
}
// Only required if you have work groups flagged by a context that is not a WorkGroupingContext
public WorkItemGroup RegisterWorkContext(ISchedulingContext context)
{
if (context == null) return null;
var wg = new WorkItemGroup(this, context);
workgroupDirectory.TryAdd(context, wg);
return wg;
}
// Only required if you have work groups flagged by a context that is not a WorkGroupingContext
public void UnregisterWorkContext(ISchedulingContext context)
{
if (context == null) return;
WorkItemGroup workGroup;
if (workgroupDirectory.TryRemove(context, out workGroup))
workGroup.Stop();
}
// public for testing only -- should be private, otherwise
public WorkItemGroup GetWorkItemGroup(ISchedulingContext context)
{
if (context == null)
return null;
WorkItemGroup workGroup;
if(workgroupDirectory.TryGetValue(context, out workGroup))
return workGroup;
var error = String.Format("QueueWorkItem was called on a non-null context {0} but there is no valid WorkItemGroup for it.", context);
logger.Error(ErrorCode.SchedulerQueueWorkItemWrongContext, error);
throw new InvalidSchedulingContextException(error);
}
internal void CheckSchedulingContextValidity(ISchedulingContext context)
{
if (context == null)
{
throw new InvalidSchedulingContextException(
"CheckSchedulingContextValidity was called on a null SchedulingContext."
+ "Please make sure you are not trying to create a Timer from outside Orleans Task Scheduler, "
+ "which will be the case if you create it inside Task.Run.");
}
GetWorkItemGroup(context); // GetWorkItemGroup throws for Invalid context
}
public TaskScheduler GetTaskScheduler(ISchedulingContext context)
{
if (context == null)
return this;
WorkItemGroup workGroup;
return workgroupDirectory.TryGetValue(context, out workGroup) ? (TaskScheduler) workGroup.TaskRunner : this;
}
public override int MaximumConcurrencyLevel { get { return Pool.MaxActiveThreads; } }
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
//bool canExecuteInline = WorkerPoolThread.CurrentContext != null;
var ctx = RuntimeContext.Current;
bool canExecuteInline = ctx == null || ctx.ActivationContext==null;
#if DEBUG
if (logger.IsVerbose2)
{
logger.Verbose2("TryExecuteTaskInline Id={0} with Status={1} PreviouslyQueued={2} CanExecute={3}",
task.Id, task.Status, taskWasPreviouslyQueued, canExecuteInline);
}
#endif
if (!canExecuteInline) return false;
if (taskWasPreviouslyQueued)
canExecuteInline = TryDequeue(task);
if (!canExecuteInline) return false; // We can't execute tasks in-line on non-worker pool threads
// We are on a worker pool thread, so can execute this task
bool done = TryExecuteTask(task);
if (!done)
{
logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete1, "TryExecuteTaskInline: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}",
task.Id, task.Status);
}
return done;
}
/// <summary>
/// Run the specified task synchronously on the current thread
/// </summary>
/// <param name="task"><c>Task</c> to be executed</param>
public void RunTask(Task task)
{
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("RunTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current);
#endif
var context = RuntimeContext.CurrentActivationContext;
var workItemGroup = GetWorkItemGroup(context);
if (workItemGroup == null)
{
RuntimeContext.SetExecutionContext(null, this);
bool done = TryExecuteTask(task);
if (!done)
logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete2, "RunTask: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}",
task.Id, task.Status);
}
else
{
var error = String.Format("RunTask was called on OrleansTaskScheduler for task {0} on Context {1}. Should only call OrleansTaskScheduler.RunTask on tasks queued on a null context.",
task.Id, context);
logger.Error(ErrorCode.SchedulerTaskRunningOnWrongScheduler1, error);
throw new InvalidOperationException(error);
}
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("RunTask: Completed Id={0} with Status={1} task.AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current);
#endif
}
// Returns true if healthy, false if not
public bool CheckHealth(DateTime lastCheckTime)
{
return Pool.DoHealthCheck();
}
internal void PrintStatistics()
{
if (!logger.IsInfo) return;
var stats = Utils.EnumerableToString(workgroupDirectory.Values.OrderBy(wg => wg.Name), wg => string.Format("--{0}", wg.DumpStatus()), Environment.NewLine);
if (stats.Length > 0)
logger.LogWithoutBulkingAndTruncating(Severity.Info, ErrorCode.SchedulerStatistics,
"OrleansTaskScheduler.PrintStatistics(): RunQueue={0}, WorkItems={1}, Directory:" + Environment.NewLine + "{2}",
RunQueue.Length, WorkItemGroupCount, stats);
}
internal void DumpSchedulerStatus(bool alwaysOutput = true)
{
if (!logger.IsVerbose && !alwaysOutput) return;
PrintStatistics();
var sb = new StringBuilder();
sb.AppendLine("Dump of current OrleansTaskScheduler status:");
sb.AppendFormat("CPUs={0} RunQueue={1}, WorkItems={2} {3}",
Environment.ProcessorCount,
RunQueue.Length,
workgroupDirectory.Count,
applicationTurnsStopped ? "STOPPING" : "").AppendLine();
sb.AppendLine("RunQueue:");
RunQueue.DumpStatus(sb);
Pool.DumpStatus(sb);
foreach (var workgroup in workgroupDirectory.Values)
sb.AppendLine(workgroup.DumpStatus());
logger.LogWithoutBulkingAndTruncating(Severity.Info, ErrorCode.SchedulerStatus, sb.ToString());
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Management.Automation.Internal;
using System.Text;
namespace System.Management.Automation.Provider
{
#region NavigationCmdletProvider
/// <summary>
/// The base class for a Cmdlet provider that expose a hierarchy of items and containers.
/// </summary>
/// <remarks>
/// The NavigationCmdletProvider class is a base class that provider can derive from
/// to implement a set of methods that allow
/// the use of a set of core commands against the data store that the provider
/// gives access to. By implementing this interface users can take advantage
/// the recursive commands, nested containers, and relative paths.
/// </remarks>
public abstract class NavigationCmdletProvider : ContainerCmdletProvider
{
#region Internal methods
/// <summary>
/// Internal wrapper for the MakePath protected method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
/// <param name="parent">
/// The parent segment of a path to be joined with the child.
/// </param>
/// <param name="child">
/// The child segment of a path to be joined with the parent.
/// </param>
/// <param name="context">
/// The context under which this method is being called.
/// </param>
/// <returns>
/// A string that represents the parent and child segments of the path
/// joined by a path separator.
/// </returns>
/// <remarks>
/// This method should use lexical joining of two path segments with a path
/// separator character. It should not validate the path as a legal fully
/// qualified path in the provider namespace as each parameter could be only
/// partial segments of a path and joined they may not generate a fully
/// qualified path.
/// Example: the file system provider may get "windows\system32" as the parent
/// parameter and "foo.dll" as the child parameter. The method should join these
/// with the "\" separator and return "windows\system32\foo.dll". Note that
/// the returned path is not a fully qualified file system path.
///
/// Also beware that the path segments may contain characters that are illegal
/// in the provider namespace. These characters are most likely being used
/// for globbing and should not be removed by the implementation of this method.
/// </remarks>
internal string MakePath(
string parent,
string child,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
return MakePath(parent, child);
}
/// <summary>
/// Internal wrapper for the GetParentPath protected method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
/// <param name="path">
/// A fully qualified provider specific path to an item. The item may or
/// may not exist.
/// </param>
/// <param name="root">
/// The fully qualified path to the root of a drive. This parameter may be null
/// or empty if a mounted drive is not in use for this operation. If this parameter
/// is not null or empty the result of the method should not be a path to a container
/// that is a parent or in a different tree than the root.
/// </param>
/// <param name="context">
/// The context under which this method is being called.
/// </param>
/// <returns>
/// The path of the parent of the path parameter.
/// </returns>
/// <remarks>
/// This should be a lexical splitting of the path on the path separator character
/// for the provider namespace. For example, the file system provider should look
/// for the last "\" and return everything to the left of the "\".
/// </remarks>
internal string GetParentPath(
string path,
string root,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
return GetParentPath(path, root);
}
/// <summary>
/// Internal wrapper for the NormalizeRelativePath method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
/// <param name="path">
/// A fully qualified provider specific path to an item. The item should exist
/// or the provider should write out an error.
/// </param>
/// <param name="basePath">
/// The path that the return value should be relative to.
/// </param>
/// <param name="context">
/// The context under which this method is being called.
/// </param>
/// <returns>
/// A normalized path that is relative to the basePath that was passed. The
/// provider should parse the path parameter, normalize the path, and then
/// return the normalized path relative to the basePath.
/// </returns>
/// <remarks>
/// This method does not have to be purely syntactical parsing of the path. It
/// is encouraged that the provider actually use the path to lookup in its store
/// and create a relative path that matches the casing, and standardized path syntax.
/// </remarks>
internal string NormalizeRelativePath(
string path,
string basePath,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
return NormalizeRelativePath(path, basePath);
}
/// <summary>
/// Internal wrapper for the GetChildName protected method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
/// <param name="path">
/// The fully qualified path to the item
/// </param>
/// <returns>
/// The leaf element in the path.
/// </returns>
/// <param name="context">
/// The context under which this method is being called.
/// </param>
/// <remarks>
/// This should be implemented as a split on the path separator. The characters
/// in the fullPath may not be legal characters in the namespace but may be
/// used in globing or regular expression matching. The provider should not error
/// unless there are no path separators in the fully qualified path.
/// </remarks>
internal string GetChildName(
string path,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
return GetChildName(path);
}
/// <summary>
/// Internal wrapper for the IsItemContainer protected method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
/// <param name="path">
/// The path to the item to determine if it is a container.
/// </param>
/// <param name="context">
/// The context under which this method is being called.
/// </param>
/// <returns>
/// true if the item specified by path is a container, false otherwise.
/// </returns>
internal bool IsItemContainer(
string path,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
return IsItemContainer(path);
}
/// <summary>
/// Internal wrapper for the MoveItem protected method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
/// <param name="path">
/// The path to the item to be moved.
/// </param>
/// <param name="destination">
/// The path of the destination container.
/// </param>
/// <param name="context">
/// The context under which this method is being called.
/// </param>
/// <returns>
/// Nothing. All objects that are moved should be written to the WriteObject method.
/// </returns>
internal void MoveItem(
string path,
string destination,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
MoveItem(path, destination);
}
/// <summary>
/// Gives the provider to attach additional parameters to
/// the move-item cmdlet.
/// </summary>
/// <param name="path">
/// If the path was specified on the command line, this is the path
/// to the item to get the dynamic parameters for.
/// </param>
/// <param name="destination">
/// The path of the destination container.
/// </param>
/// <param name="context">
/// The context under which this method is being called.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
internal object MoveItemDynamicParameters(
string path,
string destination,
CmdletProviderContext context)
{
Context = context;
return MoveItemDynamicParameters(path, destination);
}
#endregion Internal methods
#region protected methods
/// <summary>
/// Joins two strings with a path a provider specific path separator.
/// </summary>
/// <param name="parent">
/// The parent segment of a path to be joined with the child.
/// </param>
/// <param name="child">
/// The child segment of a path to be joined with the parent.
/// </param>
/// <returns>
/// A string that represents the parent and child segments of the path
/// joined by a path separator.
/// </returns>
/// <remarks>
/// This method should use lexical joining of two path segments with a path
/// separator character. It should not validate the path as a legal fully
/// qualified path in the provider namespace as each parameter could be only
/// partial segments of a path and joined they may not generate a fully
/// qualified path.
/// Example: the file system provider may get "windows\system32" as the parent
/// parameter and "foo.dll" as the child parameter. The method should join these
/// with the "\" separator and return "windows\system32\foo.dll". Note that
/// the returned path is not a fully qualified file system path.
///
/// Also beware that the path segments may contain characters that are illegal
/// in the provider namespace. These characters are most likely being used
/// for globbing and should not be removed by the implementation of this method.
/// </remarks>
protected virtual string MakePath(string parent, string child)
{
return MakePath(parent, child, childIsLeaf: false);
}
/// <summary>
/// Joins two strings with a path a provider specific path separator.
/// </summary>
/// <param name="parent">
/// The parent segment of a path to be joined with the child.
/// </param>
/// <param name="child">
/// The child segment of a path to be joined with the parent.
/// </param>
/// <param name="childIsLeaf">
/// Indicate that the <paramref name="child"/> is the name of a child item that's guaranteed to exist
/// </param>
/// <remarks>
/// If the <paramref name="childIsLeaf"/> is True, then we don't normalize the child path, and would do
/// some checks to decide whether to normalize the parent path.
/// </remarks>
/// <returns></returns>
protected string MakePath(string parent, string child, bool childIsLeaf)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
string result = null;
if (parent == null &&
child == null)
{
// If both are null it is an error
throw PSTraceSource.NewArgumentException("parent");
}
else if (string.IsNullOrEmpty(parent) &&
string.IsNullOrEmpty(child))
{
// If both are empty, just return the empty string.
result = string.Empty;
}
else if (string.IsNullOrEmpty(parent) &&
!string.IsNullOrEmpty(child))
{
// If the parent is empty but the child is not, return the
// child
result = child.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);
}
else if (!string.IsNullOrEmpty(parent) &&
string.IsNullOrEmpty(child))
{
// If the child is empty but the parent is not, return the
// parent with the path separator appended.
// Append the default path separator
if (parent.EndsWith(StringLiterals.DefaultPathSeparator))
{
result = parent;
}
else
{
result = parent + StringLiterals.DefaultPathSeparator;
}
}
else
{
// Both parts are not empty so join them
// 'childIsLeaf == true' indicates that 'child' is actually the name of a child item and
// guaranteed to exist. In this case, we don't normalize the child path.
if (childIsLeaf)
{
parent = NormalizePath(parent);
}
else
{
// Normalize the path so that only the default path separator is used as a
// separator even if the user types the alternate slash.
parent = parent.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);
child = child.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);
}
// Joins the paths
StringBuilder builder = new StringBuilder(parent, parent.Length + child.Length + 1);
if (parent.EndsWith(StringLiterals.DefaultPathSeparator))
{
if (child.StartsWith(StringLiterals.DefaultPathSeparator))
{
builder.Append(child, 1, child.Length - 1);
}
else
{
builder.Append(child);
}
}
else
{
if (child.StartsWith(StringLiterals.DefaultPathSeparator))
{
if (parent.Length == 0)
{
builder.Append(child, 1, child.Length - 1);
}
else
{
builder.Append(child);
}
}
else
{
if (parent.Length > 0 && child.Length > 0)
{
builder.Append(StringLiterals.DefaultPathSeparator);
}
builder.Append(child);
}
}
result = builder.ToString();
}
return result;
}
}
/// <summary>
/// Removes the child segment of a path and returns the remaining parent
/// portion.
/// </summary>
/// <param name="path">
/// A fully qualified provider specific path to an item. The item may or
/// may not exist.
/// </param>
/// <param name="root">
/// The fully qualified path to the root of a drive. This parameter may be null
/// or empty if a mounted drive is not in use for this operation. If this parameter
/// is not null or empty the result of the method should not be a path to a container
/// that is a parent or in a different tree than the root.
/// </param>
/// <returns>
/// The path of the parent of the path parameter.
/// </returns>
/// <remarks>
/// This should be a lexical splitting of the path on the path separator character
/// for the provider namespace. For example, the file system provider should look
/// for the last "\" and return everything to the left of the "\".
/// </remarks>
protected virtual string GetParentPath(string path, string root)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
string parentPath = null;
// Verify the parameters
if (string.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentException("path");
}
if (root == null)
{
if (PSDriveInfo != null)
{
root = PSDriveInfo.Root;
}
}
// Normalize the path
path = NormalizePath(path);
path = path.TrimEnd(StringLiterals.DefaultPathSeparator);
string rootPath = string.Empty;
if (root != null)
{
rootPath = NormalizePath(root);
}
// Check to see if the path is equal to the root
// of the virtual drive
if (string.Compare(
path,
rootPath,
StringComparison.OrdinalIgnoreCase) == 0)
{
parentPath = string.Empty;
}
else
{
int lastIndex = path.LastIndexOf(StringLiterals.DefaultPathSeparator);
if (lastIndex != -1)
{
if (lastIndex == 0)
{
++lastIndex;
}
// Get the parent directory
parentPath = path.Substring(0, lastIndex);
}
else
{
parentPath = string.Empty;
}
}
return parentPath;
}
}
/// <summary>
/// Normalizes the path that was passed in and returns the normalized path
/// as a relative path to the basePath that was passed.
/// </summary>
/// <param name="path">
/// A fully qualified provider specific path to an item. The item should exist
/// or the provider should write out an error.
/// </param>
/// <param name="basePath">
/// The path that the return value should be relative to.
/// </param>
/// <returns>
/// A normalized path that is relative to the basePath that was passed. The
/// provider should parse the path parameter, normalize the path, and then
/// return the normalized path relative to the basePath.
/// </returns>
/// <remarks>
/// This method does not have to be purely syntactical parsing of the path. It
/// is encouraged that the provider actually use the path to lookup in its store
/// and create a relative path that matches the casing, and standardized path syntax.
///
/// Note, the base class implementation uses GetParentPath, GetChildName, and MakePath
/// to normalize the path and then make it relative to basePath. All string comparisons
/// are done using StringComparison.InvariantCultureIgnoreCase.
/// </remarks>
protected virtual string NormalizeRelativePath(
string path,
string basePath)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return ContractRelativePath(path, basePath, false, Context);
}
}
internal string ContractRelativePath(
string path,
string basePath,
bool allowNonExistingPaths,
CmdletProviderContext context)
{
Context = context;
if (path == null)
{
throw PSTraceSource.NewArgumentNullException("path");
}
if (path.Length == 0)
{
return string.Empty;
}
if (basePath == null)
{
basePath = string.Empty;
}
providerBaseTracer.WriteLine("basePath = {0}", basePath);
string result = path;
bool originalPathHadTrailingSlash = false;
string normalizedPath = path;
string normalizedBasePath = basePath;
// NTRAID#Windows 7-697922-2009/06/29-leeholm
// WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND
//
// This path normalization got moved here from the MakePath override in V2 to prevent
// over-normalization of paths. This was a net-improvement for providers that use the default
// implementations, but now incorrectly replaces forward slashes with back slashes during the call to
// GetParentPath and GetChildName. This breaks providers that are sensitive to slash direction, the only
// one we are aware of being the Active Directory provider. This change prevents this over-normalization
// from being done on AD paths.
//
// For more information, see Win7:695292. Do not change this code without closely working with the
// Active Directory team.
//
// WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND
if (!string.Equals(context.ProviderInstance.ProviderInfo.FullName,
@"Microsoft.ActiveDirectory.Management\ActiveDirectory", StringComparison.OrdinalIgnoreCase))
{
normalizedPath = NormalizePath(path);
normalizedBasePath = NormalizePath(basePath);
}
do // false loop
{
// Convert to the correct path separators and trim trailing separators
string originalPath = path;
Stack<string> tokenizedPathStack = null;
if (path.EndsWith(StringLiterals.DefaultPathSeparator))
{
path = path.TrimEnd(StringLiterals.DefaultPathSeparator);
originalPathHadTrailingSlash = true;
}
basePath = basePath.TrimEnd(StringLiterals.DefaultPathSeparator);
// See if the base and the path are already the same. We resolve this to
// ..\Leaf, since resolving "." to "." doesn't offer much information.
if (string.Equals(normalizedPath, normalizedBasePath, StringComparison.OrdinalIgnoreCase) &&
(!originalPath.EndsWith(StringLiterals.DefaultPathSeparator)))
{
string childName = GetChildName(path);
result = MakePath("..", childName);
break;
}
// If the base path isn't really a base, then we resolve to a parent
// path (such as ../../foo)
if (!normalizedPath.StartsWith(normalizedBasePath, StringComparison.OrdinalIgnoreCase) &&
(basePath.Length > 0))
{
result = string.Empty;
string commonBase = GetCommonBase(normalizedPath, normalizedBasePath);
Stack<string> parentNavigationStack = TokenizePathToStack(normalizedBasePath, commonBase);
int parentPopCount = parentNavigationStack.Count;
if (string.IsNullOrEmpty(commonBase))
{
parentPopCount--;
}
for (int leafCounter = 0; leafCounter < parentPopCount; leafCounter++)
{
result = MakePath("..", result);
}
// This is true if we get passed a base path like:
// c:\directory1\directory2
// and an actual path of
// c:\directory1
// Which happens when the user is in c:\directory1\directory2
// and wants to resolve something like:
// ..\..\dir*
// In that case (as above,) we keep the ..\..\directory1
// instead of ".." as would usually be returned
if (!string.IsNullOrEmpty(commonBase))
{
if (string.Equals(normalizedPath, commonBase, StringComparison.OrdinalIgnoreCase) &&
(!normalizedPath.EndsWith(StringLiterals.DefaultPathSeparator)))
{
string childName = GetChildName(path);
result = MakePath("..", result);
result = MakePath(result, childName);
}
else
{
string[] childNavigationItems = TokenizePathToStack(normalizedPath, commonBase).ToArray();
for (int leafCounter = 0; leafCounter < childNavigationItems.Length; leafCounter++)
{
result = MakePath(result, childNavigationItems[leafCounter]);
}
}
}
}
// Otherwise, we resolve to a child path (such as foo/bar)
else
{
tokenizedPathStack = TokenizePathToStack(path, basePath);
// Now we have to normalize the path
// by processing each token on the stack
Stack<string> normalizedPathStack;
try
{
normalizedPathStack = NormalizeThePath(tokenizedPathStack, path, basePath, allowNonExistingPaths);
}
catch (ArgumentException argumentException)
{
WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.InvalidArgument, null));
result = null;
break;
}
// Now that the path has been normalized, create the relative path
result = CreateNormalizedRelativePathFromStack(normalizedPathStack);
}
} while (false);
if (originalPathHadTrailingSlash)
{
result = result + StringLiterals.DefaultPathSeparator;
}
return result;
}
/// <summary>
/// Get the common base path of two paths.
/// </summary>
/// <param name="path1">One path.</param>
/// <param name="path2">Another path.</param>
private string GetCommonBase(string path1, string path2)
{
// Always see if the shorter path is a substring of the
// longer path. If it is not, take the child off of the longer
// path and compare again.
while (!string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase))
{
if (path2.Length > path1.Length)
{
path2 = GetParentPath(path2, null);
}
else
{
path1 = GetParentPath(path1, null);
}
}
return path1;
}
/// <summary>
/// Gets the name of the leaf element in the specified path.
/// </summary>
/// <param name="path">
/// The fully qualified path to the item
/// </param>
/// <returns>
/// The leaf element in the path.
/// </returns>
/// <remarks>
/// This should be implemented as a split on the path separator. The characters
/// in the fullPath may not be legal characters in the namespace but may be
/// used in globing or regular expression matching. The provider should not error
/// unless there are no path separators in the fully qualified path.
/// </remarks>
protected virtual string GetChildName(string path)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
// Verify the parameters
if (string.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentException("path");
}
// Normalize the path
path = NormalizePath(path);
// Trim trailing back slashes
path = path.TrimEnd(StringLiterals.DefaultPathSeparator);
string result = null;
int separatorIndex = path.LastIndexOf(StringLiterals.DefaultPathSeparator);
// Since there was no path separator return the entire path
if (separatorIndex == -1)
{
result = path;
}
// If the full path existed, we must semantically evaluate the parent path
else if (ItemExists(path, Context))
{
string parentPath = GetParentPath(path, null);
// No parent, return the entire path
if (string.IsNullOrEmpty(parentPath))
result = path;
// If the parent path ends with the path separator, we can't split
// the path based on that
else if (parentPath.IndexOf(StringLiterals.DefaultPathSeparator) == (parentPath.Length - 1))
{
separatorIndex = path.IndexOf(parentPath, StringComparison.OrdinalIgnoreCase) + parentPath.Length;
result = path.Substring(separatorIndex);
}
else
{
separatorIndex = path.IndexOf(parentPath, StringComparison.OrdinalIgnoreCase) + parentPath.Length;
result = path.Substring(separatorIndex + 1);
}
}
// Otherwise, use lexical parsing
else
{
result = path.Substring(separatorIndex + 1);
}
return result;
}
}
/// <summary>
/// Determines if the item specified by the path is a container.
/// </summary>
/// <param name="path">
/// The path to the item to determine if it is a container.
/// </param>
/// <returns>
/// true if the item specified by path is a container, false otherwise.
/// </returns>
/// <remarks>
/// Providers override this method to give the user the ability to check
/// to see if a provider object is a container using the test-path -container cmdlet.
///
/// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/>
/// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those
/// requirements by accessing the appropriate property from the base class.
///
/// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>.
/// </remarks>
protected virtual bool IsItemContainer(string path)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
throw
PSTraceSource.NewNotSupportedException(
SessionStateStrings.CmdletProvider_NotSupported);
}
}
/// <summary>
/// Moves the item specified by path to the specified destination.
/// </summary>
/// <param name="path">
/// The path to the item to be moved.
/// </param>
/// <param name="destination">
/// The path of the destination container.
/// </param>
/// <returns>
/// Nothing is returned, but all the objects that were moved should be written to the WriteItemObject method.
/// </returns>
/// <remarks>
/// Providers override this method to give the user the ability to move provider objects using
/// the move-item cmdlet.
///
/// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/>
/// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path and items being moved
/// meets those requirements by accessing the appropriate property from the base class.
///
/// By default overrides of this method should not move objects over existing items unless the Force
/// property is set to true. For instance, the FileSystem provider should not move c:\temp\foo.txt over
/// c:\bar.txt if c:\bar.txt already exists unless the Force parameter is true.
///
/// If <paramref name="destination"/> exists and is a container then Force isn't required and <paramref name="path"/>
/// should be moved into the <paramref name="destination"/> container as a child.
///
/// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>.
/// </remarks>
protected virtual void MoveItem(
string path,
string destination)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
throw
PSTraceSource.NewNotSupportedException(
SessionStateStrings.CmdletProvider_NotSupported);
}
}
/// <summary>
/// Gives the provider an opportunity to attach additional parameters to
/// the move-item cmdlet.
/// </summary>
/// <param name="path">
/// If the path was specified on the command line, this is the path
/// to the item to get the dynamic parameters for.
/// </param>
/// <param name="destination">
/// The path of the destination container.
/// </param>
/// <returns>
/// Overrides of this method should return an object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class or a
/// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>.
///
/// The default implementation returns null. (no additional parameters)
/// </returns>
protected virtual object MoveItemDynamicParameters(
string path,
string destination)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return null;
}
}
#endregion Protected methods
#region private members
/// <summary>
/// When a path contains both forward slash and backslash, we may introduce some errors by
/// normalizing the path. This method does some smart checks to reduce the chances of making
/// those errors.
/// </summary>
/// <param name="path">
/// The path to normalize
/// </param>
/// <returns>
/// Normalized path or the original path
/// </returns>
private string NormalizePath(string path)
{
// If we have a mix of slashes, then we may introduce an error by normalizing the path.
// For example: path HKCU:\Test\/ is pointing to a subkey '/' of 'HKCU:\Test', if we
// normalize it, then we will get a wrong path.
bool pathHasForwardSlash = path.IndexOf(StringLiterals.AlternatePathSeparator) != -1;
bool pathHasBackSlash = path.IndexOf(StringLiterals.DefaultPathSeparator) != -1;
bool pathHasMixedSlashes = pathHasForwardSlash && pathHasBackSlash;
bool shouldNormalizePath = true;
string normalizedPath = path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);
// There is a mix of slashes & the path is rooted & the path exists without normalization.
// In this case, we might want to skip the normalization to the path.
if (pathHasMixedSlashes && IsAbsolutePath(path) && ItemExists(path))
{
// 1. The path exists and ends with a forward slash, in this case, it's very possible the ending forward slash
// make sense to the underlying provider, so we skip normalization
// 2. The path exists, but not anymore after normalization, then we skip normalization
bool parentEndsWithForwardSlash = path.EndsWith(StringLiterals.AlternatePathSeparatorString, StringComparison.Ordinal);
if (parentEndsWithForwardSlash || !ItemExists(normalizedPath))
{
shouldNormalizePath = false;
}
}
return shouldNormalizePath ? normalizedPath : path;
}
/// <summary>
/// Test if the path is an absolute path.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private bool IsAbsolutePath(string path)
{
bool result = false;
if (LocationGlobber.IsAbsolutePath(path))
{
result = true;
}
else if (this.PSDriveInfo != null && !string.IsNullOrEmpty(this.PSDriveInfo.Root) &&
path.StartsWith(this.PSDriveInfo.Root, StringComparison.OrdinalIgnoreCase))
{
result = true;
}
return result;
}
/// <summary>
/// Tokenizes the specified path onto a stack.
/// </summary>
/// <param name="path">
/// The path to tokenize.
/// </param>
/// <param name="basePath">
/// The base part of the path that should not be tokenized.
/// </param>
/// <returns>
/// A stack containing the tokenized path with leaf elements on the bottom
/// of the stack and the most ancestral parent at the top.
/// </returns>
private Stack<string> TokenizePathToStack(string path, string basePath)
{
Stack<string> tokenizedPathStack = new Stack<string>();
string tempPath = path;
string previousParent = path;
while (tempPath.Length > basePath.Length)
{
// Get the child name and push it onto the stack
// if its valid
string childName = GetChildName(tempPath);
if (string.IsNullOrEmpty(childName))
{
// Push the parent on and then stop
tokenizedPathStack.Push(tempPath);
break;
}
providerBaseTracer.WriteLine("tokenizedPathStack.Push({0})", childName);
tokenizedPathStack.Push(childName);
// Get the parent path and verify if we have to continue
// tokenizing
tempPath = GetParentPath(tempPath, basePath);
if (tempPath.Length >= previousParent.Length)
{
break;
}
previousParent = tempPath;
}
return tokenizedPathStack;
}
/// <summary>
/// Given the tokenized path, the relative path elements are removed.
/// </summary>
/// <param name="tokenizedPathStack">
/// A stack containing path elements where the leaf most element is at
/// the bottom of the stack and the most ancestral parent is on the top.
/// Generally this stack comes from TokenizePathToStack().
/// </param>
/// <param name="path">
/// The path being normalized. Just used for error reporting.
/// </param>
/// <param name="basePath">
/// The base path to make the path relative to. Just used for error reporting.
/// </param>
/// <param name="allowNonExistingPaths">
/// Determines whether to throw an exception on non-existing paths.
/// </param>
/// <returns>
/// A stack in reverse order with the path elements normalized and all relative
/// path tokens removed.
/// </returns>
private static Stack<string> NormalizeThePath(
Stack<string> tokenizedPathStack, string path,
string basePath, bool allowNonExistingPaths)
{
Stack<string> normalizedPathStack = new Stack<string>();
while (tokenizedPathStack.Count > 0)
{
string childName = tokenizedPathStack.Pop();
providerBaseTracer.WriteLine("childName = {0}", childName);
// Ignore the current directory token
if (childName.Equals(".", StringComparison.OrdinalIgnoreCase))
{
// Just ignore it and move on.
continue;
}
// Make sure we don't have
if (childName.Equals("..", StringComparison.OrdinalIgnoreCase))
{
if (normalizedPathStack.Count > 0)
{
// Pop the result and continue processing
string poppedName = normalizedPathStack.Pop();
providerBaseTracer.WriteLine("normalizedPathStack.Pop() : {0}", poppedName);
continue;
}
else
{
if (!allowNonExistingPaths)
{
PSArgumentException e =
(PSArgumentException)
PSTraceSource.NewArgumentException(
"path",
SessionStateStrings.NormalizeRelativePathOutsideBase,
path,
basePath);
throw e;
}
}
}
providerBaseTracer.WriteLine("normalizedPathStack.Push({0})", childName);
normalizedPathStack.Push(childName);
}
return normalizedPathStack;
}
/// <summary>
/// Pops each leaf element of the stack and uses MakePath to generate the relative path.
/// </summary>
/// <param name="normalizedPathStack">
/// The stack containing the leaf elements of the path.
/// </param>
/// <returns>
/// A path that is made up of the leaf elements on the given stack.
/// </returns>
/// <remarks>
/// The elements on the stack start from the leaf element followed by its parent
/// followed by its parent, etc. Each following element on the stack is the parent
/// of the one before it.
/// </remarks>
private string CreateNormalizedRelativePathFromStack(Stack<string> normalizedPathStack)
{
string leafElement = string.Empty;
while (normalizedPathStack.Count > 0)
{
if (string.IsNullOrEmpty(leafElement))
{
leafElement = normalizedPathStack.Pop();
}
else
{
string parentElement = normalizedPathStack.Pop();
leafElement = MakePath(parentElement, leafElement);
}
}
return leafElement;
}
#endregion private members
}
#endregion NavigationCmdletProvider
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OmniSharp.Models.Rename;
using OmniSharp.Roslyn.CSharp.Services.Refactoring;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class RenameFacts : AbstractSingleRequestHandlerTestFixture<RenameService>
{
public RenameFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
}
protected override string EndpointName => OmniSharpEndpoints.Rename;
[Fact]
public async Task Rename_UpdatesWorkspaceAndDocumentText()
{
const string code = @"
using System;
namespace OmniSharp.Models
{
public class CodeFormat$$Response
{
public string Buffer { get; set; }
}
}";
const string expectedCode = @"
using System;
namespace OmniSharp.Models
{
public class foo
{
public string Buffer { get; set; }
}
}";
var testFile = new TestFile("test.cs", code);
using (var host = CreateOmniSharpHost(testFile))
{
await ValidateRename(host, testFile, expectedCode, async () => await PerformRename(host, testFile, "foo", applyTextChanges: true));
}
}
[Fact]
public async Task Rename_DoesNotUpdatesWorkspace()
{
const string fileContent = @"
using System;
namespace OmniSharp.Models
{
public class CodeFormat$$Response
{
public string Buffer { get; set; }
}
}";
var testFile = new TestFile("test.cs", fileContent);
using (var host = CreateOmniSharpHost(testFile))
{
var result = await PerformRename(host, testFile, "foo", applyTextChanges: false);
var solution = host.Workspace.CurrentSolution;
var documentId = solution.GetDocumentIdsWithFilePath(testFile.FileName).First();
var document = solution.GetDocument(documentId);
var sourceText = await document.GetTextAsync();
// check that the workspace has not been updated
Assert.Equal(testFile.Content.Code, sourceText.ToString());
}
}
[Fact]
public async Task Rename_UpdatesMultipleDocumentsIfNecessary()
{
const string code1 = "public class F$$oo {}";
const string code2 = @"
public class Bar {
public Foo Property {get; set;}
}";
const string expectedCode = @"
public class Bar {
public xxx Property {get; set;}
}";
var testFiles = new[]
{
new TestFile("test1.cs", code1),
new TestFile("test2.cs", code2)
};
using (var host = CreateOmniSharpHost(testFiles))
{
var result = await PerformRename(host, testFiles, "xxx");
var solution = host.Workspace.CurrentSolution;
var documentId1 = solution.GetDocumentIdsWithFilePath(testFiles[0].FileName).First();
var document1 = solution.GetDocument(documentId1);
var sourceText1 = await document1.GetTextAsync();
var documentId2 = solution.GetDocumentIdsWithFilePath(testFiles[1].FileName).First();
var document2 = solution.GetDocument(documentId2);
var sourceText2 = await document2.GetTextAsync();
var changes = result.Changes.ToArray();
//compare workspace change with response for file 1
Assert.Equal(sourceText1.ToString(), changes[0].Buffer);
//check that response refers to modified file 1
Assert.Equal(testFiles[0].FileName, changes[0].FileName);
//check response for change in file 1
Assert.Equal(@"public class xxx {}", changes[0].Buffer);
//compare workspace change with response for file 2
Assert.Equal(sourceText2.ToString(), changes[1].Buffer);
//check that response refers to modified file 2
Assert.Equal(testFiles[1].FileName, changes[1].FileName);
//check response for change in file 2
Assert.Equal(expectedCode, changes[1].Buffer);
}
}
[Fact]
public async Task Rename_UpdatesMultipleDocumentsIfNecessaryAndProducesTextChangesIfAsked()
{
const string code1 = "public class F$$oo {}";
const string code2 = @"
public class Bar {
public Foo Property {get; set;}
}";
var testFiles = new[]
{
new TestFile("test1.cs", code1),
new TestFile("test2.cs", code2)
};
var result = await PerformRename(testFiles, "xxx", wantsTextChanges: true);
var changes = result.Changes.ToArray();
Assert.Equal(2, changes.Length);
Assert.Single(changes[0].Changes);
Assert.Null(changes[0].Buffer);
Assert.Equal("xxx", changes[0].Changes.First().NewText);
Assert.Equal(0, changes[0].Changes.First().StartLine);
Assert.Equal(13, changes[0].Changes.First().StartColumn);
Assert.Equal(0, changes[0].Changes.First().EndLine);
Assert.Equal(16, changes[0].Changes.First().EndColumn);
Assert.Null(changes[1].Buffer);
Assert.Equal("xxx", changes[1].Changes.First().NewText);
Assert.Equal(2, changes[1].Changes.First().StartLine);
Assert.Equal(11, changes[1].Changes.First().StartColumn);
Assert.Equal(2, changes[1].Changes.First().EndLine);
Assert.Equal(14, changes[1].Changes.First().EndColumn);
}
[Fact]
public async Task Rename_DoesTheRightThingWhenDocumentIsNotFound()
{
const string fileContent = "class f$$oo{}";
var testFile = new TestFile("test.cs", fileContent);
// Note: We intentionally aren't including the TestFile in the host.
using (var host = CreateEmptyOmniSharpHost())
{
var result = await PerformRename(host, testFile, "xxx", updateBuffer: true);
var changes = result.Changes.ToArray();
Assert.Single(changes);
Assert.Equal(testFile.FileName, changes[0].FileName);
}
}
[Fact]
public async Task Rename_DoesNotExplodeWhenAttemptingToRenameALibrarySymbol()
{
const string fileContent = @"
using System;
public class Program
{
public static void Main()
{
Guid.New$$Guid();
}
}";
var testFile = new TestFile("test.cs", fileContent);
var result = await PerformRename(testFile, "foo");
Assert.Empty(result.Changes);
Assert.NotNull(result.ErrorMessage);
}
[Fact]
public async Task Rename_DoesNotDuplicateRenamesWithMultipleFrameworks()
{
const string fileContent = @"
using System;
public class Program
{
public void Main(bool aBool$$ean)
{
Console.Write(aBoolean);
}
}";
var testFile = new TestFile("test.cs", fileContent);
var result = await PerformRename(testFile, "foo", wantsTextChanges: true);
var changes = result.Changes.ToArray();
Assert.Single(changes);
Assert.Equal(testFile.FileName, changes[0].FileName);
Assert.Equal(2, changes[0].Changes.Count());
}
[Fact]
public async Task Rename_CanRenameInComments()
{
const string code = @"
using System;
namespace ConsoleApplication
{
/// <summary>
/// This program performs an important work and calls Bar.
/// </summary>
public class Program
{
static void Ba$$r() {}
}
}";
const string expectedCode = @"
using System;
namespace ConsoleApplication
{
/// <summary>
/// This program performs an important work and calls Foo.
/// </summary>
public class Program
{
static void Foo() {}
}
}";
var testFile = new TestFile("test.cs", code);
using (var host = CreateOmniSharpHost(new[] { testFile }, new Dictionary<string, string>
{
["RenameOptions:RenameInComments"] = "true"
}))
{
await ValidateRename(host, testFile, expectedCode, async () => await PerformRename(host, testFile, "Foo", applyTextChanges: true));
}
}
[Fact]
public async Task Rename_CanRenameInOverloads()
{
const string code = @"
public class Foo
{
public void Do$$Stuff() {}
public void DoStuff(int foo) {}
public void DoStuff(int foo, int bar) {}
}";
const string expectedCode = @"
public class Foo
{
public void DoFunnyStuff() {}
public void DoFunnyStuff(int foo) {}
public void DoFunnyStuff(int foo, int bar) {}
}";
var testFile = new TestFile("test.cs", code);
using (var host = CreateOmniSharpHost(new[] { testFile }, new Dictionary<string, string>
{
["RenameOptions:RenameOverloads"] = "true"
}))
{
await ValidateRename(host, testFile, expectedCode, async () => await PerformRename(host, testFile, "DoFunnyStuff", applyTextChanges: true));
}
}
[Fact]
public async Task Rename_CanRenameInStrings()
{
const string code = @"
namespace ConsoleApplication
{
public class Ba$$r
{
public static string Name = ""Bar"";
}
}";
const string expectedCode = @"
namespace ConsoleApplication
{
public class Foo
{
public static string Name = ""Foo"";
}
}";
var testFile = new TestFile("test.cs", code);
using (var host = CreateOmniSharpHost(new[] { testFile }, new Dictionary<string, string>
{
["RenameOptions:RenameInStrings"] = "true"
}))
{
await ValidateRename(host, testFile, expectedCode, async () => await PerformRename(host, testFile, "Foo", applyTextChanges: true));
}
}
private async Task ValidateRename(OmniSharpTestHost host, TestFile testFile, string expectedCode, Func<Task<RenameResponse>> rename)
{
var result = await rename();
var solution = host.Workspace.CurrentSolution;
var documentId = solution.GetDocumentIdsWithFilePath(testFile.FileName).First();
var document = solution.GetDocument(documentId);
var sourceText = await document.GetTextAsync();
var change = result.Changes.Single();
// compare workspace change with response
Assert.Equal(change.Buffer, sourceText.ToString());
// check that response refers to correct modified file
Assert.Equal(change.FileName, testFile.FileName);
// check response for change
Assert.Equal(expectedCode, change.Buffer);
}
private Task<RenameResponse> PerformRename(
TestFile testFile, string renameTo,
bool wantsTextChanges = false,
bool applyTextChanges = true,
bool updateBuffer = false)
{
return PerformRename(new[] { testFile }, renameTo, wantsTextChanges, applyTextChanges, updateBuffer);
}
private async Task<RenameResponse> PerformRename(
TestFile[] testFiles, string renameTo,
bool wantsTextChanges = false,
bool applyTextChanges = true,
bool updateBuffer = false)
{
SharedOmniSharpTestHost.AddFilesToWorkspace(testFiles);
return await PerformRename(SharedOmniSharpTestHost, testFiles, renameTo, wantsTextChanges, applyTextChanges, updateBuffer);
}
private Task<RenameResponse> PerformRename(
OmniSharpTestHost host, TestFile testFile, string renameTo,
bool wantsTextChanges = false,
bool applyTextChanges = true,
bool updateBuffer = false)
{
return PerformRename(host, new[] { testFile }, renameTo, wantsTextChanges, applyTextChanges, updateBuffer);
}
private async Task<RenameResponse> PerformRename(
OmniSharpTestHost host, TestFile[] testFiles, string renameTo,
bool wantsTextChanges = false,
bool applyTextChanges = true,
bool updateBuffer = false)
{
var activeFile = testFiles.Single(tf => tf.Content.HasPosition);
var point = activeFile.Content.GetPointFromPosition();
var request = new RenameRequest
{
Line = point.Line,
Column = point.Offset,
RenameTo = renameTo,
FileName = activeFile.FileName,
Buffer = activeFile.Content.Code,
WantsTextChanges = wantsTextChanges,
ApplyTextChanges = applyTextChanges
};
var requestHandler = GetRequestHandler(host);
if (updateBuffer)
{
await host.Workspace.BufferManager.UpdateBufferAsync(request);
}
return await requestHandler.Handle(request);
}
}
}
| |
#region Header
//
// CmdWallDimensions.cs - determine wall dimensions
// by iterating over wall geometry faces
//
// Copyright (C) 2008-2021 by Jeremy Tammik,
// Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using NormalAndOrigins
= System.Collections.Generic.KeyValuePair<
Autodesk.Revit.DB.XYZ, System.Collections.Generic.List<Autodesk.Revit.DB.XYZ>>;
#endregion // Namespaces
namespace BuildingCoder
{
/// <summary>
/// List dimensions for a quadrilateral wall with
/// openings. In this algorithm, we collect all
/// the faces with parallel normal vectors and
/// calculate the maximal distance between any
/// two pairs of them. This is the wall dimension
/// in that direction.
/// </summary>
[Transaction(TransactionMode.ReadOnly)]
internal class CmdWallDimensions : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
var app = commandData.Application;
var uidoc = app.ActiveUIDocument;
var doc = uidoc.Document;
var msg = string.Empty;
//Selection sel = uidoc.Selection; // 2014
//foreach( Element e in sel.Elements ) // 2014
var walls = new List<Element>();
if (Util.GetSelectedElementsOrAll(walls, uidoc, typeof(Wall)))
foreach (Wall wall in walls)
msg += ProcessWall(wall);
if (0 == msg.Length) msg = "Please select some walls.";
Util.InfoMsg(msg);
return Result.Succeeded;
}
/// <summary>
/// Retrieve the planar face normal and origin
/// from all of the solid's planar faces and
/// insert them into the map mapping face normals
/// to a list of all origins of different faces
/// sharing this normal.
/// </summary>
/// <param name="naos">
/// Map mapping each normal vector
/// to a list of the origins of all planar faces
/// sharing this normal direction
/// </param>
/// <param name="solid">Input solid</param>
private void getFaceNaos(
Dictionary<XYZ, List<XYZ>> naos,
Solid solid)
{
foreach (Face face in solid.Faces)
{
var planarFace = face as PlanarFace;
if (null != planarFace)
{
var normal = planarFace.FaceNormal;
var origin = planarFace.Origin;
var normals = new List<XYZ>(naos.Keys);
var i = normals.FindIndex(
delegate(XYZ v) { return XyzParallel(v, normal); });
if (-1 == i)
{
Debug.Print(
"Face at {0} has new normal {1}",
Util.PointString(origin),
Util.PointString(normal));
naos.Add(normal, new List<XYZ>());
naos[normal].Add(origin);
}
else
{
Debug.Print(
"Face at {0} normal {1} matches {2}",
Util.PointString(origin),
Util.PointString(normal),
Util.PointString(normals[i]));
naos[normals[i]].Add(origin);
}
}
}
}
/// <summary>
/// Calculate the maximum distance between
/// the given set of points in the given
/// normal direction.
/// </summary>
/// <param name="pts">Points to compare</param>
/// <param name="normal">Normal direction</param>
/// <returns>Max distance along normal</returns>
private double getMaxDistanceAlongNormal(
List<XYZ> pts,
XYZ normal)
{
int i, j;
var n = pts.Count;
double dmax = 0;
for (i = 0; i < n - 1; ++i)
for (j = i + 1; j < n; ++j)
{
var v = pts[i].Subtract(pts[j]);
var d = v.DotProduct(normal);
if (d > dmax) dmax = d;
}
return dmax;
}
/// <summary>
/// Create a string listing the
/// dimensions from a dictionary
/// of normal vectors with associated
/// face origins.
/// </summary>
/// <param name="naos">Normals and origins</param>
/// <returns>Formatted string of dimensions</returns>
private string getDimensions(
Dictionary<XYZ, List<XYZ>> naos)
{
string s, ret = string.Empty;
foreach (var pair in naos)
{
var normal = pair.Key.Normalize();
var pts = pair.Value;
if (1 == pts.Count)
{
s = string.Format(
"Only one wall face in "
+ "direction {0} found.",
Util.PointString(normal));
}
else
{
var dmax = getMaxDistanceAlongNormal(
pts, normal);
s = string.Format(
"Max wall dimension in "
+ "direction {0} is {1} feet.",
Util.PointString(normal),
Util.RealString(dmax));
}
Debug.WriteLine(s);
ret += $"\n{s}";
}
return ret;
}
private string ProcessWall(Wall wall)
{
var msg = $"Wall <{wall.Name} {wall.Id.IntegerValue}>:";
Debug.WriteLine(msg);
var o = wall.Document.Application.Create.NewGeometryOptions();
var ge = wall.get_Geometry(o);
//GeometryObjectArray objs = ge.Objects; // 2012
IEnumerable<GeometryObject> objs = ge; // 2013
// face normals and origins:
var naos
= new Dictionary<XYZ, List<XYZ>>();
foreach (var obj in objs)
{
var solid = obj as Solid;
if (null != solid) getFaceNaos(naos, solid);
}
return $"{msg}{getDimensions(naos)}\n";
}
#region Geometry
private const double _eps = 1.0e-9;
/// <summary>
/// Check whether two real numbers are equal
/// </summary>
private static bool DoubleEqual(double a, double b)
{
return Math.Abs(a - b) < _eps;
}
/// <summary>
/// Check whether two vectors are parallel
/// </summary>
private static bool XyzParallel(XYZ a, XYZ b)
{
var angle = a.AngleTo(b);
return _eps > angle
|| DoubleEqual(angle, Math.PI);
}
#endregion // Geometry
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
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 EntServer = WebsitePanel.EnterpriseServer;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Portal.ExchangeServer
{
public partial class ExchangeMailboxEmailAddresses : WebsitePanelModuleBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmails();
}
}
private void BindEmails()
{
EntServer.ExchangeEmailAddress[] emails = ES.Services.ExchangeServer.GetMailboxEmailAddresses(
PanelRequest.ItemID, PanelRequest.AccountID);
gvEmails.DataSource = emails;
gvEmails.DataBind();
lblTotal.Text = emails.Length.ToString();
// form title
ExchangeAccount account = ES.Services.ExchangeServer.GetAccount(PanelRequest.ItemID, PanelRequest.AccountID);
chkPmmAllowed.Checked = (account.MailboxManagerActions & MailboxManagerActions.EmailAddresses) > 0;
litDisplayName.Text = account.DisplayName;
//disable buttons if only one e-mail available, it is primary and cannot be deleted
if (gvEmails.Rows.Count == 1)
{
btnDeleteAddresses.Enabled = false;
btnSetAsPrimary.Enabled = false;
}
}
protected void btnAddEmail_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
btnDeleteAddresses.Enabled = true;
btnSetAsPrimary.Enabled = true;
try
{
int result = ES.Services.ExchangeServer.AddMailboxEmailAddress(
PanelRequest.ItemID, PanelRequest.AccountID, email.Email.ToLower());
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
// rebind
BindEmails();
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("EXCHANGE_MAILBOX_ADD_EMAIL", ex);
}
// clear field
email.AccountName = "";
}
protected void btnSetAsPrimary_Click(object sender, EventArgs e)
{
try
{
string email = null;
bool Checked = false;
for (int i = 0; i < gvEmails.Rows.Count; i++)
{
GridViewRow row = gvEmails.Rows[i];
CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect");
if (chkSelect.Checked)
{
Checked = true;
email = gvEmails.DataKeys[i].Value.ToString();
break;
}
}
//check if any e-mail is selected to be primary
if (!Checked)
{
messageBox.ShowWarningMessage("PRIMARY_EMAIL_IS_NOT_CHECKED");
}
if (email == null)
return;
int result = ES.Services.ExchangeServer.SetMailboxPrimaryEmailAddress(
PanelRequest.ItemID, PanelRequest.AccountID, email);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
// rebind
BindEmails();
messageBox.ShowSuccessMessage("EXCHANGE_MAILBOX_SET_DEFAULT_EMAIL");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("EXCHANGE_MAILBOX_SET_DEFAULT_EMAIL", ex);
}
}
protected void btnDeleteAddresses_Click(object sender, EventArgs e)
{
// get selected e-mail addresses
List<string> emails = new List<string>();
bool containsUPN = false;
EntServer.ExchangeEmailAddress[] tmpEmails = ES.Services.ExchangeServer.GetMailboxEmailAddresses( PanelRequest.ItemID, PanelRequest.AccountID);
for (int i = 0; i < gvEmails.Rows.Count; i++)
{
GridViewRow row = gvEmails.Rows[i];
CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect");
if (chkSelect.Checked)
{
emails.Add(gvEmails.DataKeys[i].Value.ToString());
foreach (EntServer.ExchangeEmailAddress tmpEmail in tmpEmails)
{
if (gvEmails.DataKeys[i].Value.ToString() == tmpEmail.EmailAddress)
{
if (tmpEmail.IsUserPrincipalName)
{
containsUPN = true;
break;
}
}
}
}
}
if (emails.Count == 0)
{
messageBox.ShowWarningMessage("DIST_LIST_SELECT_EMAILS_TO_DELETE");
}
try
{
int result = ES.Services.ExchangeServer.DeleteMailboxEmailAddresses(
PanelRequest.ItemID, PanelRequest.AccountID, emails.ToArray());
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
else
{
if (containsUPN)
messageBox.ShowWarningMessage("NOT_ALL_EMAIL_ADDRESSES_DELETED");
}
// rebind
BindEmails();
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("EXCHANGE_MAILBOX_DELETE_EMAILS", ex);
}
}
protected void chkPmmAllowed_CheckedChanged(object sender, EventArgs e)
{
try
{
int result = ES.Services.ExchangeServer.SetMailboxManagerSettings(PanelRequest.ItemID, PanelRequest.AccountID,
chkPmmAllowed.Checked, MailboxManagerActions.EmailAddresses);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
messageBox.ShowSuccessMessage("EXCHANGE_UPDATE_MAILMANAGER");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("EXCHANGE_UPDATE_MAILMANAGER", ex);
}
}
}
}
| |
using System;
using System.Xml.Serialization;
using System.IO;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
namespace Pig
{
public class GameFragment : Fragment
{
private PigLogic pig;
private bool isDualPane;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override void OnActivityCreated(Bundle bundle)
{
base.OnActivityCreated(bundle);
if (bundle == null)
{
pig = new PigLogic();
var image = Activity.FindViewById<ImageView>(Resource.Id.dieImageView);
image.SetImageResource(Resource.Drawable.Die6);
NewGame();
}
else
{
string savedPig = bundle.GetString("Pig");
var pigSerializer = new XmlSerializer(typeof(PigLogic));
pig = (PigLogic)pigSerializer.Deserialize(new StringReader(savedPig));
ResetViews();
}
var startBtn = Activity.FindViewById<Button>(Resource.Id.startGameBtn);
if (startBtn != null)
isDualPane = true;
var rollBtn = Activity.FindViewById<Button>(Resource.Id.rollBtn);
var endBtn = Activity.FindViewById<Button>(Resource.Id.endBtn);
var newGameBtn = Activity.FindViewById<Button>(Resource.Id.newGameBtn);
rollBtn.Click += RollButtonClick;
endBtn.Click += EndTurnButtonClick;
newGameBtn.Click += NewGameButton_Click;
}
private void RollButtonClick(object sender, EventArgs e)
{
pig.Roll();
SetDieImage();
if (pig.RollScore == 0)
{
((Button)sender).Enabled = false;
pig.CanContinue = false;
}
var scoreView = Activity.FindViewById<TextView>(Resource.Id.currentScore);
scoreView.Text = pig.RollScore.ToString();
}
private void EndTurnButtonClick(object sender, EventArgs e)
{
if (pig.PlayerOneTurn)
{
pig.PlayerOneScore += pig.RollScore;
var pOneScore = Activity.FindViewById<TextView>(Resource.Id.playerOneScore);
pOneScore.Text = pig.PlayerOneScore.ToString();
}
else
{
pig.PlayerTwoScore += pig.RollScore;
var pTwoScore = Activity.FindViewById<TextView>(Resource.Id.playerTwoScore);
pTwoScore.Text = pig.PlayerTwoScore.ToString();
}
if (pig.IsWinner())
{
var turnView = Activity.FindViewById<TextView>(Resource.Id.turnText);
turnView.Text = pig.Winner + " Wins!";
DisableButtons();
}
else
{
pig.NextPlayer();
var turnView = Activity.FindViewById<TextView>(Resource.Id.turnText);
if (pig.PlayerOneTurn)
turnView.Text = string.Format("{0}'s turn", pig.PlayerOneName);
else
turnView.Text = string.Format("{0}'s turn", pig.PlayerTwoName);
var scoreView = Activity.FindViewById<TextView>(Resource.Id.currentScore);
scoreView.Text = "0";
EnableButtons();
}
}
private void DisableButtons()
{
var rollBtn = Activity.FindViewById<Button>(Resource.Id.rollBtn);
var endBtn = Activity.FindViewById<Button>(Resource.Id.endBtn);
rollBtn.Enabled = false;
endBtn.Enabled = false;
}
private void EnableButtons()
{
var rollBtn = Activity.FindViewById<Button>(Resource.Id.rollBtn);
var endBtn = Activity.FindViewById<Button>(Resource.Id.endBtn);
var newGameBtn = Activity.FindViewById<Button>(Resource.Id.newGameBtn);
rollBtn.Enabled = true;
endBtn.Enabled = true;
newGameBtn.Enabled = true;
}
private void ResetViews()
{
var turnView = Activity.FindViewById<TextView>(Resource.Id.turnText);
var scoreView = Activity.FindViewById<TextView>(Resource.Id.currentScore);
var pOneScore = Activity.FindViewById<TextView>(Resource.Id.playerOneScore);
var pTwoScore = Activity.FindViewById<TextView>(Resource.Id.playerTwoScore);
var playerOneNameView = Activity.FindViewById<TextView>(Resource.Id.playerOneTxtView);
var playerTwoNameView = Activity.FindViewById<TextView>(Resource.Id.playerTwoTxtView);
var rollBtn = Activity.FindViewById<Button>(Resource.Id.rollBtn);
scoreView.Text = pig.RollScore.ToString();
pOneScore.Text = pig.PlayerOneScore.ToString();
pTwoScore.Text = pig.PlayerTwoScore.ToString();
playerOneNameView.Text = pig.PlayerOneName;
playerTwoNameView.Text = pig.PlayerTwoName;
if (pig.PlayerOneTurn)
turnView.Text = string.Format("{0}'s turn", pig.PlayerOneName);
else
turnView.Text = string.Format("{0}'s turn", pig.PlayerTwoName);
if (!pig.CanContinue)
rollBtn.Enabled = false;
SetDieImage();
}
private void NewGameButton_Click(object sender, EventArgs e)
{
pig.Reset();
if (isDualPane)
{
var startBtn = Activity.FindViewById<Button>(Resource.Id.startGameBtn);
var rollBtn = Activity.FindViewById<Button>(Resource.Id.rollBtn);
var endBtn = Activity.FindViewById<Button>(Resource.Id.endBtn);
var newGameBtn = Activity.FindViewById<Button>(Resource.Id.newGameBtn);
startBtn.Enabled = true;
rollBtn.Enabled = false;
endBtn.Enabled = false;
newGameBtn.Enabled = false;
}
else
{
var menu = new Intent(Activity, typeof(MainActivity));
StartActivity(menu);
}
}
public void NewGame()
{
if (!isDualPane)
{
pig.PlayerOneName = Activity.Intent.GetStringExtra("Player1") ?? "Player 1";
pig.PlayerTwoName = Activity.Intent.GetStringExtra("Player2") ?? "Player 2";
}
else
{
var playerOneNameBox = Activity.FindViewById<EditText>(Resource.Id.pOneNameTxtBox);
var playerTwoNameBox = Activity.FindViewById<EditText>(Resource.Id.pTwoNameTxtBox);
pig.PlayerOneName = playerOneNameBox.Text;
pig.PlayerTwoName = playerTwoNameBox.Text;
EnableButtons();
}
ResetViews();
}
private void SetDieImage()
{
var image = Activity.FindViewById<ImageView>(Resource.Id.dieImageView);
switch (pig.CurrentRoll)
{
case 1:
image.SetImageResource(Resource.Drawable.Die1);
break;
case 2:
image.SetImageResource(Resource.Drawable.Die2);
break;
case 3:
image.SetImageResource(Resource.Drawable.Die3);
break;
case 4:
image.SetImageResource(Resource.Drawable.Die4);
break;
case 5:
image.SetImageResource(Resource.Drawable.Die5);
break;
case 6:
default:
image.SetImageResource(Resource.Drawable.Die6);
break;
}
}
public override void OnSaveInstanceState(Bundle outState)
{
var sw = new StringWriter();
var pigSerializer = new XmlSerializer(typeof(PigLogic));
pigSerializer.Serialize(sw, pig);
var xml = sw.ToString();
outState.PutString("Pig", xml);
base.OnSaveInstanceState(outState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
return inflater.Inflate(Resource.Layout.GameFrag, container, false);
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComUtils.Admin.DS
{
public class Sys_UserToRoleDS
{
public Sys_UserToRoleDS()
{
}
private const string THIS = "PCSComUtils.Admin.DS.DS.Sys_UserToRoleDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to Sys_UserToRole
/// </Description>
/// <Inputs>
/// Sys_UserToRoleVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, January 06, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
Sys_UserToRoleVO objObject = (Sys_UserToRoleVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO Sys_UserToRole("
+ Sys_UserToRoleTable.USERID_FLD + ","
+ Sys_UserToRoleTable.ROLEID_FLD + ")"
+ "VALUES(?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserToRoleTable.USERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[Sys_UserToRoleTable.USERID_FLD].Value = objObject.UserID;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserToRoleTable.ROLEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[Sys_UserToRoleTable.ROLEID_FLD].Value = objObject.RoleID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from Sys_UserToRole
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + Sys_UserToRoleTable.TABLE_NAME + " WHERE " + "id" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from Sys_UserToRole
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// Sys_UserToRoleVO
/// </Outputs>
/// <Returns>
/// Sys_UserToRoleVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, January 06, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ Sys_UserToRoleTable.ID_FLD + ","
+ Sys_UserToRoleTable.USERID_FLD + ","
+ Sys_UserToRoleTable.ROLEID_FLD
+ " FROM " + Sys_UserToRoleTable.TABLE_NAME
+" WHERE " + Sys_UserToRoleTable.ID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
Sys_UserToRoleVO objObject = new Sys_UserToRoleVO();
while (odrPCS.Read())
{
objObject.id = int.Parse(odrPCS[Sys_UserToRoleTable.ID_FLD].ToString());
objObject.UserID = int.Parse(odrPCS[Sys_UserToRoleTable.USERID_FLD].ToString());
objObject.RoleID = int.Parse(odrPCS[Sys_UserToRoleTable.ROLEID_FLD].ToString());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to Sys_UserToRole
/// </Description>
/// <Inputs>
/// Sys_UserToRoleVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
Sys_UserToRoleVO objObject = (Sys_UserToRoleVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE Sys_UserToRole SET "
+ Sys_UserToRoleTable.USERID_FLD + "= ?" + ","
+ Sys_UserToRoleTable.ROLEID_FLD + "= ?"
+" WHERE " + Sys_UserToRoleTable.ID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserToRoleTable.USERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[Sys_UserToRoleTable.USERID_FLD].Value = objObject.UserID;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserToRoleTable.ROLEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[Sys_UserToRoleTable.ROLEID_FLD].Value = objObject.RoleID;
ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserToRoleTable.ID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[Sys_UserToRoleTable.ID_FLD].Value = objObject.id;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from Sys_UserToRole
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, January 06, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ Sys_UserToRoleTable.ID_FLD + ","
+ Sys_UserToRoleTable.USERID_FLD + ","
+ Sys_UserToRoleTable.ROLEID_FLD
+ " FROM " + Sys_UserToRoleTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,Sys_UserToRoleTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from Sys_UserToRole
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, January 06, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet ListRoleToUser(int pintUserId)
{
const string METHOD_NAME = THIS + ".ListRoleToUser()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ Sys_UserToRoleTable.ID_FLD + ","
+ Sys_UserToRoleTable.USERID_FLD + ","
+ Sys_UserToRoleTable.ROLEID_FLD
+ " FROM " + Sys_UserToRoleTable.TABLE_NAME
+ " WHERE " + Sys_UserToRoleTable.USERID_FLD + "=" + pintUserId;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,Sys_UserToRoleTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from Sys_UserToRole
/// </Description>
/// <Inputs>
/// UserID
/// </Inputs>
/// <Outputs>
/// ArrayList
/// </Outputs>
/// <Returns>
/// ArrayList
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 06-Apr-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public ArrayList ListRoleByUser(int pintUserId)
{
const string METHOD_NAME = THIS + ".ListRoleByUser()";
ArrayList arrData = new ArrayList();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
OleDbDataReader odrPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ Sys_UserToRoleTable.ID_FLD + ","
+ Sys_UserToRoleTable.USERID_FLD + ","
+ Sys_UserToRoleTable.ROLEID_FLD
+ " FROM " + Sys_UserToRoleTable.TABLE_NAME
+ " WHERE " + Sys_UserToRoleTable.USERID_FLD + "=" + pintUserId;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
while (odrPCS.Read())
{
arrData.Add(int.Parse(odrPCS[Sys_UserToRoleTable.ROLEID_FLD].ToString()));
}
arrData.TrimToSize();
return arrData;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, January 06, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ Sys_UserToRoleTable.ID_FLD + ","
+ Sys_UserToRoleTable.USERID_FLD + ","
+ Sys_UserToRoleTable.ROLEID_FLD
+ " FROM " + Sys_UserToRoleTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,Sys_UserToRoleTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// Get the highest ID from table sys_usertorole
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int GetMaxID()
{
const string METHOD_NAME = THIS + ".GetMaxID()";
string strSql = String.Empty;
strSql= "SELECT isnull(max(Id),1) FROM " + Sys_UserToRoleTable.TABLE_NAME ;
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
return (int.Parse(ocmdPCS.ExecuteScalar().ToString()));
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleDiagram.SampleDiagramPublic
File: StrategiesRegistry.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Designer
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Serialization;
using StockSharp.Localization;
using StockSharp.Logging;
using StockSharp.Xaml.Diagram;
using ConfigurationExtensions = StockSharp.Configuration.Extensions;
public enum ElementTypes
{
Composition,
Strategy
}
public class StrategiesRegistry : BaseLogReceiver
{
private readonly string _compositionsPath;
private readonly SynchronizedList<DiagramElement> _strategies = new SynchronizedList<DiagramElement>();
private readonly XmlSerializer<SettingsStorage> _serializer = new XmlSerializer<SettingsStorage>();
private readonly CompositionRegistry _compositionRegistry;
private readonly string _strategiesPath;
public INotifyList<DiagramElement> Strategies => _strategies;
public INotifyList<DiagramElement> Compositions => _compositionRegistry.DiagramElements;
public INotifyList<DiagramElement> DiagramElements => _compositionRegistry.DiagramElements;
public StrategiesRegistry(string compositionsPath = "Compositions", string strategiesPath = "Strategies")
{
if (compositionsPath == null)
throw new ArgumentNullException(nameof(compositionsPath));
if (strategiesPath == null)
throw new ArgumentNullException(nameof(strategiesPath));
_compositionRegistry = new CompositionRegistry();
_compositionsPath = Path.GetFullPath(compositionsPath);
_strategiesPath = Path.GetFullPath(strategiesPath);
}
public void Init()
{
LoadElements();
LoadStrategies();
}
public void Save(CompositionItem element)
{
Save(element.Element, element.Type == CompositionType.Composition);
}
public void Save(CompositionDiagramElement element, bool isComposition)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (!isComposition)
{
if (!_strategies.Contains(element))
_strategies.Add(element);
}
else
DiagramElements.Add(element);
var path = isComposition ? _compositionsPath : _strategiesPath;
var settings = _compositionRegistry.Serialize(element);
var file = Path.Combine(path, element.GetFileName());
CultureInfo.InvariantCulture.DoInCulture(() => _serializer.Serialize(settings, file));
}
public void Remove(CompositionItem element)
{
Remove(element.Element, element.Type == CompositionType.Composition);
}
public void Remove(CompositionDiagramElement element, bool isComposition)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (isComposition)
{
_compositionRegistry.TryRemove(element);
}
else
_strategies.Remove(element);
var path = isComposition ? _compositionsPath : _strategiesPath;
var file = Path.Combine(path, element.GetFileName());
if (File.Exists(file))
File.Delete(file);
}
public void Discard(CompositionItem element)
{
Discard(element.Element, element.Type == CompositionType.Composition);
}
public void Discard(CompositionDiagramElement element, bool isComposition)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
var path = isComposition ? _compositionsPath : _strategiesPath;
var file = Path.Combine(path, element.GetFileName());
var settings = CultureInfo.InvariantCulture.DoInCulture(() => _serializer.Deserialize(file));
_compositionRegistry.Load(element, settings);
}
public void Reload(CompositionItem element)
{
Reload(element.Element, element.Type == CompositionType.Composition);
}
public void Reload(CompositionDiagramElement element, bool isComposition)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
var settings = _compositionRegistry.Serialize(element);
_compositionRegistry.Load(element, settings);
}
public CompositionDiagramElement Clone(CompositionDiagramElement element)
{
var settings = _compositionRegistry.Serialize(element);
var clone = _compositionRegistry.Deserialize(settings);
return clone;
}
private void LoadElements()
{
foreach (var element in ConfigurationExtensions.GetDiagramElements())
_compositionRegistry.DiagramElements.Add(element);
if (!Directory.Exists(_compositionsPath))
Directory.CreateDirectory(_compositionsPath);
var files = Directory.GetFiles(_compositionsPath, "*.xml");
var compositions = GetSchemas("composition_");
foreach (var file in files)
{
try
{
var settings = CultureInfo.InvariantCulture.DoInCulture(() => _serializer.Deserialize(file));
var element = _compositionRegistry.Deserialize(settings);
_compositionRegistry.DiagramElements.Add(element);
compositions.Remove(element.TypeId);
}
catch (Exception excp)
{
this.AddErrorLog(LocalizedStrings.Str3046Params, file, excp);
}
}
foreach (var pair in compositions)
{
try
{
var settings = CultureInfo.InvariantCulture.DoInCulture(() => _serializer.Deserialize(pair.Value.To<Stream>()));
var element = _compositionRegistry.Deserialize(settings);
Save(element, true);
}
catch (Exception excp)
{
this.AddErrorLog(LocalizedStrings.Str3046Params, pair.Key, excp);
}
}
}
private void LoadStrategies()
{
if (!Directory.Exists(_strategiesPath))
Directory.CreateDirectory(_strategiesPath);
var files = Directory.GetFiles(_strategiesPath, "*.xml");
var strategies = GetSchemas("strategy_");
foreach (var file in files)
{
try
{
var settings = CultureInfo.InvariantCulture.DoInCulture(() => _serializer.Deserialize(file));
var element = _compositionRegistry.Deserialize(settings);
_strategies.Add(element);
strategies.Remove(element.TypeId);
}
catch (Exception excp)
{
this.AddErrorLog(LocalizedStrings.Str3627Params, file, excp);
}
}
foreach (var pair in strategies)
{
try
{
var settings = CultureInfo.InvariantCulture.DoInCulture(() => _serializer.Deserialize(pair.Value.To<Stream>()));
var element = _compositionRegistry.Deserialize(settings);
Save(element, false);
}
catch (Exception excp)
{
this.AddErrorLog(LocalizedStrings.Str3627Params, pair.Key, excp);
}
}
}
private static IDictionary<Guid, string> GetSchemas(string prefix)
{
return Properties
.Resources
.ResourceManager
.GetResourceSet(CultureInfo.CurrentCulture, true, true)
.Cast<System.Collections.DictionaryEntry>()
.Where(i => i.Key.ToString().StartsWith(prefix))
.ToDictionary(pair => ((string)pair.Key).TrimStart(prefix).Replace("_", "-").To<Guid>(), pair => (string)pair.Value);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// X509Utils.cs
//
namespace System.Security.Cryptography.X509Certificates {
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using Microsoft.Win32.SafeHandles;
internal class X509Utils {
private X509Utils () {}
internal static bool IsCertRdnCharString (uint dwValueType) {
return ((dwValueType & CAPI.CERT_RDN_TYPE_MASK) >= CAPI.CERT_RDN_NUMERIC_STRING);
}
// this method maps a cert content type returned from CryptQueryObject
// to a value in the managed X509ContentType enum
internal static X509ContentType MapContentType (uint contentType) {
switch (contentType) {
case CAPI.CERT_QUERY_CONTENT_CERT:
return X509ContentType.Cert;
case CAPI.CERT_QUERY_CONTENT_SERIALIZED_STORE:
return X509ContentType.SerializedStore;
case CAPI.CERT_QUERY_CONTENT_SERIALIZED_CERT:
return X509ContentType.SerializedCert;
case CAPI.CERT_QUERY_CONTENT_PKCS7_SIGNED:
case CAPI.CERT_QUERY_CONTENT_PKCS7_UNSIGNED:
return X509ContentType.Pkcs7;
case CAPI.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED:
return X509ContentType.Authenticode;
case CAPI.CERT_QUERY_CONTENT_PFX:
return X509ContentType.Pkcs12;
default:
return X509ContentType.Unknown;
}
}
// this method maps a X509KeyStorageFlags enum to a combination of crypto API flags
internal static uint MapKeyStorageFlags (X509KeyStorageFlags keyStorageFlags) {
uint dwFlags = 0;
if ((keyStorageFlags & X509KeyStorageFlags.UserKeySet) == X509KeyStorageFlags.UserKeySet)
dwFlags |= CAPI.CRYPT_USER_KEYSET;
else if ((keyStorageFlags & X509KeyStorageFlags.MachineKeySet) == X509KeyStorageFlags.MachineKeySet)
dwFlags |= CAPI.CRYPT_MACHINE_KEYSET;
if ((keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable)
dwFlags |= CAPI.CRYPT_EXPORTABLE;
if ((keyStorageFlags & X509KeyStorageFlags.UserProtected) == X509KeyStorageFlags.UserProtected)
dwFlags |= CAPI.CRYPT_USER_PROTECTED;
return dwFlags;
}
// this method maps X509Store OpenFlags to a combination of crypto API flags
internal static uint MapX509StoreFlags (StoreLocation storeLocation, OpenFlags flags) {
uint dwFlags = 0;
uint openMode = ((uint)flags) & 0x3;
switch (openMode) {
case (uint) OpenFlags.ReadOnly:
dwFlags |= CAPI.CERT_STORE_READONLY_FLAG;
break;
case (uint) OpenFlags.MaxAllowed:
dwFlags |= CAPI.CERT_STORE_MAXIMUM_ALLOWED_FLAG;
break;
}
if ((flags & OpenFlags.OpenExistingOnly) == OpenFlags.OpenExistingOnly)
dwFlags |= CAPI.CERT_STORE_OPEN_EXISTING_FLAG;
if ((flags & OpenFlags.IncludeArchived) == OpenFlags.IncludeArchived)
dwFlags |= CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG;
if (storeLocation == StoreLocation.LocalMachine)
dwFlags |= CAPI.CERT_SYSTEM_STORE_LOCAL_MACHINE;
else if (storeLocation == StoreLocation.CurrentUser)
dwFlags |= CAPI.CERT_SYSTEM_STORE_CURRENT_USER;
return dwFlags;
}
// this method maps an X509NameType to crypto API flags.
internal static uint MapNameType (X509NameType nameType) {
uint type = 0;
switch (nameType) {
case X509NameType.SimpleName:
type = CAPI.CERT_NAME_SIMPLE_DISPLAY_TYPE;
break;
case X509NameType.EmailName:
type = CAPI.CERT_NAME_EMAIL_TYPE;
break;
case X509NameType.UpnName:
type = CAPI.CERT_NAME_UPN_TYPE;
break;
case X509NameType.DnsName:
case X509NameType.DnsFromAlternativeName:
type = CAPI.CERT_NAME_DNS_TYPE;
break;
case X509NameType.UrlName:
type = CAPI.CERT_NAME_URL_TYPE;
break;
default:
throw new ArgumentException(SR.GetString(SR.Argument_InvalidNameType));
}
return type;
}
// this method maps X509RevocationFlag to crypto API flags.
internal static uint MapRevocationFlags (X509RevocationMode revocationMode, X509RevocationFlag revocationFlag) {
uint dwFlags = 0;
if (revocationMode == X509RevocationMode.NoCheck)
return dwFlags;
if (revocationMode == X509RevocationMode.Offline)
dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY;
if (revocationFlag == X509RevocationFlag.EndCertificateOnly)
dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_END_CERT;
else if (revocationFlag == X509RevocationFlag.EntireChain)
dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_CHAIN;
else
dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
return dwFlags;
}
private static readonly char[] hexValues = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
internal static string EncodeHexString (byte[] sArray) {
return EncodeHexString(sArray, 0, (uint) sArray.Length);
}
internal static string EncodeHexString (byte[] sArray, uint start, uint end) {
String result = null;
if (sArray != null) {
char[] hexOrder = new char[(end - start) * 2];
uint digit;
for (uint i = start, j = 0; i < end; i++) {
digit = (uint) ((sArray[i] & 0xf0) >> 4);
hexOrder[j++] = hexValues[digit];
digit = (uint) (sArray[i] & 0x0f);
hexOrder[j++] = hexValues[digit];
}
result = new String(hexOrder);
}
return result;
}
internal static string EncodeHexStringFromInt (byte[] sArray, uint start, uint end) {
String result = null;
if(sArray != null) {
char[] hexOrder = new char[(end - start) * 2];
uint i = end;
uint digit, j=0;
while (i-- > start) {
digit = (uint) (sArray[i] & 0xf0) >> 4;
hexOrder[j++] = hexValues[digit];
digit = (uint) (sArray[i] & 0x0f);
hexOrder[j++] = hexValues[digit];
}
result = new String(hexOrder);
}
return result;
}
internal static byte HexToByte (char val) {
if (val <= '9' && val >= '0')
return (byte) (val - '0');
else if (val >= 'a' && val <= 'f')
return (byte) ((val - 'a') + 10);
else if (val >= 'A' && val <= 'F')
return (byte) ((val - 'A') + 10);
else
return 0xFF;
}
internal static uint AlignedLength (uint length) {
return ((length + (uint) 7) & ((uint) 0xfffffff8));
}
internal static String DiscardWhiteSpaces (string inputBuffer) {
return DiscardWhiteSpaces(inputBuffer, 0, inputBuffer.Length);
}
internal static String DiscardWhiteSpaces (string inputBuffer, int inputOffset, int inputCount) {
int i, iCount = 0;
for (i=0; i<inputCount; i++)
if (Char.IsWhiteSpace(inputBuffer[inputOffset + i])) iCount++;
char[] rgbOut = new char[inputCount - iCount];
iCount = 0;
for (i=0; i<inputCount; i++)
if (!Char.IsWhiteSpace(inputBuffer[inputOffset + i])) {
rgbOut[iCount++] = inputBuffer[inputOffset + i];
}
return new String(rgbOut);
}
internal static byte[] DecodeHexString (string s) {
string hexString = X509Utils.DiscardWhiteSpaces(s);
uint cbHex = (uint) hexString.Length / 2;
byte[] hex = new byte[cbHex];
int i = 0;
for (int index = 0; index < cbHex; index++) {
hex[index] = (byte) ((HexToByte(hexString[i]) << 4) | HexToByte(hexString[i+1]));
i += 2;
}
return hex;
}
internal static int GetHexArraySize (byte[] hex) {
int index = hex.Length;
while (index-- > 0) {
if (hex[index] != 0)
break;
}
return index + 1;
}
#if FEATURE_CORESYSTEM
[SecuritySafeCritical]
#endif
internal static SafeLocalAllocHandle ByteToPtr (byte[] managed) {
SafeLocalAllocHandle pb = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(managed.Length));
Marshal.Copy(managed, 0, pb.DangerousGetHandle(), managed.Length);
return pb;
}
//
// This method copies an unmanaged structure into the address of a managed structure.
// This is useful when the structure is returned to us by Crypto API and its size varies
// following the platform.
//
#if FEATURE_CORESYSTEM
[SecuritySafeCritical]
#endif
internal unsafe static void memcpy (IntPtr source, IntPtr dest, uint size) {
for (uint index = 0; index < size; index++) {
*(byte*) ((long)dest + index) = Marshal.ReadByte(new IntPtr((long)source + index));
}
}
#if FEATURE_CORESYSTEM
[SecuritySafeCritical]
#endif
internal static byte[] PtrToByte (IntPtr unmanaged, uint size) {
byte[] array = new byte[(int) size];
Marshal.Copy(unmanaged, array, 0, array.Length);
return array;
}
internal static unsafe bool MemEqual (byte * pbBuf1, uint cbBuf1, byte * pbBuf2, uint cbBuf2) {
if (cbBuf1 != cbBuf2)
return false;
while (cbBuf1-- > 0) {
if (*pbBuf1++ != *pbBuf2++) {
return false;
}
}
return true;
}
#if FEATURE_CORESYSTEM
[SecuritySafeCritical]
#endif
internal static SafeLocalAllocHandle StringToAnsiPtr (string s) {
byte[] arr = new byte[s.Length + 1];
Encoding.ASCII.GetBytes(s, 0, s.Length, arr, 0);
SafeLocalAllocHandle pb = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(arr.Length));
Marshal.Copy(arr, 0, pb.DangerousGetHandle(), arr.Length);
return pb;
}
#if FEATURE_CORESYSTEM
[SecuritySafeCritical]
#endif
internal static SafeLocalAllocHandle StringToUniPtr (string s) {
byte[] arr = new byte[2 * (s.Length + 1)];
Encoding.Unicode.GetBytes(s, 0, s.Length, arr, 0);
SafeLocalAllocHandle pb = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(arr.Length));
Marshal.Copy(arr, 0, pb.DangerousGetHandle(), arr.Length);
return pb;
}
// this method create a memory store from a certificate collection
#if FEATURE_CORESYSTEM
[SecuritySafeCritical]
#endif
internal static SafeCertStoreHandle ExportToMemoryStore (X509Certificate2Collection collection) {
//
// We need to Assert all StorePermission flags since this is a memory store and we want
// semi-trusted code to be able to export certificates to a memory store.
//
#if !FEATURE_CORESYSTEM
StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);
sp.Assert();
#endif
SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle;
// we always want to use CERT_STORE_ENUM_ARCHIVED_FLAG since we want to preserve the collection in this operation.
// By default, Archived certificates will not be included.
safeCertStoreHandle = CAPI.CertOpenStore(new IntPtr(CAPI.CERT_STORE_PROV_MEMORY),
CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
IntPtr.Zero,
CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG | CAPI.CERT_STORE_CREATE_NEW_FLAG,
null);
if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid)
throw new CryptographicException(Marshal.GetLastWin32Error());
//
// We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get
// applied to the original store. This has a limit of 99 links per cert context however.
//
foreach (X509Certificate2 x509 in collection) {
if (!CAPI.CertAddCertificateLinkToStore(safeCertStoreHandle,
x509.CertContext,
CAPI.CERT_STORE_ADD_ALWAYS,
SafeCertContextHandle.InvalidHandle))
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return safeCertStoreHandle;
}
#if FEATURE_CORESYSTEM
[SecuritySafeCritical]
#endif
internal static uint OidToAlgId (string value) {
SafeLocalAllocHandle pszOid = StringToAnsiPtr(value);
CAPI.CRYPT_OID_INFO pOIDInfo = CAPI.CryptFindOIDInfo(CAPI.CRYPT_OID_INFO_OID_KEY, pszOid, 0);
return pOIDInfo.Algid;
}
#if FEATURE_CORESYSTEM
[SecuritySafeCritical]
#endif
internal static string FindOidInfo(uint keyType, string keyValue, OidGroup oidGroup) {
if (keyValue == null)
throw new ArgumentNullException("keyValue");
if (keyValue.Length == 0)
return null;
SafeLocalAllocHandle pvKey = SafeLocalAllocHandle.InvalidHandle;
try {
switch(keyType) {
case CAPI.CRYPT_OID_INFO_OID_KEY:
pvKey = StringToAnsiPtr(keyValue);
break;
case CAPI.CRYPT_OID_INFO_NAME_KEY:
pvKey = StringToUniPtr(keyValue);
break;
default:
Debug.Assert(false);
break;
}
CAPI.CRYPT_OID_INFO pOidInfo = CAPI.CryptFindOIDInfo(keyType, pvKey, oidGroup);
if (keyType == CAPI.CRYPT_OID_INFO_OID_KEY) {
return pOidInfo.pwszName;
}
else {
return pOidInfo.pszOID;
}
}
finally {
pvKey.Dispose();
}
}
// Try to find OID info within a specific group, and if that doesn't work fall back to all
// groups for compatibility with previous frameworks
internal static string FindOidInfoWithFallback(uint key, string value, OidGroup group) {
string info = FindOidInfo(key, value, group);
// If we couldn't find it in the requested group, then try again in all groups
if (info == null && group != OidGroup.All) {
info = FindOidInfo(key, value, OidGroup.All);
}
return info;
}
//
// verify the passed keyValue is valid as per X.208
//
// The first number must be 0, 1 or 2.
// Enforce all characters are digits and dots.
// Enforce that no dot starts or ends the Oid, and disallow double dots.
// Enforce there is at least one dot separator.
//
internal static void ValidateOidValue (string keyValue) {
if (keyValue == null)
throw new ArgumentNullException("keyValue");
int len = keyValue.Length;
if (len < 2)
goto error;
// should not start with a dot. The first digit must be 0, 1 or 2.
char c = keyValue[0];
if (c != '0' && c != '1' && c != '2')
goto error;
if (keyValue[1] != '.' || keyValue[len - 1] == '.') // should not end in a dot
goto error;
bool hasAtLeastOneDot = false;
for (int i = 1; i < len; i++) {
// ensure every character is either a digit or a dot
if (Char.IsDigit(keyValue[i]))
continue;
if (keyValue[i] != '.' || keyValue[i + 1] == '.') // disallow double dots
goto error;
hasAtLeastOneDot = true;
}
if (hasAtLeastOneDot)
return;
error:
throw new ArgumentException(SR.GetString(SR.Argument_InvalidOidValue));
}
#if FEATURE_CORESYSTEM
[SecurityCritical]
#endif
internal static SafeLocalAllocHandle CopyOidsToUnmanagedMemory (OidCollection oids) {
SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
if (oids == null || oids.Count == 0)
return safeLocalAllocHandle;
// Copy the oid strings to a local list to prevent a security race condition where
// the OidCollection or individual oids can be modified by another thread and
// potentially cause a buffer overflow
List<string> oidStrs = new List<string>();
foreach (Oid oid in oids) {
oidStrs.Add(oid.Value);
}
IntPtr pOid = IntPtr.Zero;
// Needs to be checked to avoid having large sets of oids overflow the sizes and allow
// a potential buffer overflow
checked {
int ptrSize = oidStrs.Count * Marshal.SizeOf(typeof(IntPtr));
int oidSize = 0;
foreach (string oidStr in oidStrs) {
oidSize += (oidStr.Length + 1);
}
safeLocalAllocHandle = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr((uint)ptrSize + (uint)oidSize));
pOid = new IntPtr((long)safeLocalAllocHandle.DangerousGetHandle() + ptrSize);
}
for (int index = 0; index < oidStrs.Count; index++) {
Marshal.WriteIntPtr(new IntPtr((long) safeLocalAllocHandle.DangerousGetHandle() + index * Marshal.SizeOf(typeof(IntPtr))), pOid);
byte[] ansiOid = Encoding.ASCII.GetBytes(oidStrs[index]);
Marshal.Copy(ansiOid, 0, pOid, ansiOid.Length);
pOid = new IntPtr((long)pOid + oidStrs[index].Length + 1);
}
return safeLocalAllocHandle;
}
#if FEATURE_CORESYSTEM
[SecuritySafeCritical]
#endif
internal static X509Certificate2Collection GetCertificates(SafeCertStoreHandle safeCertStoreHandle) {
X509Certificate2Collection collection = new X509Certificate2Collection();
IntPtr pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, IntPtr.Zero);
while (pEnumContext != IntPtr.Zero) {
X509Certificate2 certificate = new X509Certificate2(pEnumContext);
collection.Add(certificate);
pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, pEnumContext);
}
return collection;
}
//
// Verifies whether a certificate is valid for the specified policy.
// S_OK means the certificate is valid for the specified policy.
// S_FALSE means the certificate is invalid for the specified policy.
// Anything else is an error.
//
#if FEATURE_CORESYSTEM
[SecurityCritical]
#endif
internal static unsafe int VerifyCertificate (SafeCertContextHandle pCertContext,
OidCollection applicationPolicy,
OidCollection certificatePolicy,
X509RevocationMode revocationMode,
X509RevocationFlag revocationFlag,
DateTime verificationTime,
TimeSpan timeout,
X509Certificate2Collection extraStore,
IntPtr pszPolicy,
IntPtr pdwErrorStatus) {
if (pCertContext == null || pCertContext.IsInvalid)
throw new ArgumentException("pCertContext");
CAPI.CERT_CHAIN_POLICY_PARA PolicyPara = new CAPI.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_PARA)));
CAPI.CERT_CHAIN_POLICY_STATUS PolicyStatus = new CAPI.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_STATUS)));
// Build the chain.
SafeX509ChainHandle pChainContext = SafeX509ChainHandle.InvalidHandle;
int hr = X509Chain.BuildChain(new IntPtr(CAPI.HCCE_CURRENT_USER),
pCertContext,
extraStore,
applicationPolicy,
certificatePolicy,
revocationMode,
revocationFlag,
verificationTime,
timeout,
ref pChainContext);
if (hr != CAPI.S_OK)
return hr;
// Verify the chain using the specified policy.
if (CAPI.CertVerifyCertificateChainPolicy(pszPolicy, pChainContext, ref PolicyPara, ref PolicyStatus)) {
if (pdwErrorStatus != IntPtr.Zero)
*(uint*) pdwErrorStatus = PolicyStatus.dwError;
if (PolicyStatus.dwError != 0)
return CAPI.S_FALSE;
} else {
// The API failed.
return Marshal.GetHRForLastWin32Error();
}
return CAPI.S_OK;
}
#if FEATURE_CORESYSTEM
[SecurityCritical]
#endif
internal static string GetSystemErrorString (int hr) {
StringBuilder strMessage = new StringBuilder(512);
uint dwErrorCode = CAPI.FormatMessage (CAPI.FORMAT_MESSAGE_FROM_SYSTEM | CAPI.FORMAT_MESSAGE_IGNORE_INSERTS,
IntPtr.Zero,
(uint) hr,
0,
strMessage,
(uint)strMessage.Capacity,
IntPtr.Zero);
if (dwErrorCode != 0)
return strMessage.ToString();
else
return SR.GetString(SR.Unknown_Error);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace TestLibrary
{
public static class Generator
{
internal static Random s_rand = new Random(-55);
internal static int Next()
{
lock (s_rand) return s_rand.Next();
}
internal static double NextDouble()
{
lock (s_rand) return s_rand.NextDouble();
}
public static int GetInt32()
{
int i = Next();
return i;
}
public static short GetInt16()
{
short i = Convert.ToInt16(Next() % (1 + short.MaxValue));
return i;
}
public static byte GetByte()
{
byte i = Convert.ToByte(Next() % (1 + byte.MaxValue));
return i;
}
// returns a non-negative double between 0.0 and 1.0
public static double GetDouble()
{
double i = NextDouble();
return i;
}
// returns a non-negative float between 0.0 and 1.0
public static float GetSingle()
{
float i = Convert.ToSingle(NextDouble());
return i;
}
// returns a valid char that is a letter
public static char GetCharLetter()
{
return GetCharLetter(true);
}
public static char GetCharLetter(bool allowsurrogate)
{
return GetCharLetter(allowsurrogate, true);
}
public static char GetCharLetter(bool allowsurrogate, bool allownoweight)
{
short iVal;
char c = 'a';
int counter;
bool loopCondition = true;
// attempt to randomly find a letter
counter = 100;
do
{
counter--;
iVal = GetInt16();
if (false == allownoweight)
{
throw new NotSupportedException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES");
}
c = Convert.ToChar(iVal);
loopCondition = allowsurrogate ? (!char.IsLetter(c)) : (!char.IsLetter(c) || char.IsSurrogate(c));
}
while (loopCondition && 0 < counter);
if (!char.IsLetter(c))
{
// we tried and failed to get a letter
// Grab an ASCII letter
c = Convert.ToChar(GetInt16() % 26 + 'A');
}
return c;
}
public static char GetCharNumber()
{
return GetCharNumber(true);
}
public static char GetCharNumber(bool allownoweight)
{
char c = '0';
int counter;
short iVal;
bool loopCondition = true;
// attempt to randomly find a number
counter = 100;
do
{
counter--;
iVal = GetInt16();
if (false == allownoweight)
{
throw new InvalidOperationException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES");
}
c = Convert.ToChar(iVal);
loopCondition = !char.IsNumber(c);
}
while (loopCondition && 0 < counter);
if (!char.IsNumber(c))
{
// we tried and failed to get a letter
// Grab an ASCII number
c = Convert.ToChar(GetInt16() % 10 + '0');
}
return c;
}
public static char GetChar()
{
return GetChar(true);
}
public static char GetChar(bool allowsurrogate)
{
return GetChar(allowsurrogate, true);
}
public static char GetChar(bool allowsurrogate, bool allownoweight)
{
short iVal = GetInt16();
char c = (char)(iVal);
if (!char.IsLetter(c))
{
// we tried and failed to get a letter
// Just grab an ASCII letter
c = (char)(GetInt16() % 26 + 'A');
}
return c;
}
public static string GetString(bool validPath, int minLength, int maxLength)
{
return GetString(validPath, true, true, minLength, maxLength);
}
public static string GetString(bool validPath, bool allowNulls, bool allowNoWeight, int minLength, int maxLength)
{
StringBuilder sVal = new StringBuilder();
char c;
int length;
if (0 == minLength && 0 == maxLength) return string.Empty;
if (minLength > maxLength) return null;
length = minLength;
if (minLength != maxLength)
{
length = (GetInt32() % (maxLength - minLength)) + minLength;
}
for (int i = 0; length > i; i++)
{
if (validPath)
{
if (0 == (GetByte() % 2))
{
c = GetCharLetter(true, allowNoWeight);
}
else
{
c = GetCharNumber(allowNoWeight);
}
}
else if (!allowNulls)
{
do
{
c = GetChar(true, allowNoWeight);
} while (c == '\u0000');
}
else
{
c = GetChar(true, allowNoWeight);
}
sVal.Append(c);
}
string s = sVal.ToString();
return s;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
namespace Faithlife.Utility
{
/// <summary>
/// Encapsulates a length of characters from a string starting at a particular offset.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1036:OverrideMethodsOnComparableTypes", Justification = "String does not support comparison operators.")]
[StructLayout(LayoutKind.Auto)]
public readonly struct StringSegment :
IEnumerable<char>,
IEquatable<StringSegment>,
IComparable<StringSegment>
{
/// <summary>
/// Initializes a new instance of the <see cref="StringSegment"/> class.
/// </summary>
/// <param name="source">The source string.</param>
/// <remarks>Creates a segment that represents the entire source string.</remarks>
public StringSegment(string? source)
: this(source, 0, source?.Length ?? 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StringSegment"/> class.
/// </summary>
/// <param name="source">The source string.</param>
/// <param name="offset">The offset of the segment.</param>
/// <remarks>Creates a segment that starts at the specified offset and continues to the end
/// of the source string.</remarks>
/// <exception cref="ArgumentOutOfRangeException">The offset is out of range.</exception>
public StringSegment(string? source, int offset)
: this(source, offset, (source?.Length ?? 0) - offset)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StringSegment"/> class.
/// </summary>
/// <param name="source">The source string.</param>
/// <param name="offset">The offset of the segment.</param>
/// <param name="length">The length of the segment.</param>
/// <exception cref="ArgumentOutOfRangeException">The offset or length are out of range.</exception>
public StringSegment(string? source, int offset, int length)
{
var stringLength = source?.Length ?? 0;
if (offset < 0 || offset > stringLength)
throw new ArgumentOutOfRangeException(nameof(offset));
if (length < 0 || offset + length > stringLength)
throw new ArgumentOutOfRangeException(nameof(length));
Source = source ?? "";
Offset = offset;
Length = length;
}
/// <summary>
/// Initializes a new instance of the <see cref="StringSegment"/> class.
/// </summary>
/// <param name="source">The source string.</param>
/// <param name="capture">The <see cref="Capture" /> to represent.</param>
public StringSegment(string source, Capture capture)
: this(source, capture?.Index ?? 0, capture?.Length ?? 0)
{
}
/// <summary>
/// An empty segment of the empty string.
/// </summary>
public static readonly StringSegment Empty = new StringSegment("");
/// <summary>
/// Gets the source string.
/// </summary>
/// <value>The source string of the segment.</value>
public string Source { get; }
/// <summary>
/// Gets the offset into the source string.
/// </summary>
/// <value>The offset into the source string of the segment.</value>
public int Offset { get; }
/// <summary>
/// Gets the length of the segment.
/// </summary>
/// <value>The length of the segment.</value>
public int Length { get; }
/// <summary>
/// Gets the <see cref="char"/> with the specified index.
/// </summary>
/// <value>The character at the specified index.</value>
[IndexerName("Chars")]
public char this[int index]
{
get
{
if (index < 0 || index >= Length)
throw new ArgumentOutOfRangeException(nameof(index));
return Source[Offset + index];
}
}
/// <summary>
/// Returns everything that follows this segment in the source string.
/// </summary>
/// <returns>Everything that follows this segment in the source string.</returns>
public StringSegment After() => new StringSegment(Source, Offset + Length, Source.Length - (Offset + Length));
/// <summary>
/// Appends the segment to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="stringBuilder">The <see cref="StringBuilder" />.</param>
public void AppendToStringBuilder(StringBuilder stringBuilder)
{
if (stringBuilder is null)
throw new ArgumentNullException(nameof(stringBuilder));
stringBuilder.Append(Source, Offset, Length);
}
/// <summary>
/// Returns everything that precedes this segment in the source string.
/// </summary>
/// <returns>Everything that precedes this segment in the source string.</returns>
public StringSegment Before() => new StringSegment(Source, 0, Offset);
/// <summary>
/// Compares two string segments.
/// </summary>
/// <param name="segmentA">The first segment.</param>
/// <param name="segmentB">The second segment.</param>
/// <param name="comparison">The string comparison options.</param>
/// <returns>Zero, a positive integer, or a negative integer, if the first segment is
/// equal to, greater than, or less than the second segment, respectively.</returns>
public static int Compare(StringSegment segmentA, StringSegment segmentB, StringComparison comparison)
{
var result = string.Compare(segmentA.Source, segmentA.Offset, segmentB.Source, segmentB.Offset, Math.Min(segmentA.Length, segmentB.Length), comparison);
return CompareHelper(result, segmentA, segmentB);
}
/// <summary>
/// Compares two string segments ordinally.
/// </summary>
/// <param name="segmentA">The first segment.</param>
/// <param name="segmentB">The second segment.</param>
/// <returns>Zero, a positive integer, or a negative integer, if the first segment is
/// equal to, greater than, or less than the second segment, respectively.</returns>
public static int CompareOrdinal(StringSegment segmentA, StringSegment segmentB)
{
var result = string.CompareOrdinal(segmentA.Source, segmentA.Offset, segmentB.Source, segmentB.Offset, Math.Min(segmentA.Length, segmentB.Length));
return CompareHelper(result, segmentA, segmentB);
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>Zero, a positive integer, or a negative integer, if the first segment is
/// equal to, greater than, or less than the second segment, respectively.</returns>
public int CompareTo(StringSegment other)
=> CultureInfo.CurrentCulture.CompareInfo.Compare(Source, Offset, Length, other.Source, other.Offset, other.Length, CompareOptions.None);
/// <summary>
/// Copies the characters of the string segment to an array.
/// </summary>
/// <param name="sourceIndex">The first character in the segment to copy.</param>
/// <param name="destination">The destination array.</param>
/// <param name="destinationIndex">The first index in the destination array.</param>
/// <param name="count">The number of characters to copy.</param>
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
=> Source.CopyTo(Offset + sourceIndex, destination, destinationIndex, count);
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns>true if obj and this instance are the same type and represent the same value; otherwise, false.</returns>
public override bool Equals(object? obj) => obj is StringSegment && Equals((StringSegment) obj);
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>true if the current object is equal to the other parameter; otherwise, false.</returns>
public bool Equals(StringSegment other)
{
if (Length != other.Length)
return false;
if (ReferenceEquals(Source, other.Source) && Offset == other.Offset)
return true;
return CompareOrdinal(this, other) == 0;
}
/// <summary>
/// Returns an enumerator that iterates through the characters of the string segment.
/// </summary>
/// <returns>A <see cref="IEnumerator{T}"></see> that can be used to
/// iterate through the characters of the string segment.</returns>
public IEnumerator<char> GetEnumerator()
{
for (var index = 0; index < Length; index++)
yield return Source[Offset + index];
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A 32-bit signed integer that is the hash code for this instance.</returns>
/// <remarks>This hash code is identical to the hash code that results from
/// calling <c>GetHashCode</c> on the result of <c>ToString</c>.</remarks>
#if NETSTANDARD2_0
public override int GetHashCode() => ToString().GetHashCode();
#else
public override int GetHashCode() => ToString().GetHashCode(StringComparison.Ordinal);
#endif
/// <summary>
/// Returns the first index of the specified character in the string segment.
/// </summary>
/// <param name="value">The character to find.</param>
/// <returns>The first index of the specified character in the string segment,
/// or -1 if the character cannot be found.</returns>
public int IndexOf(char value)
{
var index = Source.IndexOf(value, Offset, Length);
return index < 0 ? index : index - Offset;
}
/// <summary>
/// Returns the first index of the specified character in the string segment.
/// </summary>
/// <param name="value">The character to find.</param>
/// <param name="startIndex">The search starting position.</param>
/// <returns>The first index of the specified character in the string segment,
/// or -1 if the character cannot be found.</returns>
public int IndexOf(char value, int startIndex)
{
if (startIndex < 0 || startIndex >= Length)
throw new ArgumentOutOfRangeException(nameof(startIndex));
var index = Source.IndexOf(value, Offset + startIndex, Length - startIndex);
return index < 0 ? index : index - Offset;
}
/// <summary>
/// Returns the first index of the specified string in the string segment.
/// </summary>
/// <param name="value">The string to find.</param>
/// <param name="sc">The string comparison options.</param>
/// <returns>The first index of the specified string in the string segment,
/// or -1 if the string cannot be found.</returns>
public int IndexOf(string value, StringComparison sc)
{
var index = Source.IndexOf(value, Offset, Length, sc);
return index < 0 ? index : index - Offset;
}
/// <summary>
/// Returns the first index of any of the specified characters in the string segment.
/// </summary>
/// <param name="anyOf">The characters to find.</param>
/// <returns>The first index of any of the specified characters in the string segment,
/// or -1 if none of the characters cannot be found.</returns>
public int IndexOfAny(params char[] anyOf)
{
var index = Source.IndexOfAny(anyOf, Offset, Length);
return index < 0 ? index : index - Offset;
}
/// <summary>
/// Intersects this segment with another segment of the same string.
/// </summary>
/// <param name="segment">The segment to intersect.</param>
/// <returns>A string segment that encapsulates the portion of the string
/// contained by both string segments.</returns>
/// <remarks>If the segments do not intersect, the segment will have a length
/// of zero, but will be positioned at the offset of the end-most substring.</remarks>
public StringSegment Intersect(StringSegment segment)
{
if (Source != segment.Source)
throw new ArgumentException("The specified segment is from a different string.", nameof(segment));
if (segment.Offset >= Offset + Length)
return Redirect(segment.Offset, 0);
if (segment.Offset >= Offset)
return Redirect(segment.Offset, Math.Min(segment.Length, Offset + Length - segment.Offset));
if (Offset >= segment.Offset + segment.Length)
return Redirect(Offset, 0);
return Redirect(Offset, Math.Min(Length, segment.Offset + segment.Length - Offset));
}
/// <summary>
/// Returns the last index of the specified character in the string segment.
/// </summary>
/// <param name="value">The character to find.</param>
/// <returns>The last index of the specified character in the string segment,
/// or -1 if the character cannot be found.</returns>
public int LastIndexOf(char value)
{
var index = Source.LastIndexOf(value, Offset + Length - 1, Length);
return index < 0 ? index : index - Offset;
}
/// <summary>
/// Returns the last index of the specified string in the string segment.
/// </summary>
/// <param name="value">The string to find.</param>
/// <param name="comparison">The string comparison options.</param>
/// <returns>The last index of the specified string in the string segment,
/// or -1 if the string cannot be found.</returns>
public int LastIndexOf(string value, StringComparison comparison)
{
var index = Source.LastIndexOf(value, Offset + Length - 1, Length, comparison);
return index < 0 ? index : index - Offset;
}
/// <summary>
/// Returns the last index of any of the specified characters in the string segment.
/// </summary>
/// <param name="anyOf">The characters to find.</param>
/// <returns>The last index of any of the specified characters in the string segment,
/// or -1 if none of the characters cannot be found.</returns>
public int LastIndexOfAny(params char[] anyOf)
{
var index = Source.LastIndexOfAny(anyOf, Offset + Length - 1, Length);
return index < 0 ? index : index - Offset;
}
/// <summary>
/// Matches the specified regex against the segment.
/// </summary>
/// <param name="regex">The regex to match.</param>
/// <returns>The result of calling <c>regex.Match</c> on the segment.</returns>
public Match Match(Regex regex)
{
if (regex is null)
throw new ArgumentNullException(nameof(regex));
return regex.Match(Source, Offset, Length);
}
/// <summary>
/// Returns a new <see cref="StringSegment"/> with the same owner string.
/// </summary>
/// <param name="offset">Offset of the new string segment.</param>
/// <returns>A new segment with the same owner string.</returns>
public StringSegment Redirect(int offset) =>
new StringSegment(Source, offset, Source.Length - offset);
/// <summary>
/// Returns a new <see cref="StringSegment"/> with the same owner string.
/// </summary>
/// <param name="offset">Offset of the new string segment.</param>
/// <param name="length">Length of the new string segment.</param>
/// <returns>A new segment with the same owner string.</returns>
public StringSegment Redirect(int offset, int length) =>
new StringSegment(Source, offset, length);
/// <summary>
/// Returns a new <see cref="StringSegment"/> with the same owner string.
/// </summary>
/// <param name="capture">The <see cref="Capture" /> to represent.</param>
/// <returns>A new segment with the same owner string.</returns>
public StringSegment Redirect(Capture capture)
{
if (capture is null)
throw new ArgumentNullException(nameof(capture));
return new StringSegment(Source, capture.Index, capture.Length);
}
/// <summary>
/// Splits the string segment by the specified regular expression.
/// </summary>
/// <param name="regex">The regular expression.</param>
/// <returns>A collection of string segments corresponding to the split.
/// Consult the <c>Split</c> method of the <c>Regex</c> class
/// for more information.</returns>
public IEnumerable<StringSegment> Split(Regex regex)
{
// find first match
var match = Match(regex);
if (!match.Success)
{
// match not found, so yield this and we're done
yield return this;
yield break;
}
// ensure not right-to-left
if (!regex.RightToLeft)
{
// loop through matches
var resultOffset = Offset;
do
{
// yield segment before match
yield return Redirect(resultOffset, match.Index - resultOffset);
resultOffset = match.Index + match.Length;
// yield captures
var groups = match.Groups;
for (var nGroup = 1; nGroup < groups.Count; nGroup++)
{
var group = groups[nGroup];
if (group.Success)
yield return Redirect(group);
}
// next match
match = match.NextMatch();
}
while (match.Success);
// yield segment after last match
yield return Redirect(resultOffset, Offset + Length - resultOffset);
}
else
{
// loop through matches right to left
var resultOffset = Offset + Length;
do
{
// yield segment before match
yield return Redirect(match.Index + match.Length, resultOffset - (match.Index + match.Length));
resultOffset = match.Index;
// yield captures
var groups = match.Groups;
for (var index = 1; index < groups.Count; index++)
{
var group = groups[index];
if (group.Success)
yield return Redirect(group);
}
// next match
match = match.NextMatch();
}
while (match.Success);
// yield segment after last match
yield return Redirect(Offset, resultOffset - Offset);
}
}
/// <summary>
/// Returns a sub-segment of this segment.
/// </summary>
/// <param name="index">The start index into this segment.</param>
/// <returns>A sub-segment of this segment</returns>
public StringSegment Substring(int index) => Redirect(Offset + index, Length - index);
/// <summary>
/// Returns a sub-segment of this segment.
/// </summary>
/// <param name="index">The start index into this segment.</param>
/// <param name="length">The length of the sub-segment.</param>
/// <returns>A sub-segment of this segment</returns>
public StringSegment Substring(int index, int length) => Redirect(Offset + index, length);
/// <summary>
/// Trims the whitespace from the start and end of the string segment.
/// </summary>
/// <returns>A string segment with the whitespace trimmed.</returns>
public StringSegment Trim() => TrimHelper(c_trimTypeBoth);
/// <summary>
/// Trims the specified characters from the start and end of the string segment.
/// </summary>
/// <param name="characters">The characters to trim.</param>
/// <returns>A string segment with the whitespace trimmed.</returns>
public StringSegment Trim(params char[] characters) => TrimHelper(characters, c_trimTypeBoth);
/// <summary>
/// Trims the specified characters from the end of the string segment.
/// </summary>
/// <returns>A string segment with the whitespace trimmed.</returns>
public StringSegment TrimEnd() => TrimHelper(c_trimTypeEnd);
/// <summary>
/// Trims the whitespace from the end of the string segment.
/// </summary>
/// <param name="characters">The characters to trim.</param>
/// <returns>A string segment with the whitespace trimmed.</returns>
public StringSegment TrimEnd(params char[] characters) => TrimHelper(characters, c_trimTypeEnd);
/// <summary>
/// Trims the specified characters from the start of the string segment.
/// </summary>
/// <returns>A string segment with the whitespace trimmed.</returns>
public StringSegment TrimStart() => TrimHelper(c_trimTypeStart);
/// <summary>
/// Trims the whitespace from the start of the string segment.
/// </summary>
/// <param name="characters">The characters to trim.</param>
/// <returns>A string segment with the whitespace trimmed.</returns>
public StringSegment TrimStart(params char[] characters) => TrimHelper(characters, c_trimTypeStart);
/// <summary>
/// Returns the array of characters represented by this string segment.
/// </summary>
public char[] ToCharArray() => Source.ToCharArray(Offset, Length);
/// <summary>
/// Returns the string segment as a string.
/// </summary>
/// <returns>The string segment as a string.</returns>
public override string ToString() => Source is null ? "" : Source.Substring(Offset, Length);
/// <summary>
/// Returns the string segment as a <see cref="StringBuilder" />.
/// </summary>
/// <returns>The string segment as a <see cref="StringBuilder" />.</returns>
public StringBuilder ToStringBuilder() => new StringBuilder(Source, Offset, Length, 0);
/// <summary>
/// Returns the string segment as a <see cref="StringBuilder"/>.
/// </summary>
/// <param name="capacity">The capacity of the new <see cref="StringBuilder"/>.</param>
/// <returns>The string segment as a <see cref="StringBuilder"/>.</returns>
public StringBuilder ToStringBuilder(int capacity) => new StringBuilder(Source, Offset, Length, capacity);
/// <summary>
/// Returns the union of this segment with another segment of the same string.
/// </summary>
/// <param name="segment">Another segment of the same string.</param>
/// <returns>A string segment that spans both string segments.</returns>
/// <remarks>If the segments do not intersect, the segment will also include any
/// characters between the two segments.</remarks>
public StringSegment Union(StringSegment segment)
{
if (Source != segment.Source)
throw new ArgumentException("The specified segment is from a different string.", nameof(segment));
var start = Math.Min(Offset, segment.Offset);
var end = Math.Max(Offset + Length, segment.Offset + segment.Length);
return Redirect(start, end - start);
}
/// <summary>
/// Compares two string segments for equality.
/// </summary>
/// <param name="segmentA">The first string segment.</param>
/// <param name="segmentB">The second string segment.</param>
/// <returns><c>true</c> if the segments are equal; false otherwise.</returns>
public static bool operator ==(StringSegment segmentA, StringSegment segmentB) => segmentA.Equals(segmentB);
/// <summary>
/// Compares two string segments for inequality.
/// </summary>
/// <param name="segmentA">The first string segment.</param>
/// <param name="segmentB">The second string segment.</param>
/// <returns><c>true</c> if the segments are not equal; false otherwise.</returns>
public static bool operator !=(StringSegment segmentA, StringSegment segmentB) => !segmentA.Equals(segmentB);
/// <summary>
/// Returns an enumerator that iterates through the characters of the string segment.
/// </summary>
/// <returns>An <see cref="IEnumerator"></see> object that can be used to iterate
/// through the characters of the string segment.</returns>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private const int c_trimTypeStart = 0;
private const int c_trimTypeEnd = 1;
private const int c_trimTypeBoth = 2;
private StringSegment TrimHelper(int trimType)
{
var start = Offset;
var end = Offset + Length;
if (trimType != c_trimTypeEnd)
{
while (start < end)
{
if (char.IsWhiteSpace(Source[start]))
start++;
else
break;
}
}
if (trimType != c_trimTypeStart)
{
while (start < end)
{
if (char.IsWhiteSpace(Source[end - 1]))
end--;
else
break;
}
}
return Redirect(start, end - start);
}
private StringSegment TrimHelper(char[] trimChars, int trimType)
{
var start = Offset;
var end = Offset + Length;
if (trimType != c_trimTypeEnd)
{
while (start < end)
{
if (Array.IndexOf(trimChars, Source[start]) >= 0)
start++;
else
break;
}
}
if (trimType != c_trimTypeStart)
{
while (start < end)
{
if (Array.IndexOf(trimChars, Source[end - 1]) >= 0)
end--;
else
break;
}
}
return Redirect(start, end - start);
}
// Compares the string length if the string segments otherwise compare equal
private static int CompareHelper(int result, StringSegment segA, StringSegment segB) => result != 0 ? result : segA.Length.CompareTo(segB.Length);
}
}
| |
// 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.Immutable;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Language.Intellisense;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class GlyphExtensions
{
public static StandardGlyphGroup GetStandardGlyphGroup(this Glyph glyph)
{
switch (glyph)
{
case Glyph.Assembly:
return StandardGlyphGroup.GlyphAssembly;
case Glyph.BasicFile:
case Glyph.BasicProject:
return StandardGlyphGroup.GlyphVBProject;
case Glyph.ClassPublic:
case Glyph.ClassProtected:
case Glyph.ClassPrivate:
case Glyph.ClassInternal:
return StandardGlyphGroup.GlyphGroupClass;
case Glyph.ConstantPublic:
case Glyph.ConstantProtected:
case Glyph.ConstantPrivate:
case Glyph.ConstantInternal:
return StandardGlyphGroup.GlyphGroupConstant;
case Glyph.CSharpFile:
return StandardGlyphGroup.GlyphCSharpFile;
case Glyph.CSharpProject:
return StandardGlyphGroup.GlyphCoolProject;
case Glyph.DelegatePublic:
case Glyph.DelegateProtected:
case Glyph.DelegatePrivate:
case Glyph.DelegateInternal:
return StandardGlyphGroup.GlyphGroupDelegate;
case Glyph.EnumPublic:
case Glyph.EnumProtected:
case Glyph.EnumPrivate:
case Glyph.EnumInternal:
return StandardGlyphGroup.GlyphGroupEnum;
case Glyph.EnumMember:
return StandardGlyphGroup.GlyphGroupEnumMember;
case Glyph.Error:
return StandardGlyphGroup.GlyphGroupError;
case Glyph.ExtensionMethodPublic:
return StandardGlyphGroup.GlyphExtensionMethod;
case Glyph.ExtensionMethodProtected:
return StandardGlyphGroup.GlyphExtensionMethodProtected;
case Glyph.ExtensionMethodPrivate:
return StandardGlyphGroup.GlyphExtensionMethodPrivate;
case Glyph.ExtensionMethodInternal:
return StandardGlyphGroup.GlyphExtensionMethodInternal;
case Glyph.EventPublic:
case Glyph.EventProtected:
case Glyph.EventPrivate:
case Glyph.EventInternal:
return StandardGlyphGroup.GlyphGroupEvent;
case Glyph.FieldPublic:
case Glyph.FieldProtected:
case Glyph.FieldPrivate:
case Glyph.FieldInternal:
return StandardGlyphGroup.GlyphGroupField;
case Glyph.InterfacePublic:
case Glyph.InterfaceProtected:
case Glyph.InterfacePrivate:
case Glyph.InterfaceInternal:
return StandardGlyphGroup.GlyphGroupInterface;
case Glyph.Intrinsic:
return StandardGlyphGroup.GlyphGroupIntrinsic;
case Glyph.Keyword:
return StandardGlyphGroup.GlyphKeyword;
case Glyph.Label:
return StandardGlyphGroup.GlyphGroupIntrinsic;
case Glyph.Local:
return StandardGlyphGroup.GlyphGroupVariable;
case Glyph.Namespace:
return StandardGlyphGroup.GlyphGroupNamespace;
case Glyph.MethodPublic:
case Glyph.MethodProtected:
case Glyph.MethodPrivate:
case Glyph.MethodInternal:
return StandardGlyphGroup.GlyphGroupMethod;
case Glyph.ModulePublic:
case Glyph.ModuleProtected:
case Glyph.ModulePrivate:
case Glyph.ModuleInternal:
return StandardGlyphGroup.GlyphGroupModule;
case Glyph.OpenFolder:
return StandardGlyphGroup.GlyphOpenFolder;
case Glyph.Operator:
return StandardGlyphGroup.GlyphGroupOperator;
case Glyph.Parameter:
return StandardGlyphGroup.GlyphGroupVariable;
case Glyph.PropertyPublic:
case Glyph.PropertyProtected:
case Glyph.PropertyPrivate:
case Glyph.PropertyInternal:
return StandardGlyphGroup.GlyphGroupProperty;
case Glyph.RangeVariable:
return StandardGlyphGroup.GlyphGroupVariable;
case Glyph.Reference:
return StandardGlyphGroup.GlyphReference;
case Glyph.StructurePublic:
case Glyph.StructureProtected:
case Glyph.StructurePrivate:
case Glyph.StructureInternal:
return StandardGlyphGroup.GlyphGroupStruct;
case Glyph.TypeParameter:
return StandardGlyphGroup.GlyphGroupType;
case Glyph.Snippet:
return StandardGlyphGroup.GlyphCSharpExpansion;
case Glyph.CompletionWarning:
return StandardGlyphGroup.GlyphCompletionWarning;
default:
throw new ArgumentException("glyph");
}
}
public static StandardGlyphItem GetStandardGlyphItem(this Glyph icon)
{
switch (icon)
{
case Glyph.ClassProtected:
case Glyph.ConstantProtected:
case Glyph.DelegateProtected:
case Glyph.EnumProtected:
case Glyph.EventProtected:
case Glyph.FieldProtected:
case Glyph.InterfaceProtected:
case Glyph.MethodProtected:
case Glyph.ModuleProtected:
case Glyph.PropertyProtected:
case Glyph.StructureProtected:
return StandardGlyphItem.GlyphItemProtected;
case Glyph.ClassPrivate:
case Glyph.ConstantPrivate:
case Glyph.DelegatePrivate:
case Glyph.EnumPrivate:
case Glyph.EventPrivate:
case Glyph.FieldPrivate:
case Glyph.InterfacePrivate:
case Glyph.MethodPrivate:
case Glyph.ModulePrivate:
case Glyph.PropertyPrivate:
case Glyph.StructurePrivate:
return StandardGlyphItem.GlyphItemPrivate;
case Glyph.ClassInternal:
case Glyph.ConstantInternal:
case Glyph.DelegateInternal:
case Glyph.EnumInternal:
case Glyph.EventInternal:
case Glyph.FieldInternal:
case Glyph.InterfaceInternal:
case Glyph.MethodInternal:
case Glyph.ModuleInternal:
case Glyph.PropertyInternal:
case Glyph.StructureInternal:
return StandardGlyphItem.GlyphItemFriend;
default:
// We don't want any overlays
return StandardGlyphItem.GlyphItemPublic;
}
}
public static ImageSource GetImageSource(this Glyph? glyph, IGlyphService glyphService)
{
return glyph.HasValue ? glyph.Value.GetImageSource(glyphService) : null;
}
public static ImageSource GetImageSource(this Glyph glyph, IGlyphService glyphService)
{
return glyphService.GetGlyph(glyph.GetStandardGlyphGroup(), glyph.GetStandardGlyphItem());
}
public static ImageMoniker GetImageMoniker(this Glyph glyph)
{
switch (glyph)
{
case Glyph.None:
return default(ImageMoniker);
case Glyph.Assembly:
return KnownMonikers.Assembly;
case Glyph.BasicFile:
return KnownMonikers.VBFileNode;
case Glyph.BasicProject:
return KnownMonikers.VBProjectNode;
case Glyph.ClassPublic:
return KnownMonikers.ClassPublic;
case Glyph.ClassProtected:
return KnownMonikers.ClassProtected;
case Glyph.ClassPrivate:
return KnownMonikers.ClassPrivate;
case Glyph.ClassInternal:
return KnownMonikers.ClassInternal;
case Glyph.CSharpFile:
return KnownMonikers.CSFileNode;
case Glyph.CSharpProject:
return KnownMonikers.CSProjectNode;
case Glyph.ConstantPublic:
return KnownMonikers.ConstantPublic;
case Glyph.ConstantProtected:
return KnownMonikers.ConstantProtected;
case Glyph.ConstantPrivate:
return KnownMonikers.ConstantPrivate;
case Glyph.ConstantInternal:
return KnownMonikers.ConstantInternal;
case Glyph.DelegatePublic:
return KnownMonikers.DelegatePublic;
case Glyph.DelegateProtected:
return KnownMonikers.DelegateProtected;
case Glyph.DelegatePrivate:
return KnownMonikers.DelegatePrivate;
case Glyph.DelegateInternal:
return KnownMonikers.DelegateInternal;
case Glyph.EnumPublic:
return KnownMonikers.EnumerationPublic;
case Glyph.EnumProtected:
return KnownMonikers.EnumerationProtected;
case Glyph.EnumPrivate:
return KnownMonikers.EnumerationPrivate;
case Glyph.EnumInternal:
return KnownMonikers.EnumerationInternal;
case Glyph.EnumMember:
return KnownMonikers.EnumerationItemPublic;
case Glyph.Error:
return KnownMonikers.StatusError;
case Glyph.EventPublic:
return KnownMonikers.EventPublic;
case Glyph.EventProtected:
return KnownMonikers.EventProtected;
case Glyph.EventPrivate:
return KnownMonikers.EventPrivate;
case Glyph.EventInternal:
return KnownMonikers.EventInternal;
// Extension methods have the same glyph regardless of accessibility.
case Glyph.ExtensionMethodPublic:
case Glyph.ExtensionMethodProtected:
case Glyph.ExtensionMethodPrivate:
case Glyph.ExtensionMethodInternal:
return KnownMonikers.ExtensionMethod;
case Glyph.FieldPublic:
return KnownMonikers.FieldPublic;
case Glyph.FieldProtected:
return KnownMonikers.FieldProtected;
case Glyph.FieldPrivate:
return KnownMonikers.FieldPrivate;
case Glyph.FieldInternal:
return KnownMonikers.FieldInternal;
case Glyph.InterfacePublic:
return KnownMonikers.InterfacePublic;
case Glyph.InterfaceProtected:
return KnownMonikers.InterfaceProtected;
case Glyph.InterfacePrivate:
return KnownMonikers.InterfacePrivate;
case Glyph.InterfaceInternal:
return KnownMonikers.InterfaceInternal;
// TODO: Figure out the right thing to return here.
case Glyph.Intrinsic:
return KnownMonikers.Type;
case Glyph.Keyword:
return KnownMonikers.IntellisenseKeyword;
case Glyph.Label:
return KnownMonikers.Label;
case Glyph.Parameter:
case Glyph.Local:
return KnownMonikers.LocalVariable;
case Glyph.Namespace:
return KnownMonikers.Namespace;
case Glyph.MethodPublic:
return KnownMonikers.MethodPublic;
case Glyph.MethodProtected:
return KnownMonikers.MethodProtected;
case Glyph.MethodPrivate:
return KnownMonikers.MethodPrivate;
case Glyph.MethodInternal:
return KnownMonikers.MethodInternal;
case Glyph.ModulePublic:
return KnownMonikers.ModulePublic;
case Glyph.ModuleProtected:
return KnownMonikers.ModuleProtected;
case Glyph.ModulePrivate:
return KnownMonikers.ModulePrivate;
case Glyph.ModuleInternal:
return KnownMonikers.ModuleInternal;
case Glyph.OpenFolder:
return KnownMonikers.OpenFolder;
case Glyph.Operator:
return KnownMonikers.Operator;
case Glyph.PropertyPublic:
return KnownMonikers.PropertyPublic;
case Glyph.PropertyProtected:
return KnownMonikers.PropertyProtected;
case Glyph.PropertyPrivate:
return KnownMonikers.PropertyPrivate;
case Glyph.PropertyInternal:
return KnownMonikers.PropertyInternal;
case Glyph.RangeVariable:
return KnownMonikers.FieldPublic;
case Glyph.Reference:
return KnownMonikers.Reference;
case Glyph.StructurePublic:
return KnownMonikers.ValueTypePublic;
case Glyph.StructureProtected:
return KnownMonikers.ValueTypeProtected;
case Glyph.StructurePrivate:
return KnownMonikers.ValueTypePrivate;
case Glyph.StructureInternal:
return KnownMonikers.ValueTypeInternal;
case Glyph.TypeParameter:
return KnownMonikers.Type;
case Glyph.Snippet:
return KnownMonikers.Snippet;
case Glyph.CompletionWarning:
return KnownMonikers.IntellisenseWarning;
case Glyph.StatusInformation:
return KnownMonikers.StatusInformation;
case Glyph.NuGet:
return KnownMonikers.NuGet;
default:
throw new ArgumentException("glyph");
}
}
public static Glyph GetGlyph(this ImmutableArray<string> tags)
{
foreach (var tag in tags)
{
switch (tag)
{
case CompletionTags.Assembly:
return Glyph.Assembly;
case CompletionTags.File:
return tags.Contains(LanguageNames.VisualBasic) ? Glyph.BasicFile : Glyph.CSharpFile;
case CompletionTags.Project:
return tags.Contains(LanguageNames.VisualBasic) ? Glyph.BasicProject : Glyph.CSharpProject;
case CompletionTags.Class:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ClassProtected;
case Accessibility.Private:
return Glyph.ClassPrivate;
case Accessibility.Internal:
return Glyph.ClassInternal;
case Accessibility.Public:
default:
return Glyph.ClassPublic;
}
case CompletionTags.Constant:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ConstantProtected;
case Accessibility.Private:
return Glyph.ConstantPrivate;
case Accessibility.Internal:
return Glyph.ConstantInternal;
case Accessibility.Public:
default:
return Glyph.ConstantPublic;
}
case CompletionTags.Delegate:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.DelegateProtected;
case Accessibility.Private:
return Glyph.DelegatePrivate;
case Accessibility.Internal:
return Glyph.DelegateInternal;
case Accessibility.Public:
default:
return Glyph.DelegatePublic;
}
case CompletionTags.Enum:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.EnumProtected;
case Accessibility.Private:
return Glyph.EnumPrivate;
case Accessibility.Internal:
return Glyph.EnumInternal;
case Accessibility.Public:
default:
return Glyph.EnumPublic;
}
case CompletionTags.EnumMember:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.EnumMember;
case Accessibility.Private:
return Glyph.EnumMember;
case Accessibility.Internal:
return Glyph.EnumMember;
case Accessibility.Public:
default:
return Glyph.EnumMember;
}
case CompletionTags.Error:
return Glyph.Error;
case CompletionTags.Event:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.EventProtected;
case Accessibility.Private:
return Glyph.EventPrivate;
case Accessibility.Internal:
return Glyph.EventInternal;
case Accessibility.Public:
default:
return Glyph.EventPublic;
}
case CompletionTags.ExtensionMethod:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ExtensionMethodProtected;
case Accessibility.Private:
return Glyph.ExtensionMethodPrivate;
case Accessibility.Internal:
return Glyph.ExtensionMethodInternal;
case Accessibility.Public:
default:
return Glyph.ExtensionMethodPublic;
}
case CompletionTags.Field:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.FieldProtected;
case Accessibility.Private:
return Glyph.FieldPrivate;
case Accessibility.Internal:
return Glyph.FieldInternal;
case Accessibility.Public:
default:
return Glyph.FieldPublic;
}
case CompletionTags.Interface:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.InterfaceProtected;
case Accessibility.Private:
return Glyph.InterfacePrivate;
case Accessibility.Internal:
return Glyph.InterfaceInternal;
case Accessibility.Public:
default:
return Glyph.InterfacePublic;
}
case CompletionTags.Intrinsic:
return Glyph.Intrinsic;
case CompletionTags.Keyword:
return Glyph.Keyword;
case CompletionTags.Label:
return Glyph.Label;
case CompletionTags.Local:
return Glyph.Local;
case CompletionTags.Namespace:
return Glyph.Namespace;
case CompletionTags.Method:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.MethodProtected;
case Accessibility.Private:
return Glyph.MethodPrivate;
case Accessibility.Internal:
return Glyph.MethodInternal;
case Accessibility.Public:
default:
return Glyph.MethodPublic;
}
case CompletionTags.Module:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ModulePublic;
case Accessibility.Private:
return Glyph.ModulePrivate;
case Accessibility.Internal:
return Glyph.ModuleInternal;
case Accessibility.Public:
default:
return Glyph.ModulePublic;
}
case CompletionTags.Folder:
return Glyph.OpenFolder;
case CompletionTags.Operator:
return Glyph.Operator;
case CompletionTags.Parameter:
return Glyph.Parameter;
case CompletionTags.Property:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.PropertyProtected;
case Accessibility.Private:
return Glyph.PropertyPrivate;
case Accessibility.Internal:
return Glyph.PropertyInternal;
case Accessibility.Public:
default:
return Glyph.PropertyPublic;
}
case CompletionTags.RangeVariable:
return Glyph.RangeVariable;
case CompletionTags.Reference:
return Glyph.Reference;
case CompletionTags.Structure:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.StructureProtected;
case Accessibility.Private:
return Glyph.StructurePrivate;
case Accessibility.Internal:
return Glyph.StructureInternal;
case Accessibility.Public:
default:
return Glyph.StructurePublic;
}
case CompletionTags.TypeParameter:
return Glyph.TypeParameter;
case CompletionTags.Snippet:
return Glyph.Snippet;
case CompletionTags.Warning:
return Glyph.CompletionWarning;
case CompletionTags.StatusInformation:
return Glyph.StatusInformation;
}
}
return Glyph.None;
}
private static Accessibility GetAccessibility(ImmutableArray<string> tags)
{
if (tags.Contains(CompletionTags.Public))
{
return Accessibility.Public;
}
else if (tags.Contains(CompletionTags.Protected))
{
return Accessibility.Protected;
}
else if (tags.Contains(CompletionTags.Internal))
{
return Accessibility.Internal;
}
else if (tags.Contains(CompletionTags.Private))
{
return Accessibility.Private;
}
else
{
return Accessibility.NotApplicable;
}
}
}
}
| |
/*
Azure Media Services REST API v2 Function
This function checks a task status.
Input:
{
"jobId" : "nb:jid:UUID:1ceaa82f-2607-4df9-b034-cd730dad7097", // Mandatory, Id of the job
"taskId" : "nb:tid:UUID:cdc25b10-3ed7-4005-bcf9-6222b35b5be3", // Mandatory, Id of the task
"extendedInfo" : true // optional. Returns ams account unit size, nb units, nb of jobs in queue, scheduled and running states. Only if job is complete or error
"noWait" : true // optional. Set this parameter if you don't want the function to wait. Otherwise it waits for 15 seconds if the job is not completed before doing another check and terminate
}
Output:
{
"taskState" : 2, // The state of the task (int)
"isRunning" : "False", // True if task is running
"isSuccessful" : "True", // True is task is a success. Value is only valid if isRunning = "False"
"errorText" : "" // error(s) text if task state is error
"startTime" :""
"endTime" : "",
"runningDuration" : "",
"progress"" : 20.1 // progress of the task, between 0 and 100
"extendedInfo" : // if extendedInfo is true and job is finished or in error
{
"mediaUnitNumber" = 2,
"mediaUnitSize" = "S2",
"otherJobsProcessing" = 2,
"otherJobsScheduled" = 1,
"otherJobsQueue" = 1,
"amsRESTAPIEndpoint" = "http://....."
}
}
*/
using System;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.WindowsAzure.MediaServices.Client;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
namespace media_functions_for_logic_app
{
public static class check_task_status
{
// Field for service context.
private static CloudMediaContext _context = null;
private static CloudStorageAccount _destinationStorageAccount = null;
[FunctionName("check-task-status")]
public static async Task<object> Run([HttpTrigger(WebHookType = "genericJson")]HttpRequestMessage req, TraceWriter log)
{
log.Info($"Webhook was triggered!");
string jsonContent = await req.Content.ReadAsStringAsync();
dynamic data = JsonConvert.DeserializeObject(jsonContent);
log.Info(jsonContent);
if (data.jobId == null || data.taskId == null)
{
// used to test the function
//data.jobId = "nb:jid:UUID:acf38b8a-aef9-4789-9f0f-f69bf6ccb8e5";
return req.CreateResponse(HttpStatusCode.BadRequest, new
{
error = "Please pass the job and task ID in the input object (jobId, taskId)"
});
}
MediaServicesCredentials amsCredentials = new MediaServicesCredentials();
log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}");
IJob job = null;
ITask task = null;
string startTime = "";
string endTime = "";
StringBuilder sberror = new StringBuilder();
string runningDuration = "";
bool isRunning = true;
bool isSuccessful = true;
bool extendedInfo = false;
if (data.extendedInfo != null && ((bool)data.extendedInfo) == true)
{
extendedInfo = true;
}
try
{
AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
AzureEnvironments.AzureCloudEnvironment);
AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);
_context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);
// Get the job
string jobid = (string)data.jobId;
job = _context.Jobs.Where(j => j.Id == jobid).FirstOrDefault();
if (job == null)
{
log.Info($"Job not found {jobid}");
return req.CreateResponse(HttpStatusCode.InternalServerError, new
{
error = "Job not found"
});
}
// Get the task
string taskid = (string)data.taskId;
task = job.Tasks.Where(j => j.Id == taskid).FirstOrDefault();
if (task == null)
{
log.Info($"Task not found {taskid}");
return req.CreateResponse(HttpStatusCode.InternalServerError, new
{
error = "Task not found"
});
}
if (data.noWait != null && (bool)data.noWait)
{
// No wait
}
else
{
for (int i = 1; i <= 3; i++) // let's wait 3 times 5 seconds (15 seconds)
{
log.Info($"Task {task.Id} status is {task.State}");
if (task.State == JobState.Finished || task.State == JobState.Canceled || task.State == JobState.Error)
{
break;
}
log.Info("Waiting 5 s...");
System.Threading.Thread.Sleep(5 * 1000);
task = job.Tasks.Where(j => j.Id == taskid).FirstOrDefault();
}
}
if (task.State == JobState.Error || task.State == JobState.Canceled)
{
foreach (var details in task.ErrorDetails)
{
sberror.AppendLine(task.Name + " : " + details.Message);
}
}
if (task.StartTime != null) startTime = ((DateTime)task.StartTime).ToString("o");
if (task.EndTime != null) endTime = ((DateTime)task.EndTime).ToString("o");
if (task.RunningDuration != null) runningDuration = task.RunningDuration.ToString();
}
catch (Exception ex)
{
string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : "");
log.Info($"ERROR: Exception {message}");
return req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message });
}
isRunning = !(task.State == JobState.Finished || task.State == JobState.Canceled || task.State == JobState.Error);
isSuccessful = (task.State == JobState.Finished);
if (extendedInfo && (task.State == JobState.Finished || task.State == JobState.Canceled || task.State == JobState.Error))
{
dynamic stats = new JObject();
stats.mediaUnitNumber = _context.EncodingReservedUnits.FirstOrDefault().CurrentReservedUnits;
stats.mediaUnitSize = MediaServicesHelper.ReturnMediaReservedUnitName(_context.EncodingReservedUnits.FirstOrDefault().ReservedUnitType); ;
stats.otherJobsProcessing = _context.Jobs.Where(j => j.State == JobState.Processing).Count();
stats.otherJobsScheduled = _context.Jobs.Where(j => j.State == JobState.Scheduled).Count();
stats.otherJobsQueue = _context.Jobs.Where(j => j.State == JobState.Queued).Count();
stats.amsRESTAPIEndpoint = amsCredentials.AmsRestApiEndpoint;
return req.CreateResponse(HttpStatusCode.OK, new
{
taskState = task.State,
errorText = sberror.ToString(),
startTime = startTime,
endTime = endTime,
runningDuration = runningDuration,
extendedInfo = stats.ToString(),
isRunning = isRunning.ToString(),
isSuccessful = isSuccessful.ToString(),
progress = task.Progress
});
}
else
{
return req.CreateResponse(HttpStatusCode.OK, new
{
taskState = task.State,
errorText = sberror.ToString(),
startTime = startTime,
endTime = endTime,
runningDuration = runningDuration,
isRunning = isRunning.ToString(),
isSuccessful = isSuccessful.ToString(),
progress = task.Progress
});
}
}
}
}
| |
using System;
namespace ETLStackBrowse
{
public interface INamedFilter
{
bool this[int index] { get; set; }
bool this[string index] { get; set; }
void Clear();
void SetAll();
int Count { get; }
bool IsValidKey(string key);
bool[] GetFilters();
}
public interface IIndexedFilter
{
bool this[int index] { get; set; }
void Clear();
void SetAll();
int Count { get; }
}
public interface IStackParameters
{
bool SkipThunks { get; set; }
bool UseExeFrame { get; set; }
bool UsePid { get; set; }
bool UseTid { get; set; }
bool FoldModules { get; set; }
bool UseRootAI { get; set; }
bool ShowWhen { get; set; }
bool UseIODuration { get; set; }
bool AnalyzeReservedMemory { get; set; }
bool IndentLess { get; set; }
double MinInclusive { get; set; }
string FrameFilters { get; set; }
string ButterflyPivot { get; set; }
}
public interface IRollupParameters
{
string RollupCommand { get; set; }
int RollupTimeIntervals { get; set; }
}
public interface IContextSwitchParameters
{
bool SimulateHyperthreading { get; set; }
bool SortBySwitches { get; set; }
bool ComputeReasons { get; set; }
int TopThreadCount { get; set; }
}
public interface ITraceParameters
{
INamedFilter EventFilters { get; }
INamedFilter StackFilters { get; }
IIndexedFilter ThreadFilters { get; }
IIndexedFilter ProcessFilters { get; }
IStackParameters StackParameters { get; }
IRollupParameters RollupParameters { get; }
IContextSwitchParameters ContextSwitchParameters { get; }
String MemoryFilters { get; set; }
bool[] GetProcessFilters();
bool[] GetThreadFilters();
String FilterText { get; set; }
long T0 { get; set; }
long T1 { get; set; }
bool EnableThreadFilter { get; set; }
bool EnableProcessFilter { get; set; }
bool UnmangleBartokSymbols { get; set; }
bool ElideGenerics { get; set; }
}
public interface ITraceUINotify
{
void ClearZoomedTimes();
void ClearEventFields();
void AddEventField(string s);
void AddEventToStackEventList(string s);
void AddEventToEventList(string s);
void AddThreadToThreadList(string s);
void AddProcessToProcessList(string s);
void AddTimeToTimeList(string s);
void AddTimeToZoomedTimeList(string s);
}
public class StackParameters : IStackParameters
{
private bool fSkipThunks = true;
private bool fUseExeFrame = true;
private bool fUsePid = true;
private bool fUseTid = true;
private bool fFoldModules = false;
private bool fUseRootAI = false;
private bool fShowWhen = true;
private bool fUseIODuration = false;
private bool fIndentLess = true;
private bool fAnalyzeReservedMemory = false;
private double minIncl = 2.0;
private string frameFilters = "";
private string butterflyPivot = "";
public bool SkipThunks { get { return fSkipThunks; } set { fSkipThunks = value; } }
public bool UseExeFrame { get { return fUseExeFrame; } set { fUseExeFrame = value; } }
public bool UsePid { get { return fUsePid; } set { fUsePid = value; } }
public bool UseTid { get { return fUseTid; } set { fUseTid = value; } }
public bool FoldModules { get { return fFoldModules; } set { fFoldModules = value; } }
public bool UseRootAI { get { return fUseRootAI; } set { fUseRootAI = value; } }
public bool ShowWhen { get { return fShowWhen; } set { fShowWhen = value; } }
public bool UseIODuration { get { return fUseIODuration; } set { fUseIODuration = value; } }
public bool AnalyzeReservedMemory { get { return fAnalyzeReservedMemory; } set { fAnalyzeReservedMemory = value; } }
public bool IndentLess { get { return fIndentLess; } set { fIndentLess = value; } }
public double MinInclusive { get { return minIncl; } set { minIncl = value; } }
public string FrameFilters { get { return frameFilters; } set { frameFilters = value; } }
public string ButterflyPivot { get { return butterflyPivot; } set { butterflyPivot = value; } }
public StackParameters() { }
}
public class RollupParameters : IRollupParameters
{
private string rollupCommand = "";
private int rollupIntervals = 20;
public string RollupCommand { get { return rollupCommand; } set { rollupCommand = value; } }
public int RollupTimeIntervals { get { return rollupIntervals; } set { rollupIntervals = value; } }
public RollupParameters() { }
}
public class ContextSwitchParameters : IContextSwitchParameters
{
private bool fSimulateHyperthreading = false;
private bool fSortBySwitches = false;
private bool fComputeReasons = false;
private int nTop = 0;
public bool SimulateHyperthreading { get { return fSimulateHyperthreading; } set { fSimulateHyperthreading = value; } }
public bool SortBySwitches { get { return fSortBySwitches; } set { fSortBySwitches = value; } }
public bool ComputeReasons { get { return fComputeReasons; } set { fComputeReasons = value; } }
public int TopThreadCount { get { return nTop; } set { nTop = value; } }
public ContextSwitchParameters() { }
}
public class TraceParameters : ITraceParameters
{
private AtomFilter eventfilter;
private AtomFilter stackfilter;
private IndexFilter processfilter;
private IndexFilter threadfilter;
private IStackParameters stackParameters;
private IRollupParameters rollupParameters;
private IContextSwitchParameters contextSwitchParameters;
public TraceParameters(ETLTrace t)
{
eventfilter = new AtomFilter(t.RecordAtoms);
stackfilter = new AtomFilter(t.RecordAtoms);
processfilter = new IndexFilter(t.Processes.Count);
threadfilter = new IndexFilter(t.Threads.Count);
stackParameters = new StackParameters();
rollupParameters = new RollupParameters();
contextSwitchParameters = new ContextSwitchParameters();
contextSwitchParameters.TopThreadCount = t.Threads.Count;
FilterText = "";
MemoryFilters = "";
T0 = 0;
T1 = t.TMax;
RollupTimeIntervals = 20;
}
public INamedFilter EventFilters { get { return eventfilter; } }
public INamedFilter StackFilters { get { return stackfilter; } }
public IIndexedFilter ThreadFilters { get { return threadfilter; } }
public IIndexedFilter ProcessFilters { get { return processfilter; } }
public IStackParameters StackParameters { get { return stackParameters; } }
public IRollupParameters RollupParameters { get { return rollupParameters; } }
public IContextSwitchParameters ContextSwitchParameters { get { return contextSwitchParameters; } }
public bool[] GetProcessFilters()
{
if (!EnableProcessFilter)
{
var ret = new bool[processfilter.Count];
for (int i = 0; i < ret.Length; i++)
{
ret[i] = true;
}
return ret;
}
return processfilter.GetFilters();
}
public bool[] GetThreadFilters()
{
if (!EnableThreadFilter)
{
var ret = new bool[threadfilter.Count];
for (int i = 0; i < ret.Length; i++)
{
ret[i] = true;
}
return ret;
}
return threadfilter.GetFilters();
}
public String FilterText { get; set; }
public long T0 { get; set; }
public long T1 { get; set; }
public string MemoryFilters { get; set; }
public bool EnableThreadFilter { get; set; }
public bool EnableProcessFilter { get; set; }
public int RollupTimeIntervals { get; set; }
public bool ElideGenerics { get; set; }
public bool UnmangleBartokSymbols { get; set; }
}
public class IndexFilter : IIndexedFilter
{
private bool[] filters;
public IndexFilter(int count)
{
filters = new bool[count];
}
public void Clear()
{
for (int i = 0; i < filters.Length; i++)
{
filters[i] = false;
}
}
public void SetAll()
{
for (int i = 0; i < filters.Length; i++)
{
filters[i] = true;
}
}
public bool this[int index]
{
get
{
return filters[index];
}
set
{
filters[index] = value;
}
}
public int Count
{
get
{
return filters.Length;
}
}
public bool[] GetFilters()
{
return filters;
}
}
public class AtomFilter : INamedFilter
{
private ByteAtomTable atoms;
private bool[] filters;
public AtomFilter(ByteAtomTable atoms)
{
this.atoms = atoms;
filters = new bool[atoms.Count];
}
public void Clear()
{
for (int i = 0; i < filters.Length; i++)
{
filters[i] = false;
}
}
public void SetAll()
{
for (int i = 0; i < filters.Length; i++)
{
filters[i] = true;
}
}
public bool this[int index]
{
get
{
return filters[index];
}
set
{
filters[index] = value;
}
}
public bool this[string key]
{
get
{
int i = atoms.Lookup(key);
if (i < 0)
{
return false;
}
return filters[i];
}
set
{
int i = atoms.Lookup(key);
if (i < 0)
{
return;
}
filters[i] = value;
}
}
public bool IsValidKey(string key)
{
return atoms.Lookup(key) >= 0;
}
public int Count
{
get
{
return filters.Length;
}
}
public bool[] GetFilters()
{
return filters;
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Messaging;
using Orleans.Providers;
using Orleans.CodeGeneration;
using Orleans.Serialization;
using Orleans.Storage;
using Orleans.Runtime.Configuration;
using System.Collections.Concurrent;
using Orleans.Streams;
namespace Orleans
{
internal class OutsideRuntimeClient : IRuntimeClient, IDisposable
{
internal static bool TestOnlyThrowExceptionDuringInit { get; set; }
private readonly TraceLogger logger;
private readonly TraceLogger appLogger;
private readonly ClientConfiguration config;
private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks;
private readonly ConcurrentDictionary<GuidId, LocalObjectData> localObjects;
private readonly ProxiedMessageCenter transport;
private bool listenForMessages;
private CancellationTokenSource listeningCts;
private readonly ClientProviderRuntime clientProviderRuntime;
private readonly StatisticsProviderManager statisticsProviderManager;
internal ClientStatisticsManager ClientStatistics;
private readonly GrainId clientId;
private GrainInterfaceMap grainInterfaceMap;
private readonly ThreadTrackingStatistic incomingMessagesThreadTimeTracking;
// initTimeout used to be AzureTableDefaultPolicies.TableCreationTimeout, which was 3 min
private static readonly TimeSpan initTimeout = TimeSpan.FromMinutes(1);
private static readonly TimeSpan resetTimeout = TimeSpan.FromMinutes(1);
private const string BARS = "----------";
private readonly GrainFactory grainFactory;
public GrainFactory InternalGrainFactory
{
get { return grainFactory; }
}
/// <summary>
/// Response timeout.
/// </summary>
private TimeSpan responseTimeout;
private static readonly Object staticLock = new Object();
Logger IRuntimeClient.AppLogger
{
get { return appLogger; }
}
public ActivationAddress CurrentActivationAddress
{
get;
private set;
}
public SiloAddress CurrentSilo
{
get { return CurrentActivationAddress.Silo; }
}
public string Identity
{
get { return CurrentActivationAddress.ToString(); }
}
public IActivationData CurrentActivationData
{
get { return null; }
}
public IAddressable CurrentGrain
{
get { return null; }
}
public IStorageProvider CurrentStorageProvider
{
get { throw new InvalidOperationException("Storage provider only available from inside grain"); }
}
internal List<Uri> Gateways
{
get
{
return transport.GatewayManager.ListProvider.GetGateways().ToList();
}
}
public IStreamProviderManager CurrentStreamProviderManager { get; private set; }
public IStreamProviderRuntime CurrentStreamProviderRuntime
{
get { return clientProviderRuntime; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")]
public OutsideRuntimeClient(ClientConfiguration cfg, GrainFactory grainFactory, bool secondary = false)
{
this.grainFactory = grainFactory;
this.clientId = GrainId.NewClientId();
if (cfg == null)
{
Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object.");
throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg");
}
this.config = cfg;
if (!TraceLogger.IsInitialized) TraceLogger.Initialize(config);
StatisticsCollector.Initialize(config);
SerializationManager.Initialize(config.UseStandardSerializer);
logger = TraceLogger.GetLogger("OutsideRuntimeClient", TraceLogger.LoggerType.Runtime);
appLogger = TraceLogger.GetLogger("Application", TraceLogger.LoggerType.Application);
try
{
LoadAdditionalAssemblies();
PlacementStrategy.Initialize();
callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>();
localObjects = new ConcurrentDictionary<GuidId, LocalObjectData>();
CallbackData.Config = config;
if (!secondary)
{
UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException);
}
// Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked
SerializationManager.GetDeserializer(typeof(String));
// Ensure that any assemblies that get loaded in the future get recorded
AppDomain.CurrentDomain.AssemblyLoad += NewAssemblyHandler;
// Load serialization info for currently-loaded assemblies
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (!assembly.ReflectionOnly)
{
SerializationManager.FindSerializationInfo(assembly);
}
}
clientProviderRuntime = new ClientProviderRuntime(grainFactory);
statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime);
var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations)
.WaitForResultWithThrow(initTimeout);
if (statsProviderName != null)
{
config.StatisticsProviderName = statsProviderName;
}
responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout;
BufferPool.InitGlobalBufferPool(config);
var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface);
// Client init / sign-on message
logger.Info(ErrorCode.ClientInitializing, string.Format(
"{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}",
BARS, config.DNSHostName, localAddress, clientId));
string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}'", BARS, RuntimeVersion.Current);
startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config);
logger.Info(ErrorCode.ClientStarting, startMsg);
if (TestOnlyThrowExceptionDuringInit)
{
throw new ApplicationException("TestOnlyThrowExceptionDuringInit");
}
config.CheckGatewayProviderSettings();
var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative
var gatewayListProvider = GatewayProviderFactory.CreateGatewayListProvider(config)
.WithTimeout(initTimeout).Result;
transport = new ProxiedMessageCenter(config, localAddress, generation, clientId, gatewayListProvider);
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver");
}
}
catch (Exception exc)
{
if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc);
ConstructorReset();
throw;
}
}
private void StreamingInitialize()
{
var implicitSubscriberTable = transport.GetImplicitStreamSubscriberTable(grainFactory).Result;
clientProviderRuntime.StreamingInitialize(implicitSubscriberTable);
var streamProviderManager = new Streams.StreamProviderManager();
streamProviderManager
.LoadStreamProviders(
this.config.ProviderConfigurations,
clientProviderRuntime)
.Wait();
CurrentStreamProviderManager = streamProviderManager;
}
private static void LoadAdditionalAssemblies()
{
var logger = TraceLogger.GetLogger("AssemblyLoader.Client", TraceLogger.LoggerType.Runtime);
var directories =
new Dictionary<string, SearchOption>
{
{
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
SearchOption.AllDirectories
}
};
var excludeCriteria =
new AssemblyLoaderPathNameCriterion[]
{
AssemblyLoaderCriteria.ExcludeResourceAssemblies,
AssemblyLoaderCriteria.ExcludeSystemBinaries()
};
var loadProvidersCriteria =
new AssemblyLoaderReflectionCriterion[]
{
AssemblyLoaderCriteria.LoadTypesAssignableFrom(typeof(IProvider))
};
AssemblyLoader.LoadAssemblies(directories, excludeCriteria, loadProvidersCriteria, logger);
}
private static void NewAssemblyHandler(object sender, AssemblyLoadEventArgs args)
{
var assembly = args.LoadedAssembly;
if (!assembly.ReflectionOnly)
{
SerializationManager.FindSerializationInfo(args.LoadedAssembly);
}
}
private void UnhandledException(ISchedulingContext context, Exception exception)
{
logger.Error(ErrorCode.Runtime_Error_100007, String.Format("OutsideRuntimeClient caught an UnobservedException."), exception);
logger.Assert(ErrorCode.Runtime_Error_100008, context == null, "context should be not null only inside OrleansRuntime and not on the client.");
}
public void Start()
{
lock (staticLock)
{
if (RuntimeClient.Current != null)
throw new InvalidOperationException("Can only have one RuntimeClient per AppDomain");
RuntimeClient.Current = this;
}
StartInternal();
logger.Info(ErrorCode.ProxyClient_StartDone, "{0} Started OutsideRuntimeClient with Global Client ID: {1}", BARS, CurrentActivationAddress.ToString() + ", client GUID ID: " + clientId);
}
// used for testing to (carefully!) allow two clients in the same process
internal void StartInternal()
{
transport.Start();
TraceLogger.MyIPEndPoint = transport.MyAddress.Endpoint; // transport.MyAddress is only set after transport is Started.
CurrentActivationAddress = ActivationAddress.NewActivationAddress(transport.MyAddress, clientId);
ClientStatistics = new ClientStatisticsManager(config);
ClientStatistics.Start(config, statisticsProviderManager, transport, clientId)
.WaitWithThrow(initTimeout);
listeningCts = new CancellationTokenSource();
var ct = listeningCts.Token;
listenForMessages = true;
// Keeping this thread handling it very simple for now. Just queue task on thread pool.
Task.Factory.StartNew(() =>
{
try
{
RunClientMessagePump(ct);
}
catch(Exception exc)
{
logger.Error(ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown exception", exc);
}
}
);
grainInterfaceMap = transport.GetTypeCodeMap(grainFactory).Result;
StreamingInitialize();
}
private void RunClientMessagePump(CancellationToken ct)
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartExecution();
}
while (listenForMessages)
{
var message = transport.WaitMessage(Message.Categories.Application, ct);
if (message == null) // if wait was cancelled
break;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartProcessing();
}
#endif
switch (message.Direction)
{
case Message.Directions.Response:
{
ReceiveResponse(message);
break;
}
case Message.Directions.OneWay:
case Message.Directions.Request:
{
this.DispatchToLocalObject(message);
break;
}
default:
logger.Error(ErrorCode.Runtime_Error_100327, String.Format("Message not supported: {0}.", message));
break;
}
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopProcessing();
incomingMessagesThreadTimeTracking.IncrementNumberOfProcessed();
}
#endif
}
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}
private void DispatchToLocalObject(Message message)
{
LocalObjectData objectData;
GuidId observerId = message.TargetObserverId;
if (observerId == null)
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound_2,
String.Format("Did not find TargetObserverId header in the message = {0}. A request message to a client is expected to have an observerId.", message));
return;
}
if (localObjects.TryGetValue(observerId, out objectData))
this.InvokeLocalObjectAsync(objectData, message);
else
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound,
String.Format(
"Unexpected target grain in request: {0}. Message={1}",
message.TargetGrain,
message));
}
}
private void InvokeLocalObjectAsync(LocalObjectData objectData, Message message)
{
var obj = (IAddressable)objectData.LocalObject.Target;
if (obj == null)
{
//// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore.
logger.Warn(ErrorCode.Runtime_Error_100162,
String.Format("Object associated with Observer ID {0} has been garbage collected. Deleting object reference and unregistering it. Message = {1}", objectData.ObserverId, message));
LocalObjectData ignore;
// Try to remove. If it's not there, we don't care.
localObjects.TryRemove(objectData.ObserverId, out ignore);
return;
}
bool start;
lock (objectData.Messages)
{
objectData.Messages.Enqueue(message);
start = !objectData.Running;
objectData.Running = true;
}
if (logger.IsVerbose) logger.Verbose("InvokeLocalObjectAsync {0} start {1}", message, start);
if (start)
{
// we use Task.Run() to ensure that the message pump operates asynchronously
// with respect to the current thread. see
// http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74
// at position 54:45.
//
// according to the information posted at:
// http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr
// this idiom is dependent upon the a TaskScheduler not implementing the
// override QueueTask as task inlining (as opposed to queueing). this seems
// implausible to the author, since none of the .NET schedulers do this and
// it is considered bad form (the OrleansTaskScheduler does not do this).
//
// if, for some reason this doesn't hold true, we can guarantee what we
// want by passing a placeholder continuation token into Task.StartNew()
// instead. i.e.:
//
// return Task.StartNew(() => ..., new CancellationToken());
Func<Task> asyncFunc =
async () =>
await this.LocalObjectMessagePumpAsync(objectData);
Task.Run(asyncFunc).Ignore();
}
}
private async Task LocalObjectMessagePumpAsync(LocalObjectData objectData)
{
while (true)
{
try
{
Message message;
lock (objectData.Messages)
{
if (objectData.Messages.Count == 0)
{
objectData.Running = false;
break;
}
message = objectData.Messages.Dequeue();
}
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Invoke))
continue;
RequestContext.Import(message.RequestContextData);
var request = (InvokeMethodRequest)message.BodyObject;
var targetOb = (IAddressable)objectData.LocalObject.Target;
object resultObject = null;
Exception caught = null;
try
{
// exceptions thrown within this scope are not considered to be thrown from user code
// and not from runtime code.
var resultPromise = objectData.Invoker.Invoke(
targetOb,
request.InterfaceId,
request.MethodId,
request.Arguments);
if (resultPromise != null) // it will be null for one way messages
{
resultObject = await resultPromise;
}
}
catch (Exception exc)
{
// the exception needs to be reported in the log or propagated back to the caller.
caught = exc;
}
if (caught != null)
this.ReportException(message, caught);
else if (message.Direction != Message.Directions.OneWay)
await this.SendResponseAsync(message, resultObject);
}catch(Exception)
{
// ignore, keep looping.
}
}
}
private static bool ExpireMessageIfExpired(Message message, MessagingStatisticsGroup.Phase phase)
{
if (message.IsExpired)
{
message.DropExpiredMessage(phase);
return true;
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Task
SendResponseAsync(
Message message,
object resultObject)
{
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond))
return TaskDone.Done;
object deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = SerializationManager.DeepCopy(resultObject);
}
catch (Exception exc2)
{
SendResponse(message, Response.ExceptionResponse(exc2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendResponseFailed,
"Exception trying to send a response.", exc2);
return TaskDone.Done;
}
// the deep-copy succeeded.
SendResponse(message, new Response(deepCopy));
return TaskDone.Done;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ReportException(Message message, Exception exception)
{
var request = (InvokeMethodRequest)message.BodyObject;
switch (message.Direction)
{
default:
throw new InvalidOperationException();
case Message.Directions.OneWay:
{
logger.Error(
ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke,
String.Format(
"Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.",
request.MethodId,
request.InterfaceId),
exception);
break;
}
case Message.Directions.Request:
{
Exception deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = (Exception)SerializationManager.DeepCopy(exception);
}
catch (Exception ex2)
{
SendResponse(message, Response.ExceptionResponse(ex2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed,
"Exception trying to send an exception response", ex2);
return;
}
// the deep-copy succeeded.
var response = Response.ExceptionResponse(deepCopy);
SendResponse(message, response);
break;
}
}
}
private void SendResponse(Message request, Response response)
{
var message = request.CreateResponseMessage();
message.BodyObject = response;
transport.SendMessage(message);
}
/// <summary>
/// For testing only.
/// </summary>
public void Disconnect()
{
transport.Disconnect();
}
/// <summary>
/// For testing only.
/// </summary>
public void Reconnect()
{
transport.Reconnect();
}
#region Implementation of IRuntimeClient
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "CallbackData is IDisposable but instances exist beyond lifetime of this method so cannot Dispose yet.")]
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var message = RuntimeClient.CreateMessage(request, options);
SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments);
}
private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var targetGrainId = target.GrainId;
var oneWay = (options & InvokeMethodOptions.OneWay) != 0;
message.SendingGrain = CurrentActivationAddress.Grain;
message.SendingActivation = CurrentActivationAddress.Activation;
// Hack
message.SendingSilo = CurrentActivationAddress.Silo;
message.TargetGrain = targetGrainId;
if (!String.IsNullOrEmpty(genericArguments))
message.GenericGrainType = genericArguments;
if (targetGrainId.IsSystemTarget)
{
// If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo
message.TargetSilo = target.SystemTargetSilo;
if (target.SystemTargetSilo != null)
{
message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo);
}
}
// Client sending messages to another client (observer). Yes, we support that.
if (target.IsObserverReference)
{
message.TargetObserverId = target.ObserverId;
}
if (debugContext != null)
{
message.DebugContext = debugContext;
}
if (message.IsExpirableMessage(config))
{
// don't set expiration for system target messages.
message.Expiration = DateTime.UtcNow + responseTimeout + Constants.MAXIMUM_CLOCK_SKEW;
}
if (!oneWay)
{
var callbackData = new CallbackData(callback, TryResendMessage, context, message, () => UnRegisterCallback(message.Id));
callbacks.TryAdd(message.Id, callbackData);
callbackData.StartTimer(responseTimeout);
}
if (logger.IsVerbose2) logger.Verbose2("Send {0}", message);
transport.SendMessage(message);
}
private bool TryResendMessage(Message message)
{
if (!message.MayResend(config))
{
return false;
}
if (logger.IsVerbose) logger.Verbose("Resend {0}", message);
message.ResendCount = message.ResendCount + 1;
message.SetMetadata(Message.Metadata.TARGET_HISTORY, message.GetTargetHistory());
if (!message.TargetGrain.IsSystemTarget)
{
message.RemoveHeader(Message.Header.TARGET_ACTIVATION);
message.RemoveHeader(Message.Header.TARGET_SILO);
}
transport.SendMessage(message);
return true;
}
public void ReceiveResponse(Message response)
{
if (logger.IsVerbose2) logger.Verbose2("Received {0}", response);
// ignore duplicate requests
if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.DuplicateRequest)
return;
CallbackData callbackData;
var found = callbacks.TryGetValue(response.Id, out callbackData);
if (found)
{
// We need to import the RequestContext here as well.
// Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task.
// RequestContext.Import(response.RequestContextData);
callbackData.DoCallback(response);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response);
}
}
private void UnRegisterCallback(CorrelationId id)
{
CallbackData ignore;
callbacks.TryRemove(id, out ignore);
}
public void Reset()
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId);
}
});
Utils.SafeExecute(() =>
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset().WaitWithThrow(resetTimeout);
}
}, logger, "Client.clientProviderRuntime.Reset");
Utils.SafeExecute(() =>
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.PrepareToStop();
}
}, logger, "Client.PrepareToStop-Transport");
listenForMessages = false;
Utils.SafeExecute(() =>
{
if (listeningCts != null)
{
listeningCts.Cancel();
}
}, logger, "Client.Stop-ListeningCTS");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.Stop();
}
}, logger, "Client.Stop-Transport");
Utils.SafeExecute(() =>
{
if (ClientStatistics != null)
{
ClientStatistics.Stop();
}
}, logger, "Client.Stop-ClientStatistics");
ConstructorReset();
}
private void ConstructorReset()
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId);
}
});
try
{
UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler();
}
catch (Exception) { }
try
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset().WaitWithThrow(resetTimeout);
}
}
catch (Exception) { }
try
{
TraceLogger.UnInitialize();
}
catch (Exception) { }
}
public void SetResponseTimeout(TimeSpan timeout)
{
responseTimeout = timeout;
}
public TimeSpan GetResponseTimeout()
{
return responseTimeout;
}
public Task<IGrainReminder> RegisterOrUpdateReminder(string reminderName, TimeSpan dueTime, TimeSpan period)
{
throw new InvalidOperationException("RegisterReminder can only be called from inside a grain");
}
public Task UnregisterReminder(IGrainReminder reminder)
{
throw new InvalidOperationException("UnregisterReminder can only be called from inside a grain");
}
public Task<IGrainReminder> GetReminder(string reminderName)
{
throw new InvalidOperationException("GetReminder can only be called from inside a grain");
}
public Task<List<IGrainReminder>> GetReminders()
{
throw new InvalidOperationException("GetReminders can only be called from inside a grain");
}
public SiloStatus GetSiloStatus(SiloAddress silo)
{
throw new InvalidOperationException("GetSiloStatus can only be called on the silo.");
}
public async Task ExecAsync(Func<Task> asyncFunction, ISchedulingContext context)
{
await Task.Run(asyncFunction); // No grain context on client - run on .NET thread pool
}
public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
{
if (obj is GrainReference)
throw new ArgumentException("Argument obj is already a grain reference.");
GrainReference gr = GrainReference.NewObserverGrainReference(clientId, GuidId.GetNewGuidId());
if (!localObjects.TryAdd(gr.ObserverId, new LocalObjectData(obj, gr.ObserverId, invoker)))
{
throw new ArgumentException(String.Format("Failed to add new observer {0} to localObjects collection.", gr), "gr");
}
return gr;
}
public void DeleteObjectReference(IAddressable obj)
{
if (!(obj is GrainReference))
throw new ArgumentException("Argument reference is not a grain reference.");
var reference = (GrainReference) obj;
LocalObjectData ignore;
if (!localObjects.TryRemove(reference.ObserverId, out ignore))
throw new ArgumentException("Reference is not associated with a local object.", "reference");
}
public void DeactivateOnIdle(ActivationId id)
{
throw new InvalidOperationException();
}
#endregion
private class LocalObjectData
{
internal WeakReference LocalObject { get; private set; }
internal IGrainMethodInvoker Invoker { get; private set; }
internal GuidId ObserverId { get; private set; }
internal Queue<Message> Messages { get; private set; }
internal bool Running { get; set; }
internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker)
{
LocalObject = new WeakReference(obj);
ObserverId = observerId;
Invoker = invoker;
Messages = new Queue<Message>();
Running = false;
}
}
public void Dispose()
{
if (listeningCts != null)
{
listeningCts.Dispose();
listeningCts = null;
}
GC.SuppressFinalize(this);
}
public IGrainTypeResolver GrainTypeResolver
{
get { return grainInterfaceMap; }
}
public string CaptureRuntimeEnvironment()
{
throw new NotImplementedException();
}
public IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType = null)
{
throw new NotImplementedException();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using MigAz.Azure;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace MigAz.Forms
{
public partial class OptionsDialog : Form
{
private bool _HasChanges = false;
public OptionsDialog()
{
InitializeComponent();
}
private void chkAllowTelemetry_CheckedChanged(object sender, EventArgs e)
{
if (chkAllowTelemetry.Checked == true)
{
string message = String.Empty + "\n";
message = "\n" + "Tool telemetry data is important for us to keep improving it. Data collected is for tool development usage only and will not be shared, by any reason, out of the tool development team or scope.";
message += "\n";
message += "\n" + "Tool telemetry DOES send:";
message += "\n" + ". TenantId";
message += "\n" + ". SubscriptionId";
message += "\n" + ". Processed resources type";
message += "\n" + ". Processed resources location";
message += "\n" + ". Execution date";
message += "\n";
message += "\n" + "Tool telemetry DOES NOT send:";
message += "\n" + ". Resources names";
message += "\n" + ". Any resources configuration or caracteristics";
message += "\n" + ". Any local computer information";
message += "\n" + ". Any other information not stated on the \"Tool telemetry DOES send\" section";
message += "\n";
message += "\n" + "Do you authorize the tool to send telemetry data?";
DialogResult dialogresult = MessageBox.Show(message, "Authorization Request", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogresult == DialogResult.No)
{
chkAllowTelemetry.Checked = false;
}
}
_HasChanges = true;
}
private void txtStorageAccountSuffix_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsLetterOrDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
else
{
_HasChanges = true;
}
}
private void SaveChanges()
{
app.Default.ResourceGroupSuffix = txtResourceGroupSuffix.Text.Trim();
app.Default.VirtualNetworkSuffix = txtVirtualNetworkSuffix.Text.Trim();
app.Default.VirtualNetworkGatewaySuffix = txtVirtualNetworkGatewaySuffix.Text.Trim();
app.Default.NetworkSecurityGroupSuffix = txtNetworkSecurityGroupSuffix.Text.Trim();
app.Default.StorageAccountSuffix = txtStorageAccountSuffix.Text.Trim();
app.Default.PublicIPSuffix = txtPublicIPSuffix.Text.Trim();
app.Default.LoadBalancerSuffix = txtLoadBalancerSuffix.Text.Trim();
app.Default.AvailabilitySetSuffix = txtAvailabilitySetSuffix.Text.Trim();
app.Default.VirtualMachineSuffix = txtVirtualMachineSuffix.Text.Trim();
app.Default.NetworkInterfaceCardSuffix = txtNetworkInterfaceCardSuffix.Text.Trim();
app.Default.AutoSelectDependencies = chkAutoSelectDependencies.Checked;
app.Default.SaveSelection = chkSaveSelection.Checked;
app.Default.BuildEmpty = chkBuildEmpty.Checked;
app.Default.AllowTelemetry = chkAllowTelemetry.Checked;
app.Default.AccessSASTokenLifetimeSeconds = Convert.ToInt32(upDownAccessSASMinutes.Value) * 60;
switch (cmbLoginPromptBehavior.SelectedItem)
{
case "Always":
app.Default.LoginPromptBehavior = PromptBehavior.Always;
break;
case "Auto":
app.Default.LoginPromptBehavior = PromptBehavior.Auto;
break;
case "SelectAccount":
app.Default.LoginPromptBehavior = PromptBehavior.SelectAccount;
break;
default:
app.Default.LoginPromptBehavior = PromptBehavior.Auto;
break;
}
app.Default.AzureEnvironment = cmbDefaultAzureEnvironment.SelectedItem.ToString();
if (rbClassicDisk.Checked)
app.Default.DefaultTargetDiskType = Azure.Core.Interface.ArmDiskType.ClassicDisk;
else
app.Default.DefaultTargetDiskType = Azure.Core.Interface.ArmDiskType.ManagedDisk;
app.Default.Save();
_HasChanges = false;
}
private void btnOK_Click(object sender, EventArgs e)
{
if (_HasChanges)
SaveChanges();
}
private void formOptions_Load(object sender, EventArgs e)
{
txtResourceGroupSuffix.Text = app.Default.ResourceGroupSuffix;
txtVirtualNetworkSuffix.Text = app.Default.VirtualNetworkSuffix;
txtVirtualNetworkGatewaySuffix.Text = app.Default.VirtualNetworkGatewaySuffix;
txtNetworkSecurityGroupSuffix.Text = app.Default.NetworkSecurityGroupSuffix;
txtStorageAccountSuffix.Text = app.Default.StorageAccountSuffix;
txtPublicIPSuffix.Text = app.Default.PublicIPSuffix;
txtLoadBalancerSuffix.Text = app.Default.LoadBalancerSuffix;
txtAvailabilitySetSuffix.Text = app.Default.AvailabilitySetSuffix;
txtVirtualMachineSuffix.Text = app.Default.VirtualMachineSuffix;
txtNetworkInterfaceCardSuffix.Text = app.Default.NetworkInterfaceCardSuffix;
chkAutoSelectDependencies.Checked = app.Default.AutoSelectDependencies;
chkSaveSelection.Checked = app.Default.SaveSelection;
chkBuildEmpty.Checked = app.Default.BuildEmpty;
chkAllowTelemetry.Checked = app.Default.AllowTelemetry;
upDownAccessSASMinutes.Value = app.Default.AccessSASTokenLifetimeSeconds / 60;
if (app.Default.DefaultTargetDiskType == Azure.Core.Interface.ArmDiskType.ClassicDisk)
rbClassicDisk.Checked = true;
else
rbManagedDisk.Checked = true;
int promptBehaviorIndex = cmbLoginPromptBehavior.FindStringExact(app.Default.LoginPromptBehavior.ToString());
cmbLoginPromptBehavior.SelectedIndex = promptBehaviorIndex;
_HasChanges = false;
}
private void btnApplyDefaultNaming_Click(object sender, EventArgs e)
{
txtResourceGroupSuffix.Text = "-rg";
txtVirtualNetworkSuffix.Text = "-vnet";
txtVirtualNetworkGatewaySuffix.Text = "-gw";
txtNetworkSecurityGroupSuffix.Text = "-nsg";
txtStorageAccountSuffix.Text = "v2";
txtPublicIPSuffix.Text = "-pip";
txtLoadBalancerSuffix.Text = "-lb";
txtAvailabilitySetSuffix.Text = "-as";
txtVirtualMachineSuffix.Text = "-vm";
txtNetworkInterfaceCardSuffix.Text = "-nic";
}
private void OptionsDialog_FormClosing(object sender, FormClosingEventArgs e)
{
if (_HasChanges)
{
DialogResult result = MessageBox.Show("Do you want to save your MigAz Option changes?", "Pending Changes", MessageBoxButtons.YesNoCancel);
if (result == DialogResult.Yes)
{
this.SaveChanges();
}
else if (result == DialogResult.Cancel)
{
e.Cancel = true;
}
}
}
private void migAzOption_CheckedChanged(object sender, EventArgs e)
{
_HasChanges = true;
}
private void migAzOption_TextChanged(object sender, EventArgs e)
{
_HasChanges = true;
}
private void upDownAccessSASMinutes_ValueChanged(object sender, EventArgs e)
{
_HasChanges = true;
}
private void migAzOption_CheckChanged(object sender, EventArgs e)
{
_HasChanges = true;
}
private void btnCancel_Click(object sender, EventArgs e)
{
_HasChanges = false;
}
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
_HasChanges = true;
}
internal void Bind(List<AzureEnvironment> standardAzureEnvironments, List<AzureEnvironment> userDefinedAzureEnvironments)
{
cmbDefaultAzureEnvironment.Items.Clear();
foreach (AzureEnvironment azureEnvironment in standardAzureEnvironments)
{
cmbDefaultAzureEnvironment.Items.Add(azureEnvironment);
}
foreach (AzureEnvironment azureEnvironment in userDefinedAzureEnvironments)
{
cmbDefaultAzureEnvironment.Items.Add(azureEnvironment);
}
int defaultAzureEnvironmentIndex = cmbDefaultAzureEnvironment.FindStringExact(app.Default.AzureEnvironment);
if (defaultAzureEnvironmentIndex >= 0)
cmbDefaultAzureEnvironment.SelectedIndex = defaultAzureEnvironmentIndex;
else
cmbDefaultAzureEnvironment.SelectedIndex = 0;
}
}
}
| |
using System.Diagnostics;
using System.Text;
using HANDLE = System.IntPtr;
using i64 = System.Int64;
using u32 = System.UInt32;
using sqlite3_int64 = System.Int64;
namespace System.Data.SQLite
{
internal partial class Sqlite3
{
/*
** 2005 November 29
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains OS interface code that is common to all
** architectures.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45
**
*************************************************************************
*/
//#define _SQLITE_OS_C_ 1
//#include "sqliteInt.h"
//#undef _SQLITE_OS_C_
/*
** The default SQLite sqlite3_vfs implementations do not allocate
** memory (actually, os_unix.c allocates a small amount of memory
** from within OsOpen()), but some third-party implementations may.
** So we test the effects of a malloc() failing and the sqlite3OsXXX()
** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
**
** The following functions are instrumented for malloc() failure
** testing:
**
** sqlite3OsOpen()
** sqlite3OsRead()
** sqlite3OsWrite()
** sqlite3OsSync()
** sqlite3OsLock()
**
*/
#if (SQLITE_TEST)
static int sqlite3_memdebug_vfs_oom_test = 1;
//#define DO_OS_MALLOC_TEST(x) \
//if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
// void *pTstAlloc = sqlite3Malloc(10); \
// if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
// sqlite3_free(pTstAlloc); \
//}
static void DO_OS_MALLOC_TEST( sqlite3_file x )
{
}
#else
//#define DO_OS_MALLOC_TEST(x)
static void DO_OS_MALLOC_TEST(sqlite3_file x) { }
#endif
/*
** The following routines are convenience wrappers around methods
** of the sqlite3_file object. This is mostly just syntactic sugar. All
** of this would be completely automatic if SQLite were coded using
** C++ instead of plain old C.
*/
static int sqlite3OsClose(sqlite3_file pId)
{
int rc = SQLITE_OK;
if (pId.pMethods != null)
{
rc = pId.pMethods.xClose(pId);
pId.pMethods = null;
}
return rc;
}
static int sqlite3OsRead(sqlite3_file id, byte[] pBuf, int amt, i64 offset)
{
DO_OS_MALLOC_TEST(id);
if (pBuf == null)
pBuf = sqlite3Malloc(amt);
return id.pMethods.xRead(id, pBuf, amt, offset);
}
static int sqlite3OsWrite(sqlite3_file id, byte[] pBuf, int amt, i64 offset)
{
DO_OS_MALLOC_TEST(id);
return id.pMethods.xWrite(id, pBuf, amt, offset);
}
static int sqlite3OsTruncate(sqlite3_file id, i64 size)
{
return id.pMethods.xTruncate(id, size);
}
static int sqlite3OsSync(sqlite3_file id, int flags)
{
DO_OS_MALLOC_TEST(id);
return id.pMethods.xSync(id, flags);
}
static int sqlite3OsFileSize(sqlite3_file id, ref long pSize)
{
return id.pMethods.xFileSize(id, ref pSize);
}
static int sqlite3OsLock(sqlite3_file id, int lockType)
{
DO_OS_MALLOC_TEST(id);
return id.pMethods.xLock(id, lockType);
}
static int sqlite3OsUnlock(sqlite3_file id, int lockType)
{
return id.pMethods.xUnlock(id, lockType);
}
static int sqlite3OsCheckReservedLock(sqlite3_file id, ref int pResOut)
{
DO_OS_MALLOC_TEST(id);
return id.pMethods.xCheckReservedLock(id, ref pResOut);
}
static int sqlite3OsFileControl(sqlite3_file id, u32 op, ref sqlite3_int64 pArg)
{
return id.pMethods.xFileControl(id, (int)op, ref pArg);
}
static int sqlite3OsSectorSize(sqlite3_file id)
{
dxSectorSize xSectorSize = id.pMethods.xSectorSize;
return (xSectorSize != null ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
}
static int sqlite3OsDeviceCharacteristics(sqlite3_file id)
{
return id.pMethods.xDeviceCharacteristics(id);
}
static int sqlite3OsShmLock(sqlite3_file id, int offset, int n, int flags)
{
return id.pMethods.xShmLock(id, offset, n, flags);
}
static void sqlite3OsShmBarrier(sqlite3_file id)
{
id.pMethods.xShmBarrier(id);
}
static int sqlite3OsShmUnmap(sqlite3_file id, int deleteFlag)
{
return id.pMethods.xShmUnmap(id, deleteFlag);
}
static int sqlite3OsShmMap(
sqlite3_file id, /* Database file handle */
int iPage,
int pgsz,
int bExtend, /* True to extend file if necessary */
out object pp /* OUT: Pointer to mapping */
)
{
return id.pMethods.xShmMap(id, iPage, pgsz, bExtend, out pp);
}
/*
** The next group of routines are convenience wrappers around the
** VFS methods.
*/
static int sqlite3OsOpen(
sqlite3_vfs pVfs,
string zPath,
sqlite3_file pFile,
int flags,
ref int pFlagsOut
)
{
int rc;
DO_OS_MALLOC_TEST(null);
/* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
** reaching the VFS. */
rc = pVfs.xOpen(pVfs, zPath, pFile, flags & 0x87f3f, out pFlagsOut);
Debug.Assert(rc == SQLITE_OK || pFile.pMethods == null);
return rc;
}
static int sqlite3OsDelete(sqlite3_vfs pVfs, string zPath, int dirSync)
{
return pVfs.xDelete(pVfs, zPath, dirSync);
}
static int sqlite3OsAccess(sqlite3_vfs pVfs, string zPath, int flags, ref int pResOut)
{
DO_OS_MALLOC_TEST(null);
return pVfs.xAccess(pVfs, zPath, flags, out pResOut);
}
static int sqlite3OsFullPathname(
sqlite3_vfs pVfs,
string zPath,
int nPathOut,
StringBuilder zPathOut
)
{
zPathOut.Length = 0;//zPathOut[0] = 0;
return pVfs.xFullPathname(pVfs, zPath, nPathOut, zPathOut);
}
#if !SQLITE_OMIT_LOAD_EXTENSION
static HANDLE sqlite3OsDlOpen(sqlite3_vfs pVfs, string zPath)
{
return pVfs.xDlOpen(pVfs, zPath);
}
static void sqlite3OsDlError(sqlite3_vfs pVfs, int nByte, string zBufOut)
{
pVfs.xDlError(pVfs, nByte, zBufOut);
}
static object sqlite3OsDlSym(sqlite3_vfs pVfs, HANDLE pHdle, ref string zSym)
{
return pVfs.xDlSym(pVfs, pHdle, zSym);
}
static void sqlite3OsDlClose(sqlite3_vfs pVfs, HANDLE pHandle)
{
pVfs.xDlClose(pVfs, pHandle);
}
#endif
static int sqlite3OsRandomness(sqlite3_vfs pVfs, int nByte, byte[] zBufOut)
{
return pVfs.xRandomness(pVfs, nByte, zBufOut);
}
static int sqlite3OsSleep(sqlite3_vfs pVfs, int nMicro)
{
return pVfs.xSleep(pVfs, nMicro);
}
static int sqlite3OsCurrentTimeInt64(sqlite3_vfs pVfs, ref sqlite3_int64 pTimeOut)
{
int rc;
/* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
** method to get the current date and time if that method is available
** (if iVersion is 2 or greater and the function pointer is not NULL) and
** will fall back to xCurrentTime() if xCurrentTimeInt64() is
** unavailable.
*/
if (pVfs.iVersion >= 2 && pVfs.xCurrentTimeInt64 != null)
{
rc = pVfs.xCurrentTimeInt64(pVfs, ref pTimeOut);
}
else
{
double r = 0;
rc = pVfs.xCurrentTime(pVfs, ref r);
pTimeOut = (sqlite3_int64)(r * 86400000.0);
}
return rc;
}
static int sqlite3OsOpenMalloc(
ref sqlite3_vfs pVfs,
string zFile,
ref sqlite3_file ppFile,
int flags,
ref int pOutFlags
)
{
int rc = SQLITE_NOMEM;
sqlite3_file pFile;
pFile = new sqlite3_file(); //sqlite3Malloc(ref pVfs.szOsFile);
if (pFile != null)
{
rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, ref pOutFlags);
if (rc != SQLITE_OK)
{
pFile = null; // was sqlite3DbFree(db,ref pFile);
}
else
{
ppFile = pFile;
}
}
return rc;
}
static int sqlite3OsCloseFree(sqlite3_file pFile)
{
int rc = SQLITE_OK;
Debug.Assert(pFile != null);
rc = sqlite3OsClose(pFile);
//sqlite3_free( ref pFile );
return rc;
}
/*
** This function is a wrapper around the OS specific implementation of
** sqlite3_os_init(). The purpose of the wrapper is to provide the
** ability to simulate a malloc failure, so that the handling of an
** error in sqlite3_os_init() by the upper layers can be tested.
*/
static int sqlite3OsInit()
{
//void *p = sqlite3_malloc(10);
//if( p==null ) return SQLITE_NOMEM;
//sqlite3_free(ref p);
return sqlite3_os_init();
}
/*
** The list of all registered VFS implementations.
*/
static sqlite3_vfs vfsList;
//#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
/*
** Locate a VFS by name. If no name is given, simply return the
** first VFS on the list.
*/
static bool isInit = false;
static sqlite3_vfs sqlite3_vfs_find(string zVfs)
{
sqlite3_vfs pVfs = null;
#if SQLITE_THREADSAFE
sqlite3_mutex mutex;
#endif
#if !SQLITE_OMIT_AUTOINIT
int rc = sqlite3_initialize();
if (rc != 0)
return null;
#endif
#if SQLITE_THREADSAFE
mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
sqlite3_mutex_enter(mutex);
for (pVfs = vfsList; pVfs != null; pVfs = pVfs.pNext)
{
if (zVfs == null || zVfs == "")
break;
if (zVfs == pVfs.zName)
break; //strcmp(zVfs, pVfs.zName) == null) break;
}
sqlite3_mutex_leave(mutex);
return pVfs;
}
/*
** Unlink a VFS from the linked list
*/
static void vfsUnlink(sqlite3_vfs pVfs)
{
Debug.Assert(sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)));
if (pVfs == null)
{
/* No-op */
}
else if (vfsList == pVfs)
{
vfsList = pVfs.pNext;
}
else if (vfsList != null)
{
sqlite3_vfs p = vfsList;
while (p.pNext != null && p.pNext != pVfs)
{
p = p.pNext;
}
if (p.pNext == pVfs)
{
p.pNext = pVfs.pNext;
}
}
}
/*
** Register a VFS with the system. It is harmless to register the same
** VFS multiple times. The new VFS becomes the default if makeDflt is
** true.
*/
static int sqlite3_vfs_register(sqlite3_vfs pVfs, int makeDflt)
{
sqlite3_mutex mutex;
#if !SQLITE_OMIT_AUTOINIT
int rc = sqlite3_initialize();
if (rc != 0)
return rc;
#endif
mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
sqlite3_mutex_enter(mutex);
vfsUnlink(pVfs);
if (makeDflt != 0 || vfsList == null)
{
pVfs.pNext = vfsList;
vfsList = pVfs;
}
else
{
pVfs.pNext = vfsList.pNext;
vfsList.pNext = pVfs;
}
Debug.Assert(vfsList != null);
sqlite3_mutex_leave(mutex);
return SQLITE_OK;
}
/*
** Unregister a VFS so that it is no longer accessible.
*/
static int sqlite3_vfs_unregister(sqlite3_vfs pVfs)
{
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
sqlite3_mutex_enter(mutex);
vfsUnlink(pVfs);
sqlite3_mutex_leave(mutex);
return SQLITE_OK;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>CampaignSimulation</c> resource.</summary>
public sealed partial class CampaignSimulationName : gax::IResourceName, sys::IEquatable<CampaignSimulationName>
{
/// <summary>The possible contents of <see cref="CampaignSimulationName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </summary>
CustomerCampaignTypeModificationMethodStartDateEndDate = 1,
}
private static gax::PathTemplate s_customerCampaignTypeModificationMethodStartDateEndDate = new gax::PathTemplate("customers/{customer_id}/campaignSimulations/{campaign_id_type_modification_method_start_date_end_date}");
/// <summary>Creates a <see cref="CampaignSimulationName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CampaignSimulationName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CampaignSimulationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CampaignSimulationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CampaignSimulationName"/> with the pattern
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modificationMethodId">
/// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CampaignSimulationName"/> constructed from the provided ids.</returns>
public static CampaignSimulationName FromCustomerCampaignTypeModificationMethodStartDateEndDate(string customerId, string campaignId, string typeId, string modificationMethodId, string startDateId, string endDateId) =>
new CampaignSimulationName(ResourceNameType.CustomerCampaignTypeModificationMethodStartDateEndDate, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), typeId: gax::GaxPreconditions.CheckNotNullOrEmpty(typeId, nameof(typeId)), modificationMethodId: gax::GaxPreconditions.CheckNotNullOrEmpty(modificationMethodId, nameof(modificationMethodId)), startDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(startDateId, nameof(startDateId)), endDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(endDateId, nameof(endDateId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignSimulationName"/> with pattern
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modificationMethodId">
/// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignSimulationName"/> with pattern
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </returns>
public static string Format(string customerId, string campaignId, string typeId, string modificationMethodId, string startDateId, string endDateId) =>
FormatCustomerCampaignTypeModificationMethodStartDateEndDate(customerId, campaignId, typeId, modificationMethodId, startDateId, endDateId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignSimulationName"/> with pattern
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modificationMethodId">
/// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignSimulationName"/> with pattern
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </returns>
public static string FormatCustomerCampaignTypeModificationMethodStartDateEndDate(string customerId, string campaignId, string typeId, string modificationMethodId, string startDateId, string endDateId) =>
s_customerCampaignTypeModificationMethodStartDateEndDate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(typeId, nameof(typeId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(modificationMethodId, nameof(modificationMethodId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(startDateId, nameof(startDateId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(endDateId, nameof(endDateId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignSimulationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="campaignSimulationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CampaignSimulationName"/> if successful.</returns>
public static CampaignSimulationName Parse(string campaignSimulationName) => Parse(campaignSimulationName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignSimulationName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignSimulationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CampaignSimulationName"/> if successful.</returns>
public static CampaignSimulationName Parse(string campaignSimulationName, bool allowUnparsed) =>
TryParse(campaignSimulationName, allowUnparsed, out CampaignSimulationName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignSimulationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="campaignSimulationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignSimulationName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string campaignSimulationName, out CampaignSimulationName result) =>
TryParse(campaignSimulationName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignSimulationName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignSimulationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignSimulationName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string campaignSimulationName, bool allowUnparsed, out CampaignSimulationName result)
{
gax::GaxPreconditions.CheckNotNull(campaignSimulationName, nameof(campaignSimulationName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignTypeModificationMethodStartDateEndDate.TryParseName(campaignSimulationName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', '~', '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCampaignTypeModificationMethodStartDateEndDate(resourceName[0], split1[0], split1[1], split1[2], split1[3], split1[4]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(campaignSimulationName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private CampaignSimulationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string customerId = null, string endDateId = null, string modificationMethodId = null, string startDateId = null, string typeId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignId = campaignId;
CustomerId = customerId;
EndDateId = endDateId;
ModificationMethodId = modificationMethodId;
StartDateId = startDateId;
TypeId = typeId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CampaignSimulationName"/> class from the component parts of
/// pattern
/// <c>
/// customers/{customer_id}/campaignSimulations/{campaign_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modificationMethodId">
/// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param>
public CampaignSimulationName(string customerId, string campaignId, string typeId, string modificationMethodId, string startDateId, string endDateId) : this(ResourceNameType.CustomerCampaignTypeModificationMethodStartDateEndDate, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), typeId: gax::GaxPreconditions.CheckNotNullOrEmpty(typeId, nameof(typeId)), modificationMethodId: gax::GaxPreconditions.CheckNotNullOrEmpty(modificationMethodId, nameof(modificationMethodId)), startDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(startDateId, nameof(startDateId)), endDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(endDateId, nameof(endDateId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>EndDate</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string EndDateId { get; }
/// <summary>
/// The <c>ModificationMethod</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string ModificationMethodId { get; }
/// <summary>
/// The <c>StartDate</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string StartDateId { get; }
/// <summary>
/// The <c>Type</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TypeId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCampaignTypeModificationMethodStartDateEndDate: return s_customerCampaignTypeModificationMethodStartDateEndDate.Expand(CustomerId, $"{CampaignId}~{TypeId}~{ModificationMethodId}~{StartDateId}~{EndDateId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CampaignSimulationName);
/// <inheritdoc/>
public bool Equals(CampaignSimulationName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CampaignSimulationName a, CampaignSimulationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CampaignSimulationName a, CampaignSimulationName b) => !(a == b);
}
public partial class CampaignSimulation
{
/// <summary>
/// <see cref="CampaignSimulationName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CampaignSimulationName ResourceNameAsCampaignSimulationName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CampaignSimulationName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* 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.Reflection;
using System.Security.Cryptography;
using System.Text;
using MindTouch.Security.Cryptography;
using MindTouch.Tasking;
using MindTouch.Web;
using MindTouch.Xml;
using Autofac;
using Autofac.Builder;
namespace MindTouch.Dream {
using Yield = IEnumerator<IYield>;
/// <summary>
/// Base class for easily creating <see cref="IDreamService"/> implementations.
/// </summary>
[DreamServiceConfig("uri.self", "uri", "Uri for current service (provided by Host).")]
[DreamServiceConfig("uri.log", "uri?", "Uri for logging service.")]
[DreamServiceConfig("apikey", "string?", "Key to access protected features of the service.")]
[DreamServiceConfig("service-license", "string?", "signed service-license")]
public abstract class DreamService : IDreamService {
//--- Class Fields ---
private static log4net.ILog _log = LogUtils.CreateLog();
//--- Class Methods ---
/// <summary>
/// Create a service blueprint from reflection and attribute meta-data for an <see cref="IDreamService"/> implementation.
/// </summary>
/// <param name="type">Type of examine.</param>
/// <returns>Xml formatted blueprint.</returns>
public static XDoc CreateServiceBlueprint(Type type) {
if(type == null) {
throw new ArgumentNullException("type");
}
XDoc result = new XDoc("blueprint");
// load assembly
Dictionary<string, string> assemblySettings = new Dictionary<string, string>(StringComparer.Ordinal);
string[] assemblyParts = type.Assembly.FullName.Split(',');
foreach(string parts in assemblyParts) {
string[] assign = parts.Trim().Split(new char[] { '=' }, 2);
if(assign.Length == 2) {
assemblySettings[assign[0].Trim()] = assign[1].Trim();
}
}
result.Start("assembly");
foreach(KeyValuePair<string, string> entry in assemblySettings) {
result.Attr(entry.Key, entry.Value);
}
result.Value(assemblyParts[0]);
result.End();
result.Elem("class", type.FullName);
// retrieve DreamService attribute on class definition
DreamServiceAttribute serviceAttrib = (DreamServiceAttribute)Attribute.GetCustomAttribute(type, typeof(DreamServiceAttribute), false);
result.Elem("name", serviceAttrib.Name);
result.Elem("copyright", serviceAttrib.Copyright);
result.Elem("info", serviceAttrib.Info);
// retrieve DreamServiceUID attributes
foreach(XUri sid in serviceAttrib.GetSIDAsUris()) {
result.Elem("sid", sid);
}
// check if service has blueprint settings
foreach(DreamServiceBlueprintAttribute blueprintAttrib in Attribute.GetCustomAttributes(type, typeof(DreamServiceBlueprintAttribute), true)) {
result.InsertValueAt(blueprintAttrib.Name, blueprintAttrib.Value);
}
// check if service has configuration information
DreamServiceConfigAttribute[] configAttributes = (DreamServiceConfigAttribute[])Attribute.GetCustomAttributes(type, typeof(DreamServiceConfigAttribute), true);
if(!ArrayUtil.IsNullOrEmpty(configAttributes)) {
result.Start("configuration");
foreach(DreamServiceConfigAttribute configAttr in configAttributes) {
result.Start("entry")
.Elem("name", configAttr.Name)
.Elem("valuetype", configAttr.ValueType)
.Elem("description", configAttr.Description)
.End();
}
result.End();
}
// retrieve DreamFeature attributes on method definitions
result.Start("features");
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach(MethodInfo method in methods) {
// retrieve feature description
Attribute[] featureAttributes = Attribute.GetCustomAttributes(method, typeof(DreamFeatureAttribute), false);
if(featureAttributes.Length == 0) {
continue;
}
if(method.IsGenericMethod || method.IsGenericMethodDefinition) {
throw new NotSupportedException(string.Format("generic methods are not supported ({0})", method.Name));
}
ParameterInfo[] parameters = method.GetParameters();
// determine access level
string access;
if(method.IsPublic) {
access = "public";
} else if(method.IsAssembly) {
access = "internal";
} else if(method.IsPrivate || method.IsFamily) {
access = "private";
} else {
throw new NotSupportedException(string.Format("access level is not supported ({0})", method.Name));
}
// retrieve feature parameter descriptions, filters, prologues, and epilogues
Attribute[] paramAttributes = Attribute.GetCustomAttributes(method, typeof(DreamFeatureParamAttribute), false);
var pathAttributes = method.GetParameters().Select(p => {
var attr = (PathAttribute)p.GetCustomAttributes(typeof(PathAttribute), false).FirstOrDefault();
return ((attr != null) && (attr.Name == null)) ? new PathAttribute { Description = attr.Description, Name = p.Name } : attr;
}).Where(p => p != null);
var queryAttributes = method.GetParameters().Select(q => {
var attr = (QueryAttribute)q.GetCustomAttributes(typeof(QueryAttribute), false).FirstOrDefault();
return ((attr != null) && (attr.Name == null)) ? new QueryAttribute { Description = attr.Description, Name = q.Name } : attr;
}).Where(q => q != null);
Attribute[] statusAttributes = Attribute.GetCustomAttributes(method, typeof(DreamFeatureStatusAttribute), false);
foreach(DreamFeatureAttribute featureAttrib in featureAttributes) {
result.Start("feature");
result.Elem("obsolete", featureAttrib.Obsolete);
result.Elem("pattern", featureAttrib.Pattern);
result.Elem("description", featureAttrib.Description);
string info = featureAttrib.Info ?? serviceAttrib.Info;
if(info != null) {
result.Elem("info", info);
}
result.Elem("method", method.Name);
// add parameter descriptions (as seen on the method definition)
foreach(DreamFeatureParamAttribute paramAttrib in paramAttributes) {
result.Start("param");
result.Elem("name", paramAttrib.Name);
if(!string.IsNullOrEmpty(paramAttrib.ValueType)) {
result.Elem("valuetype", paramAttrib.ValueType);
}
result.Elem("description", paramAttrib.Description);
result.End();
}
// add parameter descriptions (as seen on the method parameters)
foreach(PathAttribute pathAttrib in pathAttributes) {
result.Start("param")
.Elem("name", "{" + pathAttrib.Name + "}")
.Elem("description", pathAttrib.Description)
.End();
}
// add parameter descriptions (as seen on the method parameters)
foreach(QueryAttribute queryAttrib in queryAttributes) {
result.Start("param")
.Elem("name", queryAttrib.Name)
.Elem("description", queryAttrib.Description)
.End();
}
// add status codes
foreach(DreamFeatureStatusAttribute paramAttrib in statusAttributes) {
result.Start("status");
result.Attr("value", (int)paramAttrib.Status);
result.Value(paramAttrib.Description);
result.End();
}
// add access level
result.Elem("access", access);
result.End();
}
}
result.End();
return result.EndAll();
}
//--- Fields ---
private Plug _pubsub;
private IDreamEnvironment _env;
private XDoc _config = XDoc.Empty;
private Plug _self;
private Plug _storage;
private Plug _owner;
private XDoc _blueprint;
private readonly DreamCookieJar _cookies = new DreamCookieJar();
private readonly string _privateAccessKey;
private readonly string _internalAccessKey;
private string _apikey;
private string _license;
private TaskTimerFactory _timerFactory;
//--- Constructors ---
/// <summary>
/// Base constructor, initializing private and internal access keys.
/// </summary>
protected DreamService() {
// generate access keys
_privateAccessKey = StringUtil.CreateAlphaNumericKey(32);
_internalAccessKey = StringUtil.CreateAlphaNumericKey(32);
}
//--- Properties ---
/// <summary>
/// Authentication realm for service (default: dream).
/// </summary>
public virtual string AuthenticationRealm { get { return "dream"; } }
/// <summary>
/// Service configuration.
/// </summary>
public XDoc Config { get { return _config; } }
/// <summary>
/// <see cref="Plug"/> for hosting environment.
/// </summary>
public Plug Env { get { return _env.Self; } }
/// <summary>
/// Service <see cref="Plug"/>.
/// </summary>
public Plug Self { get { return _self; } }
/// <summary>
/// <see cref="Plug"/> for service that created this service.
/// </summary>
public Plug Owner { get { return _owner; } }
/// <summary>
/// <see cref="Plug"/> for Storage Service.
/// </summary>
public Plug Storage { get { return _storage; } }
/// <summary>
/// <see cref="Plug"/> for PubSub Service.
/// </summary>
public Plug PubSub {
get { return _pubsub; }
protected set { _pubsub = value; }
}
/// <summary>
/// Service Identifier used to create this instance.
/// </summary>
public XUri SID { get { return _config["sid"].AsUri ?? _config["class"].AsUri; } }
/// <summary>
/// Service blueprint.
/// </summary>
public XDoc Blueprint { get { return _blueprint; } }
/// <summary>
/// Service cookie jar.
/// </summary>
public DreamCookieJar Cookies { get { return _cookies; } }
/// <summary>
/// Service license (if one exists).
/// </summary>
public string ServiceLicense { get { return _license; } }
/// <summary>
/// Prologue request stages to be executed before a Feature is executed.
/// </summary>
public virtual DreamFeatureStage[] Prologues { get { return null; } }
/// <summary>
/// Epilogue request stages to be executed after a Feature has completed.
/// </summary>
public virtual DreamFeatureStage[] Epilogues { get { return null; } }
/// <summary>
/// Exception translators given an opportunity to rewrite an exception before it is returned to the initiator of a request.
/// </summary>
public virtual ExceptionTranslator[] ExceptionTranslators { get { return null; } }
/// <summary>
/// Access Key for using internal features.
/// </summary>
protected string InternalAccessKey { get { return _internalAccessKey; } }
/// <summary>
/// Access Key for using any feature.
/// </summary>
protected string PrivateAccessKey { get { return _privateAccessKey; } }
/// <summary>
/// <see langword="True"/> if the service has been started.
/// </summary>
protected bool IsStarted { get { return !_config.IsEmpty; } }
/// <summary>
/// <see cref="TaskTimerFactory"/> associated with this service.
/// </summary>
/// <remarks>
/// Governs the lifecycle of TaskTimers created during the lifecycle of the service.
/// </remarks>
protected TaskTimerFactory TimerFactory { get { return _timerFactory; } }
//--- Features ---
/// <summary>
/// <see cref="DreamFeature"/> for retrieve the service configuration.
/// </summary>
/// <param name="context">Feature request context.</param>
/// <param name="request">Request message.</param>
/// <param name="response">Response synchronization handle.</param>
/// <returns>Iterator used by <see cref="Coroutine"/> to invoke the feature.</returns>
[DreamFeature("GET:@config", "Retrieve service configuration", Info = "http://developer.mindtouch.com/Dream/Reference/General/Generic_Features")]
protected virtual Yield GetConfig(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
if(IsStarted) {
response.Return(DreamMessage.Ok(Config));
} else {
throw new DreamNotFoundException("service not started");
}
yield break;
}
/// <summary>
/// <see cref="DreamFeature"/> for initializing the service with its configuration.
/// </summary>
/// <remarks>
/// This feature is responsible for calling <see cref="Start(MindTouch.Xml.XDoc,MindTouch.Tasking.Result)"/>.
/// </remarks>
/// <param name="context">Feature request context.</param>
/// <param name="request">Request message.</param>
/// <param name="response">Response synchronization handle.</param>
/// <returns>Iterator used by <see cref="Coroutine"/> to invoke the feature.</returns>
[DreamFeature("PUT:@config", "Initialize service", Info = "http://developer.mindtouch.com/Dream/Reference/General/Generic_Features")]
protected virtual Yield PutConfig(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
XDoc config = request.ToDocument();
if(config.Name != "config") {
throw new DreamBadRequestException("bad document type");
}
if(IsStarted) {
throw new DreamBadRequestException("service must be stopped first");
}
_timerFactory = TaskTimerFactory.Create(this);
// configure service container
var components = config["components"];
var servicecontainer = _env.CreateServiceContainer(this);
var builder = new ContainerBuilder();
builder.Register(_timerFactory).ExternallyOwned();
if(!components.IsEmpty) {
_log.Debug("registering service level module");
builder.RegisterModule(new XDocAutofacContainerConfigurator(components, DreamContainerScope.Service));
}
builder.Build(servicecontainer);
// call container-less start (which contains shared start logic)
yield return Coroutine.Invoke(Start, request.ToDocument(), new Result());
// call start with container for sub-classes that want to resolve instances at service start
yield return Coroutine.Invoke(Start, config, servicecontainer, new Result());
response.Return(DreamMessage.Ok(new XDoc("service-info")
.Start("private-key")
.Add(DreamCookie.NewSetCookie("service-key", PrivateAccessKey, Self.Uri).AsSetCookieDocument)
.End()
.Start("internal-key")
.Add(DreamCookie.NewSetCookie("service-key", InternalAccessKey, Self.Uri).AsSetCookieDocument)
.End()
));
}
/// <summary>
/// <see cref="DreamFeature"/> for deinitializing the service.
/// </summary>
/// <param name="context">Feature request context.</param>
/// <param name="request">Request message.</param>
/// <param name="response">Response synchronization handle.</param>
/// <returns>Iterator used by <see cref="Coroutine"/> to invoke the feature.</returns>
[DreamFeature("DELETE:@config", "Deinitialize service", Info = "http://developer.mindtouch.com/Dream/Reference/General/Generic_Features")]
protected virtual Yield DeleteConfig(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
if(IsStarted) {
_timerFactory.Dispose();
yield return Coroutine.Invoke(Stop, new Result());
}
response.Return(DreamMessage.Ok());
yield break;
}
/// <summary>
/// <see cref="DreamFeature"/> for retrieving the service blueprint.
/// </summary>
/// <param name="context">Feature request context.</param>
/// <param name="request">Request message.</param>
/// <param name="response">Response synchronization handle.</param>
/// <returns>Iterator used by <see cref="Coroutine"/> to invoke the feature.</returns>
[DreamFeature("GET:@blueprint", "Retrieve service blueprint", Info = "http://developer.mindtouch.com/Dream/Reference/General/Generic_Features")]
public virtual Yield GetServiceBlueprint(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
response.Return(DreamMessage.Ok(Blueprint));
yield break;
}
/// <summary>
/// <see cref="DreamFeature"/> for retrieving the service description.
/// </summary>
/// <param name="context">Feature request context.</param>
/// <param name="request">Request message.</param>
/// <param name="response">Response synchronization handle.</param>
/// <returns>Iterator used by <see cref="Coroutine"/> to invoke the feature.</returns>
[DreamFeature("GET:@about", "Retrieve service description", Info = "http://developer.mindtouch.com/Dream/Reference/General/Generic_Features")]
public virtual Yield GetServiceInfo(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
XDoc blueprint = Blueprint;
string title = blueprint["name"].AsText ?? "Service Blueprint";
XDoc result = new XDoc("html").Attr("xmlns", "http://www.w3.org/1999/xhtml")
.Start("head")
.Elem("title", title)
.Start("meta").Attr("http-equiv", "content-type").Attr("content", "text/html;charset=utf-8").End()
.Start("meta").Attr("http-equiv", "Content-Style-Type").Attr("content", "text/css").End()
.End();
if(blueprint.IsEmpty) {
result.Elem("body", "Missing service blueprint");
} else {
result.Start("body")
.Elem("h1", title)
.Start("p")
.Value(blueprint["copyright"].Contents)
.Value(" ")
.Start("a").Attr("href", blueprint["info"].Contents).Value("(more)").End()
.Value(" ")
.Start("a").Attr("href", Self.Uri.At("@blueprint").Path).Value("(blueprint)").End()
.End();
// show configuration information
XDoc config = blueprint["configuration"];
if(!config.IsEmpty) {
result.Elem("h2", "Configuration");
result.Start("ul");
foreach(XDoc entry in config["entry"]) {
result.Start("li");
if(entry["valuetype"].Contents != string.Empty) {
result.Value(string.Format("{0} = {1} : {2}", entry["name"].Contents, entry["valuetype"].Contents, entry["description"].Contents));
} else {
result.Value(string.Format("{0} : {1}", entry["name"].Contents, entry["description"].Contents));
}
result.End();
}
result.End();
}
// sort features by signature then verb
blueprint["features"].Sort(delegate(XDoc first, XDoc second) {
string[] firstPattern = first["pattern"].Contents.Split(new char[] { ':' }, 2);
string[] secondPattern = second["pattern"].Contents.Split(new char[] { ':' }, 2);
int cmp = StringUtil.CompareInvariantIgnoreCase(firstPattern[1], secondPattern[1]);
if(cmp != 0) {
return cmp;
}
return StringUtil.CompareInvariant(firstPattern[0], secondPattern[0]);
});
// display features
XDoc features = blueprint["features/feature"];
if(!features.IsEmpty) {
result.Elem("h2", "Features");
List<string> modifiers = new List<string>();
foreach(XDoc feature in features) {
string modifier;
modifiers.Clear();
// add modifiers
modifier = feature["access"].AsText;
if(modifier != null) {
modifiers.Add(modifier);
}
modifier = feature["obsolete"].AsText;
if(modifier != null) {
modifiers.Add("OBSOLETE => " + modifier);
}
if(modifiers.Count > 0) {
modifier = " (" + string.Join(", ", modifiers.ToArray()) + ")";
} else {
modifier = string.Empty;
}
// check if feature has GET verb and no path parameters
string pattern = feature["pattern"].Contents;
if(StringUtil.StartsWithInvariantIgnoreCase(pattern, Verb.GET + ":") && (pattern.IndexOfAny(new char[] { '{', '*', '?' }) == -1)) {
string[] parts = pattern.Split(new char[] { ':' }, 2);
result.Start("h3")
.Start("a").Attr("href", context.AsPublicUri(Self.Uri.AtPath(parts[1])))
.Value(feature["pattern"].Contents)
.End()
.Value(modifier)
.End();
} else {
result.Elem("h3", feature["pattern"].Contents + modifier);
}
result.Start("p")
.Value(feature["description"].Contents)
.Value(" ")
.Start("a").Attr("href", feature["info"].Contents).Value("(more)").End();
XDoc paramlist = feature["param"];
if(!paramlist.IsEmpty) {
result.Start("ul");
foreach(XDoc param in paramlist) {
result.Start("li");
if(param["valuetype"].Contents != string.Empty) {
result.Value(string.Format("{0} = {1} : {2}", param["name"].Contents, param["valuetype"].Contents, param["description"].Contents));
} else {
result.Value(string.Format("{0} : {1}", param["name"].Contents, param["description"].Contents));
}
result.End();
}
result.End();
}
result.End();
}
}
}
response.Return(DreamMessage.Ok(MimeType.HTML, result.ToString()));
yield break;
}
/// <summary>
/// <see cref="DreamFeature"/> for deleting the service (separate from deinitializing it.)
/// </summary>
/// <param name="context">Feature request context.</param>
/// <param name="request">Request message.</param>
/// <param name="response">Response synchronization handle.</param>
/// <returns>Iterator used by <see cref="Coroutine"/> to invoke the feature.</returns>
[DreamFeature("DELETE:", "Stop service", Info = "http://developer.mindtouch.com/Dream/Reference/General/Generic_Features")]
[DreamFeatureStatus(DreamStatus.Ok, "Request completed successfully")]
[DreamFeatureStatus(DreamStatus.Forbidden, "Insufficient permission")]
protected virtual Yield DeleteService(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
yield return Env.At("stop").Post(new XDoc("service").Elem("uri", Self), new Result<DreamMessage>(TimeSpan.MaxValue)).CatchAndLog(_log);
response.Return(DreamMessage.Ok());
}
[DreamFeature("POST:@grants", "Adds a grant to this service for accessing another service.", Info = "http://developer.mindtouch.com/Dream/Reference/General/Generic_Features")]
internal Yield PostGrant(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
lock(Cookies) {
Cookies.Update(DreamCookie.ParseAllSetCookieNodes(request.ToDocument()), null);
}
response.Return(DreamMessage.Ok());
yield break;
}
//--- Methods ---
/// <summary>
/// Initialize a service instance.
/// </summary>
/// <param name="env">Host environment.</param>
/// <param name="blueprint">Service blueprint.</param>
public virtual void Initialize(IDreamEnvironment env, XDoc blueprint) {
if(env == null) {
throw new ArgumentNullException("env");
}
if(blueprint == null) {
throw new ArgumentNullException("blueprint");
}
_env = env;
_blueprint = blueprint;
}
/// <summary>
/// Perform startup configuration of a service instance.
/// </summary>
/// <remarks>
/// Should not be manually invoked and should only be overridden if <see cref="Start(MindTouch.Xml.XDoc,MindTouch.Tasking.Result)"/> isn't already overriden.
/// </remarks>
/// <param name="config">Service configuration.</param>
/// <param name="serviceContainer">Service level IoC container</param>
/// <param name="result">Synchronization handle for coroutine invocation.</param>
/// <returns>Iterator used by <see cref="Coroutine"/> execution environment.</returns>
protected virtual Yield Start(XDoc config, IContainer serviceContainer, Result result) {
result.Return();
yield break;
}
/// <summary>
/// Perform startup configuration of a service instance.
/// </summary>
/// <remarks>
/// Should not be manually invoked and should only be overridden if <see cref="Start(MindTouch.Xml.XDoc,Autofac.IContainer,MindTouch.Tasking.Result)"/> isn't already overriden.
/// </remarks>
/// <param name="config">Service configuration.</param>
/// <param name="result">Synchronization handle for coroutine invocation.</param>
/// <returns>Iterator used by <see cref="Coroutine"/> execution environment.</returns>
protected virtual Yield Start(XDoc config, Result result) {
Result<DreamMessage> res;
// store configuration and uri
_config = config;
_self = Plug.New(config["uri.self"].AsUri);
if(_self == null) {
throw new ArgumentNullException("uri.self");
}
_owner = Plug.New(config["uri.owner"].AsUri);
// check for api-key settings
_apikey = config["apikey"].AsText;
// process 'set-cookie' entries
List<DreamCookie> setCookies = DreamCookie.ParseAllSetCookieNodes(config["set-cookie"]);
if(setCookies.Count > 0) {
Cookies.Update(setCookies, null);
}
// grant private access key to self, host, and owner
//string privateAcccessCookie = HttpUtil.RenderSetCookieHeader(HttpUtil.SetCookie("service-key", PrivateAccessKey, Self.Uri.Path, Self.Uri.Host, DateTime.MaxValue));
//Cookies.Update(HttpUtil.ParseSetCookieHeader(privateAcccessCookie), null);
DreamCookie privateAcccessCookie = DreamCookie.NewSetCookie("service-key", PrivateAccessKey, Self.Uri);
Cookies.Update(privateAcccessCookie, null);
yield return Env.At("@grants").Post(DreamMessage.Ok(privateAcccessCookie.AsSetCookieDocument), new Result<DreamMessage>(TimeSpan.MaxValue));
if(Owner != null) {
yield return res = Owner.At("@grants").Post(DreamMessage.Ok(privateAcccessCookie.AsSetCookieDocument), new Result<DreamMessage>(TimeSpan.MaxValue));
if(!res.Value.IsSuccessful) {
throw new ArgumentException("unexpected failure setting grants on owner service");
}
}
// check if this service requires a service-license to work
if(this is IDreamServiceLicense) {
string service_license = config["service-license"].AsText;
if(string.IsNullOrEmpty(service_license)) {
throw new DreamAbortException(DreamMessage.LicenseRequired("service-license missing"));
}
// extract public RSA key for validation
RSACryptoServiceProvider public_key = RSAUtil.ProviderFrom(GetType().Assembly);
if(public_key == null) {
throw new DreamAbortException(DreamMessage.InternalError("service assembly invalid"));
}
// validate the service-license
_license = null;
if(service_license != null) {
Dictionary<string, string> values;
try {
// parse service-license
values = HttpUtil.ParseNameValuePairs(service_license);
if(!Encoding.UTF8.GetBytes(service_license.Substring(0, service_license.LastIndexOf(','))).VerifySignature(values["dsig"], public_key)) {
throw new DreamAbortException(DreamMessage.InternalError("invalid service-license (1)"));
}
// check if the SID matches
string sid;
if(!values.TryGetValue("sid", out sid) || !SID.HasPrefix(XUri.TryParse(sid), true)) {
throw new DreamAbortException(DreamMessage.InternalError("invalid service-license (2)"));
}
_license = service_license;
} catch(Exception e) {
// unexpected error, blame it on the license
if(e is DreamAbortException) {
throw;
} else {
throw new DreamAbortException(DreamMessage.InternalError("corrupt service-license (1)"));
}
}
// validate expiration date
string expirationtext;
if(values.TryGetValue("expire", out expirationtext)) {
try {
DateTime expiration = DateTime.Parse(expirationtext);
if(expiration < DateTime.UtcNow) {
_license = null;
}
} catch(Exception e) {
_license = null;
// unexpected error, blame it on the license
if(e is DreamAbortException) {
throw;
} else {
throw new DreamAbortException(DreamMessage.InternalError("corrupt service-license (2)"));
}
}
}
}
// check if a license was assigned
if(_license == null) {
throw new DreamAbortException(DreamMessage.LicenseRequired("service-license has expired"));
}
} else {
config["service-license"].RemoveAll();
}
// create built-in services
_storage = Plug.New(config["uri.storage"].AsUri);
_pubsub = Plug.New(config["uri.pubsub"].AsUri);
// done
_log.Debug("Start");
result.Return();
}
/// <summary>
/// Perform shutdown cleanup of a service instance.
/// </summary>
/// <remarks>
/// Should not be manually invoked.
/// </remarks>
/// <param name="result">Synchronization handle for coroutine invocation.</param>
/// <returns>Iterator used by <see cref="Coroutine"/> execution environment.</returns>
protected virtual Yield Stop(Result result) {
// ungrant owner and parent, otherwise they end up with thousands of grants
DreamCookie cookie = DreamCookie.NewSetCookie("service-key", string.Empty, Self.Uri, DateTime.UtcNow);
// ignore if these operations fail since we're shutting down anyway
yield return Env.At("@grants").Post(DreamMessage.Ok(cookie.AsSetCookieDocument), new Result<DreamMessage>(TimeSpan.MaxValue)).CatchAndLog(_log);
if(Owner != null) {
yield return Owner.At("@grants").Post(DreamMessage.Ok(cookie.AsSetCookieDocument), new Result<DreamMessage>(TimeSpan.MaxValue)).CatchAndLog(_log);
}
_log.Debug("Stop");
// reset fields
_self = null;
_owner = null;
_storage = null;
_config = XDoc.Empty;
_apikey = null;
_cookies.Clear();
_license = null;
_env.DisposeServiceContainer(this);
// we're done
result.Return();
}
/// <summary>
/// Create a service as a child of the current service.
/// </summary>
/// <param name="path">Relative path to locate new service at.</param>
/// <param name="sid">Service Identifier.</param>
/// <param name="config">Service configuration.</param>
/// <param name="result">The result instance to be returned by this methods.</param>
/// <returns>Synchronization handle for this method's invocation.</returns>
protected Result<Plug> CreateService(string path, string sid, XDoc config, Result<Plug> result) {
return Coroutine.Invoke(CreateService_Helper, path, sid, config ?? new XDoc("config"), result);
}
private Yield CreateService_Helper(string path, string sid, XDoc config, Result<Plug> result) {
if(path == null) {
throw new ArgumentNullException("path");
}
if(sid == null) {
throw new ArgumentNullException("sid");
}
if(config == null) {
throw new ArgumentNullException("config");
}
// check if we have a licensekey for the requested SID
string serviceLicense = TryGetServiceLicense(XUri.TryParse(sid) ?? XUri.Localhost);
// add parameters to config document
Plug plug = Self.AtPath(path);
config.Root
.Elem("path", plug.Uri.Path)
.Elem("sid", sid)
// add 'owner' and make sure we keep it in 'local://' format
.Elem("uri.owner", Self.Uri.ToString())
// add 'internal' access key
.Add(DreamCookie.NewSetCookie("service-key", InternalAccessKey, Self.Uri).AsSetCookieDocument)
// add optional 'service-license' token
.Elem("service-license", serviceLicense);
// inject parent apikey if apikey not defined
if(config["apikey"].IsEmpty) {
config.Root.Elem("apikey", _apikey);
}
// post to host to create service
Result<DreamMessage> res;
yield return res = Env.At("services").Post(config, new Result<DreamMessage>(TimeSpan.MaxValue));
if(!res.Value.IsSuccessful) {
if(res.Value.HasDocument) {
string message = res.Value.ToDocument()[".//message"].AsText.IfNullOrEmpty("unknown error");
throw new DreamResponseException(res.Value, string.Format("unable to initialize service ({0})", message));
} else {
throw new DreamResponseException(res.Value, string.Format("unable to initialize service ({0})", res.Value.ToText()));
}
}
result.Return(plug);
yield break;
}
/// <summary>
/// No-op hook for retrieving a service license string from its Service Identifier uri.
/// </summary>
/// <param name="sid">Service Identifier.</param>
/// <returns>Service license.</returns>
protected virtual string TryGetServiceLicense(XUri sid) {
return null;
}
/// <summary>
/// Determine the access appropriate for an incoming request.
/// </summary>
/// <param name="context">Request context.</param>
/// <param name="request">Request message.</param>
/// <returns>Access level for request.</returns>
public virtual DreamAccess DetermineAccess(DreamContext context, DreamMessage request) {
DreamMessage message = request;
// check if request has a service or api key
string key = DreamContext.Current.Uri.GetParam("apikey", null);
if(key == null) {
DreamCookie cookie = DreamCookie.GetCookie(message.Cookies, "service-key");
if(cookie != null) {
key = cookie.Value;
}
}
return DetermineAccess(context, key);
}
private Yield InServiceInvokeHandler(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
throw new InvalidOperationException("this feature should never be invoked");
}
/// <summary>
/// Invoke an action in the context of a service feature.
/// </summary>
/// <remarks>
/// Assumes that there exists a current <see cref="DreamContext"/> that belongs to a request to another feature of this service.
/// </remarks>
/// <param name="verb">Http verb.</param>
/// <param name="path">Feature path.</param>
/// <param name="handler">Action to perform in this context.</param>
/// <returns>Exception thrown by handler or null.</returns>
public Exception InvokeInServiceContext(string verb, string path, Action handler) {
if(handler == null) {
throw new ArgumentNullException("handler");
}
if(string.IsNullOrEmpty(verb)) {
throw new ArgumentNullException("verb");
}
if(path == null) {
throw new ArgumentNullException("path");
}
// create new new environment for execution
XUri uri = Self.AtPath(path);
DreamContext current = DreamContext.Current;
Exception e = TaskEnv.ExecuteNew(delegate {
DreamFeatureStage[] stages = new DreamFeatureStage[] {
new DreamFeatureStage("InServiceInvokeHandler", InServiceInvokeHandler, DreamAccess.Private)
};
// BUGBUGBUG (steveb): when invoking a remote function this way, we're are not running the proloques and epilogues, which leads to errors;
// also dream-access attributes are being ignored (i.e. 'public' vs. 'private')
DreamMessage message = DreamUtil.AppendHeadersToInternallyForwardedMessage(current.Request, DreamMessage.Ok());
var context = current.CreateContext(verb, uri, new DreamFeature(this, Self, 0, stages, verb, path), message);
context.AttachToCurrentTaskEnv();
// pass along host and public-uri information
handler();
}, TimerFactory);
return e;
}
/// <summary>
/// Check the service's response cache.
/// </summary>
/// <param name="key">Key to check.</param>
protected void CheckResponseCache(object key) {
_env.CheckResponseCache(this, key);
}
/// <summary>
/// Remove a key from the service's response cache
/// </summary>
/// <param name="key"></param>
protected void RemoveResponseCache(object key) {
_env.RemoveResponseCache(this, key);
}
/// <summary>
/// Clear out the service's response cache
/// </summary>
protected void EmptyResponseCache() {
_env.EmptyResponseCache(this);
}
/// <summary>
/// Provides a hook for overriding what access level the current request should be granted.
/// </summary>
/// <param name="context">Request context.</param>
/// <param name="key">Authorization key of request.</param>
/// <returns>Access level granted to the request.</returns>
protected virtual DreamAccess DetermineAccess(DreamContext context, string key) {
if(_env.IsDebugEnv) {
return DreamAccess.Private;
}
if(!string.IsNullOrEmpty(key) && (StringUtil.EqualsInvariant(key, _apikey))) {
return DreamAccess.Private;
}
if(key == InternalAccessKey) {
return DreamAccess.Internal;
}
if(key == PrivateAccessKey) {
return DreamAccess.Private;
}
return DreamAccess.Public;
}
/// <summary>
/// Provides a hook for overriding default authentication of incoming user credentials.
/// </summary>
/// <remarks>
/// Overriding methods should throw <see cref="DreamAbortException"/> if the user cannot be authenticated.
/// </remarks>
/// <param name="context">Request context.</param>
/// <param name="message">Request message.</param>
/// <param name="username">Request user.</param>
/// <param name="password">User password.</param>
protected void Authenticate(DreamContext context, DreamMessage message, out string username, out string password) {
if(!HttpUtil.GetAuthentication(context.Uri, message.Headers, out username, out password)) {
throw new DreamAbortException(DreamMessage.AccessDenied(AuthenticationRealm, "authentication failed"));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Scripting.Actions.Calls;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using AstUtils = Microsoft.Scripting.Ast.Utils;
namespace Microsoft.Scripting.Actions {
public partial class DefaultBinder : ActionBinder {
// TODO: Rename Call to Invoke, obsolete Call
// TODO: Invoke overloads should also take CallInfo objects to simplify use for languages which don't need CallSignature features.
/// <summary>
/// Provides default binding for performing a call on the specified meta objects.
/// </summary>
/// <param name="signature">The signature describing the call</param>
/// <param name="target">The meta object to be called.</param>
/// <param name="args">
/// Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction.
/// </param>
/// <returns>A MetaObject representing the call or the error.</returns>
public DynamicMetaObject Call(CallSignature signature, DynamicMetaObject target, params DynamicMetaObject[] args) {
return Call(signature, new DefaultOverloadResolverFactory(this), target, args);
}
/// <summary>
/// Provides default binding for performing a call on the specified meta objects.
/// </summary>
/// <param name="signature">The signature describing the call</param>
/// <param name="target">The meta object to be called.</param>
/// <param name="args">
/// Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction.
/// </param>
/// <param name="resolverFactory">Overload resolver factory.</param>
/// <returns>A MetaObject representing the call or the error.</returns>
public DynamicMetaObject Call(CallSignature signature, OverloadResolverFactory resolverFactory, DynamicMetaObject target, params DynamicMetaObject[] args) {
return Call(signature, null, resolverFactory, target, args);
}
/// <summary>
/// Provides default binding for performing a call on the specified meta objects.
/// </summary>
/// <param name="signature">The signature describing the call</param>
/// <param name="target">The meta object to be called.</param>
/// <param name="args">
/// Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction.
/// </param>
/// <param name="resolverFactory">Overload resolver factory.</param>
/// <param name="errorSuggestion">The result should the object be uncallable.</param>
/// <returns>A MetaObject representing the call or the error.</returns>
public DynamicMetaObject Call(CallSignature signature, DynamicMetaObject errorSuggestion, OverloadResolverFactory resolverFactory, DynamicMetaObject target, params DynamicMetaObject[] args) {
ContractUtils.RequiresNotNullItems(args, nameof(args));
ContractUtils.RequiresNotNull(resolverFactory, nameof(resolverFactory));
TargetInfo targetInfo = GetTargetInfo(target, args);
if (targetInfo != null) {
// we're calling a well-known MethodBase
DynamicMetaObject res = MakeMetaMethodCall(signature, resolverFactory, targetInfo);
if (res.Expression.Type.IsValueType) {
res = new DynamicMetaObject(
AstUtils.Convert(res.Expression, typeof(object)),
res.Restrictions
);
}
return res;
}
// we can't call this object
return errorSuggestion ?? MakeCannotCallRule(target, target.GetLimitType());
}
#region Method Call Rule
private DynamicMetaObject MakeMetaMethodCall(CallSignature signature, OverloadResolverFactory resolverFactory, TargetInfo targetInfo) {
BindingRestrictions restrictions = BindingRestrictions.Combine(targetInfo.Arguments).Merge(targetInfo.Restrictions);
if (targetInfo.Instance != null) {
restrictions = targetInfo.Instance.Restrictions.Merge(restrictions);
}
DynamicMetaObject[] args;
CallTypes callType;
if (targetInfo.Instance != null) {
args = ArrayUtils.Insert(targetInfo.Instance, targetInfo.Arguments);
callType = CallTypes.ImplicitInstance;
} else {
args = targetInfo.Arguments;
callType = CallTypes.None;
}
return CallMethod(resolverFactory.CreateOverloadResolver(args, signature, callType), targetInfo.Targets, restrictions);
}
#endregion
#region Target acquisition
/// <summary>
/// Gets a TargetInfo object for performing a call on this object.
///
/// If this object is a delegate we bind to the Invoke method.
/// If this object is a MemberGroup or MethodGroup we bind to the methods in the member group.
/// If this object is a BoundMemberTracker we bind to the methods with the bound instance.
/// If the underlying type has defined an operator Call method we'll bind to that method.
/// </summary>
private TargetInfo GetTargetInfo(DynamicMetaObject target, DynamicMetaObject[] args) {
Debug.Assert(target.HasValue);
object objTarget = target.Value;
return
TryGetDelegateTargets(target, args, objTarget as Delegate) ??
TryGetMemberGroupTargets(target, args, objTarget as MemberGroup) ??
TryGetMethodGroupTargets(target, args, objTarget as MethodGroup) ??
TryGetBoundMemberTargets(target, args, objTarget as BoundMemberTracker) ??
TryGetOperatorTargets(target, args, target);
}
/// <summary>
/// Binds to the methods in a method group.
/// </summary>
private static TargetInfo TryGetMethodGroupTargets(DynamicMetaObject target, DynamicMetaObject[] args, MethodGroup mthgrp) {
if (mthgrp == null)
return null;
List<MethodBase> foundTargets = new List<MethodBase>();
foreach (MethodTracker mt in mthgrp.Methods) {
foundTargets.Add(mt.Method);
}
return new TargetInfo(null, ArrayUtils.Insert(target, args), BindingRestrictions.GetInstanceRestriction(target.Expression, mthgrp), foundTargets.ToArray());
}
/// <summary>
/// Binds to the methods in a member group.
///
/// TODO: We should really only have either MemberGroup or MethodGroup, not both.
/// </summary>
private static TargetInfo TryGetMemberGroupTargets(DynamicMetaObject target, DynamicMetaObject[] args, MemberGroup mg) {
if (mg == null)
return null;
List<MethodInfo> foundTargets = new List<MethodInfo>();
foreach (MemberTracker mt in mg) {
if (mt.MemberType == TrackerTypes.Method) {
foundTargets.Add(((MethodTracker)mt).Method);
}
}
MethodBase[] targets = foundTargets.ToArray();
return new TargetInfo(null, ArrayUtils.Insert(target, args), targets);
}
/// <summary>
/// Binds to the BoundMemberTracker and uses the instance in the tracker and restricts
/// based upon the object instance type.
/// </summary>
private TargetInfo TryGetBoundMemberTargets(DynamicMetaObject self, DynamicMetaObject[] args, BoundMemberTracker bmt) {
if (bmt != null) {
Debug.Assert(bmt.Instance == null); // should be null for trackers that leak to user code
MethodBase[] targets;
// instance is pulled from the BoundMemberTracker and restricted to the correct
// type.
DynamicMetaObject instance = new DynamicMetaObject(
AstUtils.Convert(
Expression.Property(
Expression.Convert(self.Expression, typeof(BoundMemberTracker)),
typeof(BoundMemberTracker).GetDeclaredProperty("ObjectInstance")
),
bmt.BoundTo.DeclaringType
),
self.Restrictions
).Restrict(CompilerHelpers.GetType(bmt.ObjectInstance));
// we also add a restriction to make sure we're going to the same BoundMemberTracker
BindingRestrictions restrictions = BindingRestrictions.GetExpressionRestriction(
Expression.Equal(
Expression.Property(
Expression.Convert(self.Expression, typeof(BoundMemberTracker)),
typeof(BoundMemberTracker).GetDeclaredProperty("BoundTo")
),
AstUtils.Constant(bmt.BoundTo)
)
);
switch (bmt.BoundTo.MemberType) {
case TrackerTypes.MethodGroup:
targets = ((MethodGroup)bmt.BoundTo).GetMethodBases();
break;
case TrackerTypes.Method:
targets = new MethodBase[] { ((MethodTracker)bmt.BoundTo).Method };
break;
default:
throw new InvalidOperationException(); // nothing else binds yet
}
return new TargetInfo(instance, args, restrictions, targets);
}
return null;
}
/// <summary>
/// Binds to the Invoke method on a delegate if this is a delegate type.
/// </summary>
private static TargetInfo TryGetDelegateTargets(DynamicMetaObject target, DynamicMetaObject[] args, Delegate d) {
if (d != null) {
return new TargetInfo(target, args, d.GetType().GetMethod("Invoke"));
}
return null;
}
/// <summary>
/// Attempts to bind to an operator Call method.
/// </summary>
private TargetInfo TryGetOperatorTargets(DynamicMetaObject self, DynamicMetaObject[] args, object target) {
Type targetType = CompilerHelpers.GetType(target);
MemberGroup callMembers = GetMember(MemberRequestKind.Invoke, targetType, "Call");
List<MethodBase> callTargets = new List<MethodBase>();
foreach (MemberTracker mi in callMembers) {
if (mi.MemberType == TrackerTypes.Method) {
MethodInfo method = ((MethodTracker)mi).Method;
if (method.IsSpecialName) {
callTargets.Add(method);
}
}
}
if (callTargets.Count > 0) {
return new TargetInfo(null, ArrayUtils.Insert(self, args), callTargets.ToArray());
}
return null;
}
#endregion
#region Error support
private DynamicMetaObject MakeCannotCallRule(DynamicMetaObject self, Type type) {
return MakeError(
ErrorInfo.FromException(
Expression.New(
typeof(ArgumentTypeException).GetConstructor(new Type[] { typeof(string) }),
AstUtils.Constant(GetTypeName(type) + " is not callable")
)
),
self.Restrictions.Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(self.Expression, type)),
typeof(object)
);
}
#endregion
/// <summary>
/// Encapsulates information about the target of the call. This includes an implicit instance for the call,
/// the methods that we'll be calling as well as any restrictions required to perform the call.
/// </summary>
class TargetInfo {
public readonly DynamicMetaObject Instance;
public readonly DynamicMetaObject[] Arguments;
public readonly MethodBase[] Targets;
public readonly BindingRestrictions Restrictions;
public TargetInfo(DynamicMetaObject instance, DynamicMetaObject[] arguments, params MethodBase[] args) :
this(instance, arguments, BindingRestrictions.Empty, args) {
}
public TargetInfo(DynamicMetaObject instance, DynamicMetaObject[] arguments, BindingRestrictions restrictions, params MethodBase[] targets) {
Assert.NotNullItems(targets);
Assert.NotNull(restrictions);
Instance = instance;
Arguments = arguments;
Targets = targets;
Restrictions = restrictions;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
// FUTURE: Add a Debug check to see if Write operations result in data loss
namespace NetGore.IO
{
/// <summary>
/// A stream that supports performing I/O on a bit level. No parts of this class are
/// guarenteed to be thread safe.
/// </summary>
public partial class BitStream : Stream, IValueReader, IValueWriter
{
/// <summary>
/// Default maximum length of a string when the maximum length is not specified.
/// </summary>
public const ushort DefaultStringMaxLength = ushort.MaxValue - 1;
/// <summary>
/// The number of bits in a byte.
/// </summary>
const int _bitsByte = sizeof(byte) * 8;
/// <summary>
/// The number of bits in an int.
/// </summary>
const int _bitsInt = sizeof(int) * 8;
/// <summary>
/// The number of bits in a sbyte.
/// </summary>
const int _bitsSByte = sizeof(sbyte) * 8;
/// <summary>
/// The number of bits in a short.
/// </summary>
const int _bitsShort = sizeof(short) * 8;
/// <summary>
/// The number of bits in a uint.
/// </summary>
const int _bitsUInt = sizeof(uint) * 8;
/// <summary>
/// The number of bits in a ushort.
/// </summary>
const int _bitsUShort = sizeof(ushort) * 8;
const int _defaultBufferSize = 64;
/// <summary>
/// The 0-based index of the most significant bit in a byte.
/// </summary>
const int _highBit = (sizeof(byte) * 8) - 1;
readonly bool _useEnumNames = false;
/// <summary>
/// Data buffer
/// </summary>
byte[] _buffer;
/// <summary>
/// The number of bits in the buffer that contain valid data.
/// </summary>
int _lengthBits;
/// <summary>
/// Current position in the buffer in bits.
/// </summary>
int _positionBits = 0;
/// <summary>
/// Initializes a new instance of the <see cref="BitStream"/> class.
/// </summary>
/// <param name="buffer">The initial buffer (default mode set to read). A shallow copy of this object
/// is used, so altering the buffer directly will also alter the stream.</param>
/// <param name="useEnumNames">If true, Enums I/O will be done using the Enum's name. If false,
/// Enum I/O will use the underlying integer value of the Enum.</param>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception>
public BitStream(byte[] buffer, bool useEnumNames = false)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
_useEnumNames = useEnumNames;
SetBuffer(buffer);
}
/// <summary>
/// Initializes a new instance of the <see cref="BitStream"/> class.
/// </summary>
/// <param name="bufferByteSize">Initial size of the internal buffer in bytes (must be greater than 0),</param>
/// <param name="useEnumNames">If true, Enums I/O will be done using the Enum's name. If false,
/// Enum I/O will use the underlying integer value of the Enum.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="bufferByteSize"/> is less than or equal to 0.</exception>
public BitStream(int bufferByteSize = _defaultBufferSize, bool useEnumNames = false)
{
if (bufferByteSize <= 0)
throw new ArgumentOutOfRangeException("bufferByteSize", "BufferByteSize must be greater than 0.");
_useEnumNames = useEnumNames;
_buffer = new byte[bufferByteSize];
}
/// <summary>
/// Gets or sets the length of the internal buffer in bytes. When setting the value, the value
/// must be greater than or equal to the <see cref="BitStream.LengthBytes"/>.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is less than <see cref="BitStream.LengthBytes"/>.</exception>
public int BufferLength
{
get { return _buffer.Length; }
set
{
if (value < Length)
{
const string errmsg =
"value must be greater than or equal to the LengthBytes." +
" If you want to truncate the buffer below this value, change the length first before changing the buffer length.";
throw new ArgumentOutOfRangeException("value", errmsg);
}
Array.Resize(ref _buffer, value);
}
}
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports reading.
/// </summary>
/// <returns>
/// true if the stream supports reading; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public override bool CanRead
{
get { return true; }
}
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
/// </summary>
/// <returns>
/// true if the stream supports seeking; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public override bool CanSeek
{
get { return true; }
}
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
/// </summary>
/// <returns>
/// true if the stream supports writing; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public override bool CanWrite
{
get { return true; }
}
/// <summary>
/// Gets the length of the BitStream in full bytes. This value is always rounded up when there
/// are partial bytes written. For example, if you write anything, even just 1 bit, it will be greater than 0.
/// </summary>
public override long Length
{
get { return LengthBytes; }
}
/// <summary>
/// Gets or sets the length of the BitStream in bits. If the length is set to a value less than the
/// <see cref="PositionBits"/>, then the <see cref="PositionBits"/> will be changed to be equal
/// to the new length.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception>
public int LengthBits
{
get { return _lengthBits; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("value");
_lengthBits = value;
// When the position exceeds the length, update the position
if (_positionBits > _lengthBits)
_positionBits = _lengthBits;
}
}
/// <summary>
/// Gets the length of the BitStream in full bytes. This value is always rounded up when there
/// are partial bytes written. For example, if you write anything, even just 1 bit, it will be greater than 0.
/// </summary>
public int LengthBytes
{
get { return (int)Math.Ceiling(_lengthBits / (float)_bitsByte); }
}
/// <summary>
/// When overridden in a derived class, gets or sets the position within the current stream.
/// </summary>
/// <value></value>
/// <returns>
/// The current position within the stream.
/// </returns>
public override long Position
{
get { return PositionBytes; }
set { PositionBits = (int)(value * _bitsByte); }
}
/// <summary>
/// Gets or sets the position of the buffer in bits.
/// </summary>
public int PositionBits
{
get { return _positionBits; }
set
{
_positionBits = value;
// When the position exceeds the length, update the length
if (_positionBits > _lengthBits)
_lengthBits = _positionBits;
}
}
/// <summary>
/// Gets the position of the stream in bytes.
/// This value is always rounded down when on a partial bit.
/// </summary>
public int PositionBytes
{
get
{
var ret = PositionBits / _bitsByte;
Debug.Assert(ret == (int)Math.Floor(PositionBits / (float)_bitsByte));
return ret;
}
}
/// <summary>
/// Checks if a number of bits can fit into the buffer without overflowing. If
/// the buffer is set to automatically expand, this will always be true.
/// </summary>
/// <param name="numBits">Number of bits to check to fit into the buffer.</param>
/// <returns>True if the bits can fit, else false.</returns>
bool CanFitBits(int numBits)
{
if (numBits < 1)
{
Debug.Fail("numBits less than 1.");
return true;
}
// Check if the bits can fit
return PositionBits + numBits <= BufferLength * _bitsByte;
}
/// <summary>
/// Gets a NotSupportedException to use for when trying to use nodes for the IValueReader and IValueWriter.
/// </summary>
/// <returns>A NotSupportedException to use for when trying to use nodes.</returns>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "BinaryValueWriter")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "BitStream")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "BinaryValueReader")]
protected internal static NotSupportedException CreateNodesNotSupportedException()
{
const string errmsg =
"Nodes are not supported by the BitStream. If you want node support, use the" +
" BinaryValueReader and BinaryValueWriter instead of the BitStream directly.";
return new NotSupportedException(errmsg);
}
/// <summary>
/// Expands the buffer.
/// </summary>
void ExpandBuffer()
{
// The amount we expand will always be enough to fit in at least a 32-bit integer, and that is the largest
// number of bits we write to or read from the buffer at any one time, so this will always be enough.
// Always increase the buffer by at least 6 bytes.
var newSize = _buffer.Length + 6;
// Round up to the next power of two (if not already there)
newSize = BitOps.NextPowerOf2(newSize);
// Resize the buffer
Array.Resize(ref _buffer, newSize);
}
/// <summary>
/// Unused by the <see cref="BitStream"/>.
/// </summary>
public override void Flush()
{
}
/// <summary>
/// Gets the byte buffer (shallow copy) used by the BitStream.
/// </summary>
/// <returns>Byte buffer used by the BitStream (shallow copy).</returns>
public byte[] GetBuffer()
{
return _buffer;
}
/// <summary>
/// Gets a deep copy of the data in the BitStream's buffer. When called in Write mode,
/// this will flush out the working buffer (if one exists), so do not call this until
/// you are sure you are done writing!
/// </summary>
/// <returns>Byte buffer containing a copy of BitStream's buffer.</returns>
public byte[] GetBufferCopy()
{
// Create the byte array to hold the copy and transfer over the data
var len = LengthBytes;
var ret = new byte[len];
Buffer.BlockCopy(_buffer, 0, ret, 0, len);
// Return the copy
return ret;
}
/// <summary>
/// Gets the number of bits required to store the length of a string with the specified maximum size.
/// </summary>
/// <param name="maxLength">Maximum length of the string.</param>
/// <returns>Number of bits required to store the length of the string.</returns>
static int GetStringLengthBits(uint maxLength)
{
return BitOps.RequiredBits(maxLength);
}
/// <summary>
/// When overridden in the derived class, performs disposing of the object.
/// </summary>
protected virtual void HandleDispose()
{
}
/// <summary>
/// Increases the position to the next perfect byte. If you
/// plan on doing multiple reads or writes in a row by a multiple
/// of 8 bits, this can help increase the I/O performance.
/// </summary>
public void MoveToNextByte()
{
// Don't move if we're already on a perfect byte
var bitsToMove = _bitsByte - (PositionBits % _bitsByte);
if (bitsToMove == 0)
return;
SeekBits(bitsToMove, SeekOrigin.Current);
}
/// <summary>
/// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array
/// with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1)
/// replaced by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data
/// read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
/// bytes are not currently available, or zero (0) if the end of the stream has been reached.
/// </returns>
/// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is
/// larger than the buffer length.</exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="buffer"/> is null.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="offset"/> or <paramref name="count"/> is negative.</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer" /> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><c>offset</c> is less than zero.</exception>
/// <exception cref="ArgumentOutOfRangeException"><c>count</c> is less than zero.</exception>
/// <exception cref="ArgumentException">The sum of the offset and count is greater than the buffer length.</exception>
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (offset + count > buffer.Length)
throw new ArgumentException("The sum of the offset and count is greater than the buffer length.");
// Find the number of full bytes remaining
var bytesRemaining = (int)Math.Floor(((float)LengthBits - PositionBits) / _bitsByte);
Debug.Assert(bytesRemaining >= 0);
// Find the number of bytes we should read
var bytesToRead = Math.Min(count, bytesRemaining);
Debug.Assert(bytesToRead >= 0);
// Read one byte at a time
for (var i = 0; i < bytesToRead; i++)
{
buffer[i + offset] = ReadByte();
}
return bytesToRead;
}
/// <summary>
/// Reads a signed value from the BitStream.
/// </summary>
/// <param name="numBits">Number of bits to read.</param>
/// <param name="maxBits">Number of bits in the desired value type.</param>
/// <returns>The read value.</returns>
/// <exception cref="ArgumentOutOfRangeException"><c>numBits</c> is out of range.</exception>
int ReadSigned(int numBits, int maxBits)
{
if (numBits > maxBits)
throw new ArgumentOutOfRangeException("numBits",
string.Format("numBits ({0}) must be <= maxBits ({1}).", numBits, maxBits));
if (numBits == 1)
return ReadBitAsInt();
var signWithValue = ReadUnsigned(numBits);
var sign = signWithValue & (1 << (numBits - 1));
var value = signWithValue & (~sign);
// Check for a negative value
if (sign != 0)
{
// Any time that value == 0 and the sign is set, it must have been because we wrote
// a perfect negative square, since why the hell would we waste a beautiful little sign
// on 0? For -0? Ha! Screw you.
if (value == 0)
return sign << (maxBits - numBits);
// Sign is set, value is non-zero, negate that piggy!
value = -value;
}
Debug.Assert((value == 0) || ((value < 0) == (sign != 0)), "Value is improperly signed.");
return value;
}
/// <summary>
/// Reads from the BitStream.
/// </summary>
/// <param name="numBits">Number of bits to read (1 to 32 bits).</param>
/// <returns>Base 10 value of the bits read.</returns>
/// <exception cref="ArgumentOutOfRangeException"><c>numBits</c> is greater than <see cref="_bitsInt"/> or less
/// than one.</exception>
/// <exception cref="ArithmeticException">Unexpected error encountered while reading <paramref name="numBits"/>.</exception>
int ReadUnsigned(int numBits)
{
if (numBits > _bitsInt || numBits < 1)
throw new ArgumentOutOfRangeException("numBits", string.Format("numBits contains an invalid range ({0})", numBits));
// Check if the buffer will overflow
if (!CanFitBits(numBits))
ExpandBuffer();
int ret;
if ((numBits % _bitsByte == 0) && (PositionBits % _bitsByte == 0))
{
var bufferIndex = (PositionBits / _bitsByte);
// Optimal scenario - buffer is fresh and we're grabbing whole bytes,
// so just skip the buffer and copy the memory
switch (numBits)
{
case _bitsByte * 1: // Perfect byte copy
ret = _buffer[bufferIndex + 0];
break;
case _bitsByte * 2: // Perfect short copy
ret = (_buffer[bufferIndex + 0] << _bitsByte) | _buffer[bufferIndex + 1];
break;
case _bitsByte * 3: // Perfect bigger-than-short-but-not-quite-int-but-we-love-him-anyways copy
ret = (_buffer[bufferIndex + 0] << (_bitsByte * 2)) | (_buffer[bufferIndex + 1] << _bitsByte) |
_buffer[bufferIndex + 2];
break;
case _bitsByte * 4: // Perfect int copy
ret = (_buffer[bufferIndex + 0] << (_bitsByte * 3)) | (_buffer[bufferIndex + 1] << (_bitsByte * 2)) |
(_buffer[bufferIndex + 2] << _bitsByte) | _buffer[bufferIndex + 3];
break;
default: // Compiler complains if we don't assign ret...
throw new ArithmeticException("Huh... how did this happen?");
}
// Update the stream position
PositionBits += numBits;
}
else
{
// Loop until all the bits have been read
ret = 0;
var retPos = numBits - 1;
do
{
// Check how much of the current byte in the buffer can be read
var bufferIndex = (PositionBits / _bitsByte);
var bufferByteBitsLeft = _bitsByte - (PositionBits % _bitsByte);
// *** Find the number of bits to read ***
int bitsToRead;
// Check if we can fit the whole piece of the buffer into the return value
if (bufferByteBitsLeft > retPos + 1)
{
// Only use the chunk of the buffer we can fit into the return value
bitsToRead = retPos + 1;
}
else
{
// Use the remainder of the bits at the current buffer position
bitsToRead = bufferByteBitsLeft;
}
// *** Add the bits to the return value ***
// Create the mask to apply to the value from the buffer
var mask = (1 << bitsToRead) - 1;
// Grab the value from the buffer and shift it over so it starts with the bits we are interested in
var value = _buffer[bufferIndex] >> (bufferByteBitsLeft - bitsToRead);
// Apply the mask to zero out values we are not interested in
value &= mask;
// Shift the value to the left to align it to where we want it on the return value
value <<= (retPos - (bitsToRead - 1));
// OR the value from the buffer onto the return value
ret |= value;
// Decrease the retPos by the number of bits we read and increase the stream position
retPos -= bitsToRead;
PositionBits += bitsToRead;
}
while (retPos >= 0);
Debug.Assert(retPos == -1);
}
return ret;
}
/// <summary>
/// Resets the BitStream content and variables to a "like-new" state. The read/write buffer modes, along
/// with the Mode are not altered by this.
/// </summary>
public void Reset()
{
_lengthBits = 0;
_positionBits = 0;
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="byteOffset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
/// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point
/// used to obtain the new position.</param>
/// <returns>
/// The new position within the current stream.
/// </returns>
public override long Seek(long byteOffset, SeekOrigin origin)
{
return SeekBits((int)(byteOffset * _bitsByte), origin) * _bitsByte;
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="bitOffset">A bit offset relative to the <paramref name="origin"/> parameter.</param>
/// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point
/// used to obtain the new position.</param>
/// <returns>
/// The new position within the current stream.
/// </returns>
public int SeekBits(int bitOffset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
PositionBits = bitOffset;
break;
case SeekOrigin.Current:
PositionBits += bitOffset;
break;
case SeekOrigin.End:
PositionBits = LengthBits - bitOffset;
break;
}
return PositionBits;
}
/// <summary>
/// Sets a new internal buffer for the BitStream.
/// </summary>
/// <param name="buffer">The new buffer.</param>
void SetBuffer(byte[] buffer)
{
Reset();
_buffer = buffer;
LengthBits = buffer.Length * _bitsByte;
PositionBits = 0;
}
/// <summary>
/// When overridden in a derived class, sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
public override void SetLength(long value)
{
LengthBits = (int)(value * _bitsByte);
}
/// <summary>
/// Converts a byte array to a string.
/// </summary>
/// <param name="bytes">The byte array.</param>
/// <returns>The string created from the <paramref name="bytes"/>.</returns>
public static string StringFromByteArray(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
/// <summary>
/// Converts a string to a byte array.
/// </summary>
/// <param name="str">The string.</param>
/// <returns>The byte array for the <paramref name="str"/>.</returns>
public static byte[] StringToByteArray(string str)
{
return Encoding.UTF8.GetBytes(str);
}
/// <summary>
/// Trims down the internal buffer to only fit the desired data. This will result in the internal buffer
/// length being equal to <see cref="BitStream.Length"/>.
/// </summary>
public void TrimExcess()
{
Array.Resize(ref _buffer, (int)Length);
}
/// <summary>
/// Writes a signed value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="numBits">The number of bits.</param>
/// <exception cref="ArgumentOutOfRangeException"><c>numBits</c> is greater than <see cref="_bitsInt"/> or less than one.</exception>
void WriteSigned(int value, int numBits)
{
if (numBits > _bitsInt || numBits < 1)
throw new ArgumentOutOfRangeException("numBits", "numBits must be between 1 and 32.");
// Treat single bits as just that - a single bit
// No sign will be written for 1-bit numbers, since that'd just be stupid... you stupid
if (numBits == 1)
{
WriteBit(value);
return;
}
// Special case scenario - if lowest value of a 2's complement, we can't negate it (legally)
// Funny enough, it actually makes it easier for us since only int.MinValue will throw an
// exception, but every other case of a perfect negative power of 2 will fall victim to this
// same problem, but our reader fixes it with ease. See ReadSigned for more info.
if (value == int.MinValue)
{
WriteBit(value);
Write(0, numBits - 1);
return;
}
// Get a 1-bit mask for the bit at the sign
var signBit = 1 << (numBits - 1);
// If negative, negate the value. While we're at it, we might as well also just
// pack the sign into the value so we can write the whole value in one call. This
// is essentially the same as if we were to just use:
//
// WriteBit(value < 0);
// if (value < 0)
// value = -value;
// WriteUnsigned(value, numBits - 1)
//
// Sure, who cares about one extra write call, right? Well, when we split up the
// sign and value, this fucks us over for 8, 16, 24, and 32 bit signed writes
// since then are no longer able to take advantage of just pushing the value into
// the buffer instead of throwing bits all over the place.
if (value < 0)
{
value = -value;
// Ensure the sign bit is set
value |= signBit;
}
else
{
// Ensure the sign bit is not set
value &= ~signBit;
}
WriteUnsigned(value, numBits);
}
/// <summary>
/// Writes an unsigned value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="numBits">The number of bits.</param>
/// <exception cref="ArgumentOutOfRangeException"><c>numBits</c> is greater than <see cref="_bitsInt"/> or less than one.</exception>
/// <exception cref="ArithmeticException">Unexpected error occured when handling <paramref name="numBits"/>.</exception>
void WriteUnsigned(int value, int numBits)
{
if (numBits > _bitsInt || numBits < 1)
throw new ArgumentOutOfRangeException("numBits", "Value must be between 1 and 32.");
// Check if the buffer will overflow
if (!CanFitBits(numBits))
ExpandBuffer();
if ((PositionBits % _bitsByte == 0) && (numBits % _bitsByte == 0))
{
var bufferIndex = (PositionBits / _bitsByte);
// Optimal scenario - buffer is fresh and we're writing a byte, so
// we can just do a direct memory copy
switch (numBits)
{
case _bitsByte * 1: // Perfect byte writing
_buffer[bufferIndex + 0] = (byte)(value >> (_bitsByte * 0));
break;
case _bitsByte * 2: // Perfect short writing
_buffer[bufferIndex + 0] = (byte)(value >> (_bitsByte * 1));
_buffer[bufferIndex + 1] = (byte)(value >> (_bitsByte * 0));
break;
case _bitsByte * 3: // Perfect 24-bit writing
_buffer[bufferIndex + 0] = (byte)(value >> (_bitsByte * 2));
_buffer[bufferIndex + 1] = (byte)(value >> (_bitsByte * 1));
_buffer[bufferIndex + 2] = (byte)(value >> (_bitsByte * 0));
break;
case _bitsByte * 4: // Perfect int writing
_buffer[bufferIndex + 0] = (byte)(value >> (_bitsByte * 3));
_buffer[bufferIndex + 1] = (byte)(value >> (_bitsByte * 2));
_buffer[bufferIndex + 2] = (byte)(value >> (_bitsByte * 1));
_buffer[bufferIndex + 3] = (byte)(value >> (_bitsByte * 0));
break;
default:
throw new ArithmeticException("Huh... how did this happen?");
}
// Update the stream position
PositionBits += numBits;
}
else
{
// Non-optimal scenario - we have to use some sexy bit hacking
// Loop until all the bits have been written
var valuePos = numBits - 1;
do
{
// Check how much of the current byte in the buffer can be written
var bufferIndex = (PositionBits / _bitsByte);
var bufferByteBitsLeft = _bitsByte - (PositionBits % _bitsByte);
// *** Find the number of bits to write ***
int bitsToWrite;
// Check if we can fit the whole piece of the value into the buffer
if (valuePos + 1 > bufferByteBitsLeft)
{
// Write to the remaining bits at the current buffer byte
bitsToWrite = bufferByteBitsLeft;
}
else
{
// Only write the remaining bits in the value
bitsToWrite = valuePos + 1;
}
// *** Add the bits to the buffer ***
// Create the mask to apply to the value
var mask = (1 << bitsToWrite) - 1;
// Shift over the value so that it starts with only the bits we are intersted in
var valueToWrite = value >> ((valuePos + 1) - bitsToWrite);
// Apply the mask to zero out values we are not interested in
valueToWrite &= mask;
// Shift the value to the left to align it to where we want it in the buffer
valueToWrite <<= bufferByteBitsLeft - bitsToWrite;
// Grab the current buffer value
var newBufferValue = _buffer[bufferIndex];
// Make sure we zero out the bits that we are about to write to so that way we can
// be sure that, when overwriting existing values, 0's are still written properly even if
// the bit in the buffer is a 1. We do this by taking the mask we have from earlier (which contains
// the mask, stored in the right-most bits) and shifting it over to the position we want (giving
// us a mask for the bits we are writing), then using a bitwise NOT to create a mask for all the
// other bits. Finally, use a bitwise AND to zero out all bits that we will be writing to.
var clearMask = (byte)(mask << (bufferByteBitsLeft - bitsToWrite));
clearMask = (byte)~clearMask;
newBufferValue &= clearMask;
// OR the value onto the buffer value
newBufferValue |= (byte)valueToWrite;
// Copy the value back into the buffer
_buffer[bufferIndex] = newBufferValue;
// Decrease the valuePos by the number of bits we wrote, and increase the stream position
valuePos -= bitsToWrite;
PositionBits += bitsToWrite;
}
while (valuePos >= 0);
Debug.Assert(valuePos == -1);
}
}
}
}
| |
// 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.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Groups Settings API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/google-apps/groups-settings/get_started'>Groups Settings API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20170607 (888)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/google-apps/groups-settings/get_started'>
* https://developers.google.com/google-apps/groups-settings/get_started</a>
* <tr><th>Discovery Name<td>groupssettings
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Groups Settings API can be found at
* <a href='https://developers.google.com/google-apps/groups-settings/get_started'>https://developers.google.com/google-apps/groups-settings/get_started</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.Groupssettings.v1
{
/// <summary>The Groupssettings Service.</summary>
public class GroupssettingsService : 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 GroupssettingsService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public GroupssettingsService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
groups = new GroupsResource(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 "groupssettings"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/groups/v1/groups/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "groups/v1/groups/"; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://www.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Groups Settings API.</summary>
public class Scope
{
/// <summary>View and manage the settings of a G Suite group</summary>
public static string AppsGroupsSettings = "https://www.googleapis.com/auth/apps.groups.settings";
}
private readonly GroupsResource groups;
/// <summary>Gets the Groups resource.</summary>
public virtual GroupsResource Groups
{
get { return groups; }
}
}
///<summary>A base abstract class for Groupssettings requests.</summary>
public abstract class GroupssettingsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new GroupssettingsBaseServiceRequest instance.</summary>
protected GroupssettingsBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: atom]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/atom+xml</summary>
[Google.Apis.Util.StringValueAttribute("atom")]
Atom,
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [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. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes Groupssettings parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "atom",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "groups" collection of methods.</summary>
public class GroupsResource
{
private const string Resource = "groups";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public GroupsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Gets one resource by id.</summary>
/// <param name="groupUniqueId">The resource ID</param>
public virtual GetRequest Get(string groupUniqueId)
{
return new GetRequest(service, groupUniqueId);
}
/// <summary>Gets one resource by id.</summary>
public class GetRequest : GroupssettingsBaseServiceRequest<Google.Apis.Groupssettings.v1.Data.Groups>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string groupUniqueId)
: base(service)
{
GroupUniqueId = groupUniqueId;
InitParameters();
}
/// <summary>The resource ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupUniqueId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupUniqueId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<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 "{groupUniqueId}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"groupUniqueId", new Google.Apis.Discovery.Parameter
{
Name = "groupUniqueId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates an existing resource. This method supports patch semantics.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="groupUniqueId">The resource ID</param>
public virtual PatchRequest Patch(Google.Apis.Groupssettings.v1.Data.Groups body, string groupUniqueId)
{
return new PatchRequest(service, body, groupUniqueId);
}
/// <summary>Updates an existing resource. This method supports patch semantics.</summary>
public class PatchRequest : GroupssettingsBaseServiceRequest<Google.Apis.Groupssettings.v1.Data.Groups>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Groupssettings.v1.Data.Groups body, string groupUniqueId)
: base(service)
{
GroupUniqueId = groupUniqueId;
Body = body;
InitParameters();
}
/// <summary>The resource ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupUniqueId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupUniqueId { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Groupssettings.v1.Data.Groups Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{groupUniqueId}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"groupUniqueId", new Google.Apis.Discovery.Parameter
{
Name = "groupUniqueId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates an existing resource.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="groupUniqueId">The resource ID</param>
public virtual UpdateRequest Update(Google.Apis.Groupssettings.v1.Data.Groups body, string groupUniqueId)
{
return new UpdateRequest(service, body, groupUniqueId);
}
/// <summary>Updates an existing resource.</summary>
public class UpdateRequest : GroupssettingsBaseServiceRequest<Google.Apis.Groupssettings.v1.Data.Groups>
{
/// <summary>Constructs a new Update request.</summary>
public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Groupssettings.v1.Data.Groups body, string groupUniqueId)
: base(service)
{
GroupUniqueId = groupUniqueId;
Body = body;
InitParameters();
}
/// <summary>The resource ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupUniqueId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupUniqueId { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Groupssettings.v1.Data.Groups Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "update"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PUT"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{groupUniqueId}"; }
}
/// <summary>Initializes Update parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"groupUniqueId", new Google.Apis.Discovery.Parameter
{
Name = "groupUniqueId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Groupssettings.v1.Data
{
/// <summary>JSON template for Group resource</summary>
public class Groups : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Are external members allowed to join the group.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("allowExternalMembers")]
public virtual string AllowExternalMembers { get; set; }
/// <summary>Is google allowed to contact admins.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("allowGoogleCommunication")]
public virtual string AllowGoogleCommunication { get; set; }
/// <summary>If posting from web is allowed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("allowWebPosting")]
public virtual string AllowWebPosting { get; set; }
/// <summary>If the group is archive only</summary>
[Newtonsoft.Json.JsonPropertyAttribute("archiveOnly")]
public virtual string ArchiveOnly { get; set; }
/// <summary>Custom footer text.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("customFooterText")]
public virtual string CustomFooterText { get; set; }
/// <summary>Default email to which reply to any message should go.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("customReplyTo")]
public virtual string CustomReplyTo { get; set; }
/// <summary>Default message deny notification message</summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultMessageDenyNotificationText")]
public virtual string DefaultMessageDenyNotificationText { get; set; }
/// <summary>Description of the group</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Email id of the group</summary>
[Newtonsoft.Json.JsonPropertyAttribute("email")]
public virtual string Email { get; set; }
/// <summary>Whether to include custom footer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("includeCustomFooter")]
public virtual string IncludeCustomFooter { get; set; }
/// <summary>If this groups should be included in global address list or not.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("includeInGlobalAddressList")]
public virtual string IncludeInGlobalAddressList { get; set; }
/// <summary>If the contents of the group are archived.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("isArchived")]
public virtual string IsArchived { get; set; }
/// <summary>The type of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Maximum message size allowed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("maxMessageBytes")]
public virtual System.Nullable<int> MaxMessageBytes { get; set; }
/// <summary>Can members post using the group email address.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("membersCanPostAsTheGroup")]
public virtual string MembersCanPostAsTheGroup { get; set; }
/// <summary>Default message display font. Possible values are: DEFAULT_FONT FIXED_WIDTH_FONT</summary>
[Newtonsoft.Json.JsonPropertyAttribute("messageDisplayFont")]
public virtual string MessageDisplayFont { get; set; }
/// <summary>Moderation level for messages. Possible values are: MODERATE_ALL_MESSAGES MODERATE_NON_MEMBERS
/// MODERATE_NEW_MEMBERS MODERATE_NONE</summary>
[Newtonsoft.Json.JsonPropertyAttribute("messageModerationLevel")]
public virtual string MessageModerationLevel { get; set; }
/// <summary>Name of the Group</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Primary language for the group.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("primaryLanguage")]
public virtual string PrimaryLanguage { get; set; }
/// <summary>Whome should the default reply to a message go to. Possible values are: REPLY_TO_CUSTOM
/// REPLY_TO_SENDER REPLY_TO_LIST REPLY_TO_OWNER REPLY_TO_IGNORE REPLY_TO_MANAGERS</summary>
[Newtonsoft.Json.JsonPropertyAttribute("replyTo")]
public virtual string ReplyTo { get; set; }
/// <summary>Should the member be notified if his message is denied by owner.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sendMessageDenyNotification")]
public virtual string SendMessageDenyNotification { get; set; }
/// <summary>Is the group listed in groups directory</summary>
[Newtonsoft.Json.JsonPropertyAttribute("showInGroupDirectory")]
public virtual string ShowInGroupDirectory { get; set; }
/// <summary>Moderation level for messages detected as spam. Possible values are: ALLOW MODERATE
/// SILENTLY_MODERATE REJECT</summary>
[Newtonsoft.Json.JsonPropertyAttribute("spamModerationLevel")]
public virtual string SpamModerationLevel { get; set; }
/// <summary>Permissions to add members. Possible values are: ALL_MANAGERS_CAN_ADD ALL_MEMBERS_CAN_ADD
/// NONE_CAN_ADD</summary>
[Newtonsoft.Json.JsonPropertyAttribute("whoCanAdd")]
public virtual string WhoCanAdd { get; set; }
/// <summary>Permission to contact owner of the group via web UI. Possible values are: ANYONE_CAN_CONTACT
/// ALL_IN_DOMAIN_CAN_CONTACT ALL_MEMBERS_CAN_CONTACT ALL_MANAGERS_CAN_CONTACT</summary>
[Newtonsoft.Json.JsonPropertyAttribute("whoCanContactOwner")]
public virtual string WhoCanContactOwner { get; set; }
/// <summary>Permissions to invite members. Possible values are: ALL_MEMBERS_CAN_INVITE ALL_MANAGERS_CAN_INVITE
/// NONE_CAN_INVITE</summary>
[Newtonsoft.Json.JsonPropertyAttribute("whoCanInvite")]
public virtual string WhoCanInvite { get; set; }
/// <summary>Permissions to join the group. Possible values are: ANYONE_CAN_JOIN ALL_IN_DOMAIN_CAN_JOIN
/// INVITED_CAN_JOIN CAN_REQUEST_TO_JOIN</summary>
[Newtonsoft.Json.JsonPropertyAttribute("whoCanJoin")]
public virtual string WhoCanJoin { get; set; }
/// <summary>Permission to leave the group. Possible values are: ALL_MANAGERS_CAN_LEAVE ALL_MEMBERS_CAN_LEAVE
/// NONE_CAN_LEAVE</summary>
[Newtonsoft.Json.JsonPropertyAttribute("whoCanLeaveGroup")]
public virtual string WhoCanLeaveGroup { get; set; }
/// <summary>Permissions to post messages to the group. Possible values are: NONE_CAN_POST ALL_MANAGERS_CAN_POST
/// ALL_MEMBERS_CAN_POST ALL_OWNERS_CAN_POST ALL_IN_DOMAIN_CAN_POST ANYONE_CAN_POST</summary>
[Newtonsoft.Json.JsonPropertyAttribute("whoCanPostMessage")]
public virtual string WhoCanPostMessage { get; set; }
/// <summary>Permissions to view group. Possible values are: ANYONE_CAN_VIEW ALL_IN_DOMAIN_CAN_VIEW
/// ALL_MEMBERS_CAN_VIEW ALL_MANAGERS_CAN_VIEW</summary>
[Newtonsoft.Json.JsonPropertyAttribute("whoCanViewGroup")]
public virtual string WhoCanViewGroup { get; set; }
/// <summary>Permissions to view membership. Possible values are: ALL_IN_DOMAIN_CAN_VIEW ALL_MEMBERS_CAN_VIEW
/// ALL_MANAGERS_CAN_VIEW</summary>
[Newtonsoft.Json.JsonPropertyAttribute("whoCanViewMembership")]
public virtual string WhoCanViewMembership { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// ChallengeResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Verify.V2.Service.Entity
{
public class ChallengeResource : Resource
{
public sealed class ChallengeStatusesEnum : StringEnum
{
private ChallengeStatusesEnum(string value) : base(value) {}
public ChallengeStatusesEnum() {}
public static implicit operator ChallengeStatusesEnum(string value)
{
return new ChallengeStatusesEnum(value);
}
public static readonly ChallengeStatusesEnum Pending = new ChallengeStatusesEnum("pending");
public static readonly ChallengeStatusesEnum Expired = new ChallengeStatusesEnum("expired");
public static readonly ChallengeStatusesEnum Approved = new ChallengeStatusesEnum("approved");
public static readonly ChallengeStatusesEnum Denied = new ChallengeStatusesEnum("denied");
}
public sealed class ChallengeReasonsEnum : StringEnum
{
private ChallengeReasonsEnum(string value) : base(value) {}
public ChallengeReasonsEnum() {}
public static implicit operator ChallengeReasonsEnum(string value)
{
return new ChallengeReasonsEnum(value);
}
public static readonly ChallengeReasonsEnum None = new ChallengeReasonsEnum("none");
public static readonly ChallengeReasonsEnum NotNeeded = new ChallengeReasonsEnum("not_needed");
public static readonly ChallengeReasonsEnum NotRequested = new ChallengeReasonsEnum("not_requested");
}
public sealed class FactorTypesEnum : StringEnum
{
private FactorTypesEnum(string value) : base(value) {}
public FactorTypesEnum() {}
public static implicit operator FactorTypesEnum(string value)
{
return new FactorTypesEnum(value);
}
public static readonly FactorTypesEnum Push = new FactorTypesEnum("push");
public static readonly FactorTypesEnum Totp = new FactorTypesEnum("totp");
}
public sealed class ListOrdersEnum : StringEnum
{
private ListOrdersEnum(string value) : base(value) {}
public ListOrdersEnum() {}
public static implicit operator ListOrdersEnum(string value)
{
return new ListOrdersEnum(value);
}
public static readonly ListOrdersEnum Asc = new ListOrdersEnum("asc");
public static readonly ListOrdersEnum Desc = new ListOrdersEnum("desc");
}
private static Request BuildCreateRequest(CreateChallengeOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Verify,
"/v2/Services/" + options.PathServiceSid + "/Entities/" + options.PathIdentity + "/Challenges",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Create a new Challenge for the Factor
/// </summary>
/// <param name="options"> Create Challenge parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Challenge </returns>
public static ChallengeResource Create(CreateChallengeOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Create a new Challenge for the Factor
/// </summary>
/// <param name="options"> Create Challenge parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Challenge </returns>
public static async System.Threading.Tasks.Task<ChallengeResource> CreateAsync(CreateChallengeOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Create a new Challenge for the Factor
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathIdentity"> Unique external identifier of the Entity </param>
/// <param name="factorSid"> Factor Sid. </param>
/// <param name="expirationDate"> The date-time when this Challenge expires </param>
/// <param name="detailsMessage"> Shown to the user when the push notification arrives </param>
/// <param name="detailsFields"> A list of objects that describe the Fields included in the Challenge </param>
/// <param name="hiddenDetails"> Hidden details provided to contextualize the Challenge </param>
/// <param name="authPayload"> Optional payload to verify the Challenge </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Challenge </returns>
public static ChallengeResource Create(string pathServiceSid,
string pathIdentity,
string factorSid,
DateTime? expirationDate = null,
string detailsMessage = null,
List<object> detailsFields = null,
object hiddenDetails = null,
string authPayload = null,
ITwilioRestClient client = null)
{
var options = new CreateChallengeOptions(pathServiceSid, pathIdentity, factorSid){ExpirationDate = expirationDate, DetailsMessage = detailsMessage, DetailsFields = detailsFields, HiddenDetails = hiddenDetails, AuthPayload = authPayload};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Create a new Challenge for the Factor
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathIdentity"> Unique external identifier of the Entity </param>
/// <param name="factorSid"> Factor Sid. </param>
/// <param name="expirationDate"> The date-time when this Challenge expires </param>
/// <param name="detailsMessage"> Shown to the user when the push notification arrives </param>
/// <param name="detailsFields"> A list of objects that describe the Fields included in the Challenge </param>
/// <param name="hiddenDetails"> Hidden details provided to contextualize the Challenge </param>
/// <param name="authPayload"> Optional payload to verify the Challenge </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Challenge </returns>
public static async System.Threading.Tasks.Task<ChallengeResource> CreateAsync(string pathServiceSid,
string pathIdentity,
string factorSid,
DateTime? expirationDate = null,
string detailsMessage = null,
List<object> detailsFields = null,
object hiddenDetails = null,
string authPayload = null,
ITwilioRestClient client = null)
{
var options = new CreateChallengeOptions(pathServiceSid, pathIdentity, factorSid){ExpirationDate = expirationDate, DetailsMessage = detailsMessage, DetailsFields = detailsFields, HiddenDetails = hiddenDetails, AuthPayload = authPayload};
return await CreateAsync(options, client);
}
#endif
private static Request BuildFetchRequest(FetchChallengeOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Verify,
"/v2/Services/" + options.PathServiceSid + "/Entities/" + options.PathIdentity + "/Challenges/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch a specific Challenge.
/// </summary>
/// <param name="options"> Fetch Challenge parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Challenge </returns>
public static ChallengeResource Fetch(FetchChallengeOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch a specific Challenge.
/// </summary>
/// <param name="options"> Fetch Challenge parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Challenge </returns>
public static async System.Threading.Tasks.Task<ChallengeResource> FetchAsync(FetchChallengeOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch a specific Challenge.
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathIdentity"> Unique external identifier of the Entity </param>
/// <param name="pathSid"> A string that uniquely identifies this Challenge. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Challenge </returns>
public static ChallengeResource Fetch(string pathServiceSid,
string pathIdentity,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchChallengeOptions(pathServiceSid, pathIdentity, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch a specific Challenge.
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathIdentity"> Unique external identifier of the Entity </param>
/// <param name="pathSid"> A string that uniquely identifies this Challenge. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Challenge </returns>
public static async System.Threading.Tasks.Task<ChallengeResource> FetchAsync(string pathServiceSid,
string pathIdentity,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchChallengeOptions(pathServiceSid, pathIdentity, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadChallengeOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Verify,
"/v2/Services/" + options.PathServiceSid + "/Entities/" + options.PathIdentity + "/Challenges",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all Challenges for a Factor.
/// </summary>
/// <param name="options"> Read Challenge parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Challenge </returns>
public static ResourceSet<ChallengeResource> Read(ReadChallengeOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<ChallengeResource>.FromJson("challenges", response.Content);
return new ResourceSet<ChallengeResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Challenges for a Factor.
/// </summary>
/// <param name="options"> Read Challenge parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Challenge </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ChallengeResource>> ReadAsync(ReadChallengeOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<ChallengeResource>.FromJson("challenges", response.Content);
return new ResourceSet<ChallengeResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all Challenges for a Factor.
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathIdentity"> Unique external identifier of the Entity </param>
/// <param name="factorSid"> Factor Sid. </param>
/// <param name="status"> The Status of theChallenges to fetch </param>
/// <param name="order"> The sort order of the Challenges list </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Challenge </returns>
public static ResourceSet<ChallengeResource> Read(string pathServiceSid,
string pathIdentity,
string factorSid = null,
ChallengeResource.ChallengeStatusesEnum status = null,
ChallengeResource.ListOrdersEnum order = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadChallengeOptions(pathServiceSid, pathIdentity){FactorSid = factorSid, Status = status, Order = order, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Challenges for a Factor.
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathIdentity"> Unique external identifier of the Entity </param>
/// <param name="factorSid"> Factor Sid. </param>
/// <param name="status"> The Status of theChallenges to fetch </param>
/// <param name="order"> The sort order of the Challenges list </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Challenge </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ChallengeResource>> ReadAsync(string pathServiceSid,
string pathIdentity,
string factorSid = null,
ChallengeResource.ChallengeStatusesEnum status = null,
ChallengeResource.ListOrdersEnum order = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadChallengeOptions(pathServiceSid, pathIdentity){FactorSid = factorSid, Status = status, Order = order, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<ChallengeResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<ChallengeResource>.FromJson("challenges", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<ChallengeResource> NextPage(Page<ChallengeResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Verify)
);
var response = client.Request(request);
return Page<ChallengeResource>.FromJson("challenges", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<ChallengeResource> PreviousPage(Page<ChallengeResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Verify)
);
var response = client.Request(request);
return Page<ChallengeResource>.FromJson("challenges", response.Content);
}
private static Request BuildUpdateRequest(UpdateChallengeOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Verify,
"/v2/Services/" + options.PathServiceSid + "/Entities/" + options.PathIdentity + "/Challenges/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Verify a specific Challenge.
/// </summary>
/// <param name="options"> Update Challenge parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Challenge </returns>
public static ChallengeResource Update(UpdateChallengeOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Verify a specific Challenge.
/// </summary>
/// <param name="options"> Update Challenge parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Challenge </returns>
public static async System.Threading.Tasks.Task<ChallengeResource> UpdateAsync(UpdateChallengeOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Verify a specific Challenge.
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathIdentity"> Unique external identifier of the Entity </param>
/// <param name="pathSid"> A string that uniquely identifies this Challenge. </param>
/// <param name="authPayload"> Optional payload to verify the Challenge </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Challenge </returns>
public static ChallengeResource Update(string pathServiceSid,
string pathIdentity,
string pathSid,
string authPayload = null,
ITwilioRestClient client = null)
{
var options = new UpdateChallengeOptions(pathServiceSid, pathIdentity, pathSid){AuthPayload = authPayload};
return Update(options, client);
}
#if !NET35
/// <summary>
/// Verify a specific Challenge.
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathIdentity"> Unique external identifier of the Entity </param>
/// <param name="pathSid"> A string that uniquely identifies this Challenge. </param>
/// <param name="authPayload"> Optional payload to verify the Challenge </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Challenge </returns>
public static async System.Threading.Tasks.Task<ChallengeResource> UpdateAsync(string pathServiceSid,
string pathIdentity,
string pathSid,
string authPayload = null,
ITwilioRestClient client = null)
{
var options = new UpdateChallengeOptions(pathServiceSid, pathIdentity, pathSid){AuthPayload = authPayload};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a ChallengeResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> ChallengeResource object represented by the provided JSON </returns>
public static ChallengeResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<ChallengeResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// A string that uniquely identifies this Challenge.
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// Account Sid.
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// Service Sid.
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// Entity Sid.
/// </summary>
[JsonProperty("entity_sid")]
public string EntitySid { get; private set; }
/// <summary>
/// Unique external identifier of the Entity
/// </summary>
[JsonProperty("identity")]
public string Identity { get; private set; }
/// <summary>
/// Factor Sid.
/// </summary>
[JsonProperty("factor_sid")]
public string FactorSid { get; private set; }
/// <summary>
/// The date this Challenge was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The date this Challenge was updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The date this Challenge was responded
/// </summary>
[JsonProperty("date_responded")]
public DateTime? DateResponded { get; private set; }
/// <summary>
/// The date-time when this Challenge expires
/// </summary>
[JsonProperty("expiration_date")]
public DateTime? ExpirationDate { get; private set; }
/// <summary>
/// The Status of this Challenge
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public ChallengeResource.ChallengeStatusesEnum Status { get; private set; }
/// <summary>
/// The Reason of this Challenge `status`
/// </summary>
[JsonProperty("responded_reason")]
[JsonConverter(typeof(StringEnumConverter))]
public ChallengeResource.ChallengeReasonsEnum RespondedReason { get; private set; }
/// <summary>
/// Details about the Challenge.
/// </summary>
[JsonProperty("details")]
public object Details { get; private set; }
/// <summary>
/// Hidden details about the Challenge
/// </summary>
[JsonProperty("hidden_details")]
public object HiddenDetails { get; private set; }
/// <summary>
/// The Factor Type of this Challenge
/// </summary>
[JsonProperty("factor_type")]
[JsonConverter(typeof(StringEnumConverter))]
public ChallengeResource.FactorTypesEnum FactorType { get; private set; }
/// <summary>
/// The URL of this resource.
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// Nested resource URLs.
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private ChallengeResource()
{
}
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using Verse;
using Verse.Sound;
using RimWorld;
namespace UnificaMagica
{
// [StaticConstructorOnStartup]
public class ExtThingDef: Verse.ThingDef {
public List<ExtComp> extcomps = new List<ExtComp>();
}
// ExtendedThings are extended with Extended Components (ExtComp and ExtInstComp)
public interface IExtendedThing {
List<ExtInstComp> ExtComps {
get;
set;
}
ExtThingDef def {
get;
set;
}
// initialize ExtComps when creating and loading
void PostMake();
void ExposeData();
}
[StaticConstructorOnStartup]
public class PlantExtended : Plant, IExtendedThing {
protected List<ExtInstComp> extcomps = null; // set during InitializeExtendedComps
// ExtThingDef defint;
public List<ExtInstComp> ExtComps {
get { return this.extcomps; }
set { this.extcomps = value; }
}
public new ExtThingDef def {
get { return (ExtThingDef) base.def; }
set {
ExtThingDef dd = value as ExtThingDef;
if ( dd == null ) {
Log.Error("Can not set a non-ExtThingDef to an IExtendedThing");
Log.Error("Can not set a non-ExtThingDef ("+( value )+") to an IExtendedThing");
}
base.def = value;
}
}
public override void PostMake()
{
Log.Message("PlantExtended.PostMake 1");
base.PostMake();
Log.Message("PlantExtended.PostMake 2");
ExtendedComponent.InitializeExtComps(this);
Log.Message("PlantExtended.PostMake 3");
}
public override void ExposeData()
{
Log.Message("PlantExtended.ExposeData 1");
base.ExposeData();
Log.Message("PlantExtended.ExposeData 2");
if (Scribe.mode == LoadSaveMode.LoadingVars)
{
Log.Message("PlantExtended.ExposeData 2.1");
ExtendedComponent.InitializeExtComps(this);
Log.Message("PlantExtended.ExposeData 2.2");
}
for (int i = 0; i < this.ExtComps.Count; i++)
{
this.ExtComps[i].PostExposeData();
}
Log.Message("PlantExtended.ExposeData 3");
}
public Building_PlantGrower thepot = null;
public List<ExtInstComp> planttraps = new List<ExtInstComp>();
/*
public void Initialize()
{
// Plant Traps
for (int i = 0; i < this.def.comps.Count; i++) {
ThingComp thingComp = (ThingComp)Activator.CreateInstance (this.def.comps [i].compClass);
thingComp.parent = this;
this.comps.Add (thingComp);
thingComp.Initialize (this.def.comps [i]);
}
}
*/
// find the pot this is in
protected bool initPot() {
if ( base.Map == null ) return false;
List<Thing> list = base.Map.thingGrid.ThingsListAt(base.Position);
for (int i = 0; i < list.Count; i++)
{
Thing thing = list[i];
if (thing is Building_PlantGrower ) {
// Log.Warning("PlantTrap found pot");
this.thepot = (Building_PlantGrower)thing;
}
}
// Log.Warning("PlantTrap pot : "+this.thepot);
// Log.Warning("Creating Plant_Trap with properties:");
// Helpers.PrintObject(this.def.planttraps);
//((DruidPlantProperties)this.def.plant).planttraps);
return true;
}
public IEnumerable<IntVec3> alertzone = null;
public void initAlertZone() {
Log.Message("PlantTrap.initAlertZonw 1 ");
Log.Message("PlantTrap.initAlertZonw 1 : the pot "+this.thepot);
float r = this.thepot.def.specialDisplayRadius;
Log.Message("PlantTrap.initAlertZonw 2 ");
this.alertzone = GenRadial.RadialCellsAround (this.Position, r, true);
Log.Message("PlantTrap.initAlertZonw 3 ");
}
// protected int rearmAt = 0;
// ---------------------------------------------------------------------
// From Building_Trap below
// ---------------------------------------------------------------------
// private List<Pawn> touchingPawns = new List<Pawn> ();
//protected bool Armed = true;
protected void Spring(Pawn p, ExtInstComp_PlantTrap _ptp)
{
// Log.Message("PlantTrap.Spring! ");
SoundDef.Named("PlantTrapSpring").PlayOneShot(new TargetInfo(base.Position, base.Map, false));
if (p.Faction != null)
{
p.Faction.TacticalMemory.TrapRevealed(base.Position, base.Map);
}
_ptp.SpringPlantTrap(p,this);
}
public override void Tick ()
{
int curtick = Find.TickManager.TicksGame;
Log.Message("PlantTrap.Tick 1 "+base.LabelMouseover+ " : " + curtick);
//this.TickInterval
if ( curtick % 2000 == 0 ) { this.TickLong(); }
if ( this.thepot == null ) {
if ( this.initPot() == false ) {
Log.Message("PlantTrap.Tick .. map not set on first pass so return");
return;
}
} // Map not set on first pass so return
// only mature trips
Log.Message("PlantTrap.Tick 2 ");
if ( base.Map != null && base.LifeStage == PlantLifeStage.Mature ) {
// check for alert zone initialization
Log.Message("PlantTrap.Tick 2.1");
if ( this.alertzone == null ) {
Log.Message("PlantTrap.Tick 2.1.1");
this.initAlertZone();
Log.Message("PlantTrap.Tick 2.1.2");
}
// find if there is an active trap; reactivate any needing it
bool anyarmed = false;
Log.Message("PlantTrap.Tick 2.2");
// handle all traps
// foreach ( ExtInstComp_PlantTrap ptp in this.def.GetComps<ExtInstComp_PlantTrap>() )
foreach ( ExtInstComp ptp2 in this.ExtComps ) {
ExtInstComp_PlantTrap ptp = ptp2 as ExtInstComp_PlantTrap;
if ( ptp != null ) {
// check for rearm if not armed
// Log.Message("PlantTrap.Tick rearm check "+this.Armed+" " + Find.TickManager.TicksGame +" "+ this.rearmAt+ " " + (Find.TickManager.TicksGame > this.rearmAt ));
Log.Message("PlantTrap.Tick 2.2.1");
if ( ptp.Armed == false && ( ptp.rearmAt != -1 ) && ( curtick > ptp.rearmAt ) ) {
Log.Message("PlantTrap.Tick 2.2.1.1");
ptp.Armed = true;
Log.Message("PlantTrap.Tick 2.2.1.2");
}
// if armed, check alert zones
Log.Message("PlantTrap.Tick 2.2.2");
if ( ptp.Armed == true ) {
Log.Message("PlantTrap.Tick 2.2.2.1");
anyarmed = true;
Log.Message("PlantTrap.Tick 2.2.2.2");
}
Log.Message("PlantTrap.Tick 2.2.3");
}
}
// find all Pawns nearby
Log.Message("PlantTrap.Tick 2.3");
List<Pawn> pawnthings = new List<Pawn>();
Log.Message("PlantTrap.Tick 2.4");
if ( anyarmed ) {
// find all pawns
Log.Message("PlantTrap.Tick 2.4.1");
foreach ( IntVec3 pp in this.alertzone) { // for each spot in alert zone
Log.Message("PlantTrap.Tick 2.4.1.1");
List<Thing> thingList = pp.GetThingList (base.Map);
Log.Message("PlantTrap.Tick 2.4.1.2");
for (int i = 0; i < thingList.Count; i++) {
Log.Message("PlantTrap.Tick 2.4.1.2.1");
Pawn pawn = thingList [i] as Pawn;
Log.Message("PlantTrap.Tick 2.4.1.2.2");
if (pawn != null ) {
Log.Message("PlantTrap.Tick 2.4.1.2.2.1");
pawnthings.Add(pawn);
Log.Message("PlantTrap.Tick 2.4.1.2.2.2");
}
Log.Message("PlantTrap.Tick 2.4.1.2.3");
}
Log.Message("PlantTrap.Tick 2.4.1.3");
}
Log.Message("PlantTrap.Tick 2.4.2");
}
// is anyarmed, chekc
Log.Message("PlantTrap.Tick 2.5");
if ( anyarmed ) {
Log.Message("PlantTrap.Tick 2.5.1");
foreach ( ExtInstComp ptp2 in this.ExtComps ) {
ExtInstComp_PlantTrap ptp = ptp2 as ExtInstComp_PlantTrap;
if ( ptp != null ) {
//foreach ( PlantTrapProperties ptp in ((UnificaMagica.DruidPlantDef)this.def).planttraps ) {
Log.Message("PlantTrap.Tick 2.5.1.1");
if ( ptp.Armed ) {
Log.Message("PlantTrap.Tick 2.5.1.1.1");
foreach ( Pawn pawn in pawnthings ) {
Log.Message("PlantTrap.Tick 2.5.1.1.1.1");
if ( this.CheckSpring (pawn,ptp) ) {
Log.Message("PlantTrap.Tick 2.5.1.1.1.1.1");
if ( ptp.Props.isAoE ) break; // apply only once if AoE
//if ( ((ExtComp_PlantTrap)ptp.props).isAoE ) break; // apply only once if AoE
}
Log.Message("PlantTrap.Tick 2.5.1.1.1.2");
}
Log.Message("PlantTrap.Tick 2.5.1.1.2");
}
Log.Message("PlantTrap.Tick 2.5.1.2");
}
Log.Message("PlantTrap.Tick 2.5.2");
}
}
//delete(pawnthings);
Log.Message("PlantTrap.Tick 2.6");
}
Log.Message("PlantTrap.Tick 3 - End");
}
protected virtual bool CheckSpring (Pawn p, ExtInstComp_PlantTrap _ptp)
{
bool retval = false;
if ( ! _ptp.Armed ) return false;
float sc = this.SpringChance(p);
float rr = Rand.Value;
// Log.Message("PlantTrap.CheckSpring : rand("+rr+") chance("+sc+")");
if (Rand.Value < sc ) { //this.SpringChance (p))
// Log.Message("PlantTrap.CheckSpring : sprung");
retval = true;
this.Spring (p,_ptp);
if (p.Faction == Faction.OfPlayer || p.HostFaction == Faction.OfPlayer) {
Letter let = new Letter ("LetterFriendlyTrapSprungLabel".Translate (new object[] { p.NameStringShort }), "LetterFriendlyTrapSprung".Translate (new object[] { p.NameStringShort }), LetterType.BadNonUrgent, new TargetInfo (base.Position, base.Map, false));
Find.LetterStack.ReceiveLetter (let, null);
}
}
return retval;
}
protected virtual float SpringChance (Pawn p)
{
float num;
if (this.KnowsOfTrap (p)) {
num = 0.004f;
// Log.Message("PlantTrap.SpringChance 1 : "+num);
}
else {
num = this.GetStatValue (StatDefOf.TrapSpringChance, true);
// Log.Message("PlantTrap.SpringChance 1 : "+num);
}
num *= GenMath.LerpDouble (0.4f, 0.8f, 0f, 1f, p.BodySize);
if (p.RaceProps.Animal) {
num *= 0.1f;
}
// Log.Message("PlantTrap.SpringChance chance: "+num+" base is "+StatDefOf.TrapSpringChance);
return Mathf.Clamp01 (num);
}
public bool KnowsOfTrap(Pawn p)
{
if ( this.thepot == null ) {
// Log.Error("can not find pot of plant "+this+" at "+this.Position);
return false;
}
Faction f = this.thepot.Faction;
// Log.Message("PlantTrap.KnowsOfTrap 0 : is faction null "+(f == null));
bool retval = (p.Faction != null && !p.Faction.HostileTo(f)) || (p.Faction == null && p.RaceProps.Animal && !p.InAggroMentalState) || (p.guest != null && p.guest.released);
// Log.Message("PlantTrap.KnowsOfTrap 1 "+retval);
// Log.Message("PlantTrap.KnowsOfTrap 2 "+(p.Faction!= null));
// Log.Message("PlantTrap.KnowsOfTrap 3 "+f);
// Log.Message("PlantTrap.KnowsOfTrap 4 "+p.Faction.HostileTo(f));
//return (p.Faction != null && !p.Faction.HostileTo(base.Faction)) || (p.Faction == null && p.RaceProps.Animal && !p.InAggroMentalState) || (p.guest != null && p.guest.released);
return (p.Faction != null && !p.Faction.HostileTo(f)) || (p.Faction == null && p.RaceProps.Animal && !p.InAggroMentalState) || (p.guest != null && p.guest.released);
}
public override string GetInspectString()
{
string retval = base.GetInspectString();
StringBuilder stringBuilder = new StringBuilder();
Log.Message("PlantExtended.GetInspectString()");
stringBuilder.Append(retval);
//if ( this.def.ExtComps.Count != 0 )
if (this.LifeStage == PlantLifeStage.Growing)
{
stringBuilder.AppendLine("Druid Plant is not mature");
} else if (this.LifeStage == PlantLifeStage.Mature) {
bool fl = false;
foreach ( ExtInstComp ptp2 in this.ExtComps ) {
ExtInstComp_PlantTrap ptp = ptp2 as ExtInstComp_PlantTrap;
if ( ptp != null ) {
if ( ptp.Armed ) { stringBuilder.AppendLine( ptp.Props.ArmedLabel ); fl = true; }
else {
stringBuilder.AppendLine( ptp.Props.ArmedLabel + " in " + ptp.rearmAt + " ticks");
}
}
}
if ( fl == false ) { stringBuilder.AppendLine("No armed traps");
}
}
return stringBuilder.ToString();
}
}
}
| |
/*
* Velcro Physics:
* Copyright (c) 2017 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using Microsoft.Xna.Framework;
using VelcroPhysics.Dynamics.Solver;
using VelcroPhysics.Shared;
using VelcroPhysics.Utilities;
namespace VelcroPhysics.Dynamics.Joints
{
/// <summary>
/// A revolute joint constrains to bodies to share a common point while they
/// are free to rotate about the point. The relative rotation about the shared
/// point is the joint angle. You can limit the relative rotation with
/// a joint limit that specifies a lower and upper angle. You can use a motor
/// to drive the relative rotation about the shared point. A maximum motor torque
/// is provided so that infinite forces are not generated.
/// </summary>
public class RevoluteJoint : Joint
{
private bool _enableLimit;
private bool _enableMotor;
// Solver shared
private Vector3 _impulse;
// Solver temp
private int _indexA;
private int _indexB;
private float _invIA;
private float _invIB;
private float _invMassA;
private float _invMassB;
private LimitState _limitState;
private Vector2 _localCenterA;
private Vector2 _localCenterB;
private float _lowerAngle;
private Mat33 _mass; // effective mass for point-to-point constraint.
private float _maxMotorTorque;
private float _motorImpulse;
private float _motorMass; // effective mass for motor/limit angular constraint.
private float _motorSpeed;
private Vector2 _rA;
private Vector2 _rB;
private float _referenceAngle;
private float _upperAngle;
internal RevoluteJoint()
{
JointType = JointType.Revolute;
}
/// <summary>
/// Constructor of RevoluteJoint.
/// </summary>
/// <param name="bodyA">The first body.</param>
/// <param name="bodyB">The second body.</param>
/// <param name="anchorA">The first body anchor.</param>
/// <param name="anchorB">The second anchor.</param>
/// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param>
public RevoluteJoint(Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, bool useWorldCoordinates = false)
: base(bodyA, bodyB)
{
JointType = JointType.Revolute;
if (useWorldCoordinates)
{
LocalAnchorA = BodyA.GetLocalPoint(anchorA);
LocalAnchorB = BodyB.GetLocalPoint(anchorB);
}
else
{
LocalAnchorA = anchorA;
LocalAnchorB = anchorB;
}
ReferenceAngle = BodyB.Rotation - BodyA.Rotation;
_impulse = Vector3.Zero;
_limitState = LimitState.Inactive;
}
/// <summary>
/// Constructor of RevoluteJoint.
/// </summary>
/// <param name="bodyA">The first body.</param>
/// <param name="bodyB">The second body.</param>
/// <param name="anchor">The shared anchor.</param>
/// <param name="useWorldCoordinates"></param>
public RevoluteJoint(Body bodyA, Body bodyB, Vector2 anchor, bool useWorldCoordinates = false)
: this(bodyA, bodyB, anchor, anchor, useWorldCoordinates) { }
/// <summary>
/// The local anchor point on BodyA
/// </summary>
public Vector2 LocalAnchorA { get; set; }
/// <summary>
/// The local anchor point on BodyB
/// </summary>
public Vector2 LocalAnchorB { get; set; }
public override Vector2 WorldAnchorA
{
get { return BodyA.GetWorldPoint(LocalAnchorA); }
set { LocalAnchorA = BodyA.GetLocalPoint(value); }
}
public override Vector2 WorldAnchorB
{
get { return BodyB.GetWorldPoint(LocalAnchorB); }
set { LocalAnchorB = BodyB.GetLocalPoint(value); }
}
/// <summary>
/// The referance angle computed as BodyB angle minus BodyA angle.
/// </summary>
public float ReferenceAngle
{
get { return _referenceAngle; }
set
{
WakeBodies();
_referenceAngle = value;
}
}
/// <summary>
/// Get the current joint angle in radians.
/// </summary>
public float JointAngle
{
get { return BodyB._sweep.A - BodyA._sweep.A - ReferenceAngle; }
}
/// <summary>
/// Get the current joint angle speed in radians per second.
/// </summary>
public float JointSpeed
{
get { return BodyB._angularVelocity - BodyA._angularVelocity; }
}
/// <summary>
/// Is the joint limit enabled?
/// </summary>
/// <value><c>true</c> if [limit enabled]; otherwise, <c>false</c>.</value>
public bool LimitEnabled
{
get { return _enableLimit; }
set
{
if (_enableLimit == value)
return;
WakeBodies();
_enableLimit = value;
_impulse.Z = 0.0f;
}
}
/// <summary>
/// Get the lower joint limit in radians.
/// </summary>
public float LowerLimit
{
get { return _lowerAngle; }
set
{
if (_lowerAngle == value)
return;
WakeBodies();
_lowerAngle = value;
_impulse.Z = 0.0f;
}
}
/// <summary>
/// Get the upper joint limit in radians.
/// </summary>
public float UpperLimit
{
get { return _upperAngle; }
set
{
if (_upperAngle == value)
return;
WakeBodies();
_upperAngle = value;
_impulse.Z = 0.0f;
}
}
/// <summary>
/// Is the joint motor enabled?
/// </summary>
/// <value><c>true</c> if [motor enabled]; otherwise, <c>false</c>.</value>
public bool MotorEnabled
{
get { return _enableMotor; }
set
{
if (value == _enableMotor)
return;
WakeBodies();
_enableMotor = value;
}
}
/// <summary>
/// Get or set the motor speed in radians per second.
/// </summary>
public float MotorSpeed
{
set
{
if (value == _motorSpeed)
return;
WakeBodies();
_motorSpeed = value;
}
get { return _motorSpeed; }
}
/// <summary>
/// Get or set the maximum motor torque, usually in N-m.
/// </summary>
public float MaxMotorTorque
{
set
{
if (value == _maxMotorTorque)
return;
WakeBodies();
_maxMotorTorque = value;
}
get { return _maxMotorTorque; }
}
/// <summary>
/// Get or set the current motor impulse, usually in N-m.
/// </summary>
public float MotorImpulse
{
get { return _motorImpulse; }
set
{
if (value == _motorImpulse)
return;
WakeBodies();
_motorImpulse = value;
}
}
/// <summary>
/// Set the joint limits, usually in meters.
/// </summary>
/// <param name="lower">The lower limit</param>
/// <param name="upper">The upper limit</param>
public void SetLimits(float lower, float upper)
{
if (lower == _lowerAngle && upper == _upperAngle)
return;
WakeBodies();
_upperAngle = upper;
_lowerAngle = lower;
_impulse.Z = 0.0f;
}
/// <summary>
/// Gets the motor torque in N-m.
/// </summary>
/// <param name="invDt">The inverse delta time</param>
public float GetMotorTorque(float invDt)
{
return invDt * _motorImpulse;
}
public override Vector2 GetReactionForce(float invDt)
{
Vector2 p = new Vector2(_impulse.X, _impulse.Y);
return invDt * p;
}
public override float GetReactionTorque(float invDt)
{
return invDt * _impulse.Z;
}
internal override void InitVelocityConstraints(ref SolverData data)
{
_indexA = BodyA.IslandIndex;
_indexB = BodyB.IslandIndex;
_localCenterA = BodyA._sweep.LocalCenter;
_localCenterB = BodyB._sweep.LocalCenter;
_invMassA = BodyA._invMass;
_invMassB = BodyB._invMass;
_invIA = BodyA._invI;
_invIB = BodyB._invI;
float aA = data.Positions[_indexA].A;
Vector2 vA = data.Velocities[_indexA].V;
float wA = data.Velocities[_indexA].W;
float aB = data.Positions[_indexB].A;
Vector2 vB = data.Velocities[_indexB].V;
float wB = data.Velocities[_indexB].W;
Rot qA = new Rot(aA), qB = new Rot(aB);
_rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
_rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
bool fixedRotation = (iA + iB == 0.0f);
_mass.ex.X = mA + mB + _rA.Y * _rA.Y * iA + _rB.Y * _rB.Y * iB;
_mass.ey.X = -_rA.Y * _rA.X * iA - _rB.Y * _rB.X * iB;
_mass.ez.X = -_rA.Y * iA - _rB.Y * iB;
_mass.ex.Y = _mass.ey.X;
_mass.ey.Y = mA + mB + _rA.X * _rA.X * iA + _rB.X * _rB.X * iB;
_mass.ez.Y = _rA.X * iA + _rB.X * iB;
_mass.ex.Z = _mass.ez.X;
_mass.ey.Z = _mass.ez.Y;
_mass.ez.Z = iA + iB;
_motorMass = iA + iB;
if (_motorMass > 0.0f)
{
_motorMass = 1.0f / _motorMass;
}
if (_enableMotor == false || fixedRotation)
{
_motorImpulse = 0.0f;
}
if (_enableLimit && fixedRotation == false)
{
float jointAngle = aB - aA - ReferenceAngle;
if (Math.Abs(_upperAngle - _lowerAngle) < 2.0f * Settings.AngularSlop)
{
_limitState = LimitState.Equal;
}
else if (jointAngle <= _lowerAngle)
{
if (_limitState != LimitState.AtLower)
{
_impulse.Z = 0.0f;
}
_limitState = LimitState.AtLower;
}
else if (jointAngle >= _upperAngle)
{
if (_limitState != LimitState.AtUpper)
{
_impulse.Z = 0.0f;
}
_limitState = LimitState.AtUpper;
}
else
{
_limitState = LimitState.Inactive;
_impulse.Z = 0.0f;
}
}
else
{
_limitState = LimitState.Inactive;
}
if (Settings.EnableWarmstarting)
{
// Scale impulses to support a variable time step.
_impulse *= data.Step.dtRatio;
_motorImpulse *= data.Step.dtRatio;
Vector2 P = new Vector2(_impulse.X, _impulse.Y);
vA -= mA * P;
wA -= iA * (MathUtils.Cross(_rA, P) + MotorImpulse + _impulse.Z);
vB += mB * P;
wB += iB * (MathUtils.Cross(_rB, P) + MotorImpulse + _impulse.Z);
}
else
{
_impulse = Vector3.Zero;
_motorImpulse = 0.0f;
}
data.Velocities[_indexA].V = vA;
data.Velocities[_indexA].W = wA;
data.Velocities[_indexB].V = vB;
data.Velocities[_indexB].W = wB;
}
internal override void SolveVelocityConstraints(ref SolverData data)
{
Vector2 vA = data.Velocities[_indexA].V;
float wA = data.Velocities[_indexA].W;
Vector2 vB = data.Velocities[_indexB].V;
float wB = data.Velocities[_indexB].W;
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
bool fixedRotation = (iA + iB == 0.0f);
// Solve motor constraint.
if (_enableMotor && _limitState != LimitState.Equal && fixedRotation == false)
{
float Cdot = wB - wA - _motorSpeed;
float impulse = _motorMass * (-Cdot);
float oldImpulse = _motorImpulse;
float maxImpulse = data.Step.dt * _maxMotorTorque;
_motorImpulse = MathUtils.Clamp(_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = _motorImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve limit constraint.
if (_enableLimit && _limitState != LimitState.Inactive && fixedRotation == false)
{
Vector2 Cdot1 = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA);
float Cdot2 = wB - wA;
Vector3 Cdot = new Vector3(Cdot1.X, Cdot1.Y, Cdot2);
Vector3 impulse = -_mass.Solve33(Cdot);
if (_limitState == LimitState.Equal)
{
_impulse += impulse;
}
else if (_limitState == LimitState.AtLower)
{
float newImpulse = _impulse.Z + impulse.Z;
if (newImpulse < 0.0f)
{
Vector2 rhs = -Cdot1 + _impulse.Z * new Vector2(_mass.ez.X, _mass.ez.Y);
Vector2 reduced = _mass.Solve22(rhs);
impulse.X = reduced.X;
impulse.Y = reduced.Y;
impulse.Z = -_impulse.Z;
_impulse.X += reduced.X;
_impulse.Y += reduced.Y;
_impulse.Z = 0.0f;
}
else
{
_impulse += impulse;
}
}
else if (_limitState == LimitState.AtUpper)
{
float newImpulse = _impulse.Z + impulse.Z;
if (newImpulse > 0.0f)
{
Vector2 rhs = -Cdot1 + _impulse.Z * new Vector2(_mass.ez.X, _mass.ez.Y);
Vector2 reduced = _mass.Solve22(rhs);
impulse.X = reduced.X;
impulse.Y = reduced.Y;
impulse.Z = -_impulse.Z;
_impulse.X += reduced.X;
_impulse.Y += reduced.Y;
_impulse.Z = 0.0f;
}
else
{
_impulse += impulse;
}
}
Vector2 P = new Vector2(impulse.X, impulse.Y);
vA -= mA * P;
wA -= iA * (MathUtils.Cross(_rA, P) + impulse.Z);
vB += mB * P;
wB += iB * (MathUtils.Cross(_rB, P) + impulse.Z);
}
else
{
// Solve point-to-point constraint
Vector2 Cdot = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA);
Vector2 impulse = _mass.Solve22(-Cdot);
_impulse.X += impulse.X;
_impulse.Y += impulse.Y;
vA -= mA * impulse;
wA -= iA * MathUtils.Cross(_rA, impulse);
vB += mB * impulse;
wB += iB * MathUtils.Cross(_rB, impulse);
}
data.Velocities[_indexA].V = vA;
data.Velocities[_indexA].W = wA;
data.Velocities[_indexB].V = vB;
data.Velocities[_indexB].W = wB;
}
internal override bool SolvePositionConstraints(ref SolverData data)
{
Vector2 cA = data.Positions[_indexA].C;
float aA = data.Positions[_indexA].A;
Vector2 cB = data.Positions[_indexB].C;
float aB = data.Positions[_indexB].A;
Rot qA = new Rot(aA), qB = new Rot(aB);
float angularError = 0.0f;
float positionError;
bool fixedRotation = (_invIA + _invIB == 0.0f);
// Solve angular limit constraint.
if (_enableLimit && _limitState != LimitState.Inactive && fixedRotation == false)
{
float angle = aB - aA - ReferenceAngle;
float limitImpulse = 0.0f;
if (_limitState == LimitState.Equal)
{
// Prevent large angular corrections
float C = MathUtils.Clamp(angle - _lowerAngle, -Settings.MaxAngularCorrection, Settings.MaxAngularCorrection);
limitImpulse = -_motorMass * C;
angularError = Math.Abs(C);
}
else if (_limitState == LimitState.AtLower)
{
float C = angle - _lowerAngle;
angularError = -C;
// Prevent large angular corrections and allow some slop.
C = MathUtils.Clamp(C + Settings.AngularSlop, -Settings.MaxAngularCorrection, 0.0f);
limitImpulse = -_motorMass * C;
}
else if (_limitState == LimitState.AtUpper)
{
float C = angle - _upperAngle;
angularError = C;
// Prevent large angular corrections and allow some slop.
C = MathUtils.Clamp(C - Settings.AngularSlop, 0.0f, Settings.MaxAngularCorrection);
limitImpulse = -_motorMass * C;
}
aA -= _invIA * limitImpulse;
aB += _invIB * limitImpulse;
}
// Solve point-to-point constraint.
{
qA.Set(aA);
qB.Set(aB);
Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
Vector2 C = cB + rB - cA - rA;
positionError = C.Length();
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
Mat22 K = new Mat22();
K.ex.X = mA + mB + iA * rA.Y * rA.Y + iB * rB.Y * rB.Y;
K.ex.Y = -iA * rA.X * rA.Y - iB * rB.X * rB.Y;
K.ey.X = K.ex.Y;
K.ey.Y = mA + mB + iA * rA.X * rA.X + iB * rB.X * rB.X;
Vector2 impulse = -K.Solve(C);
cA -= mA * impulse;
aA -= iA * MathUtils.Cross(rA, impulse);
cB += mB * impulse;
aB += iB * MathUtils.Cross(rB, impulse);
}
data.Positions[_indexA].C = cA;
data.Positions[_indexA].A = aA;
data.Positions[_indexB].C = cB;
data.Positions[_indexB].A = aB;
return positionError <= Settings.LinearSlop && angularError <= Settings.AngularSlop;
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] Value of GL_DEBUG_CATEGORY_API_ERROR_AMD symbol.
/// </summary>
[RequiredByFeature("GL_AMD_debug_output")]
public const int DEBUG_CATEGORY_API_ERROR_AMD = 0x9149;
/// <summary>
/// [GL] Value of GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD symbol.
/// </summary>
[RequiredByFeature("GL_AMD_debug_output")]
public const int DEBUG_CATEGORY_WINDOW_SYSTEM_AMD = 0x914A;
/// <summary>
/// [GL] Value of GL_DEBUG_CATEGORY_DEPRECATION_AMD symbol.
/// </summary>
[RequiredByFeature("GL_AMD_debug_output")]
public const int DEBUG_CATEGORY_DEPRECATION_AMD = 0x914B;
/// <summary>
/// [GL] Value of GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD symbol.
/// </summary>
[RequiredByFeature("GL_AMD_debug_output")]
public const int DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD = 0x914C;
/// <summary>
/// [GL] Value of GL_DEBUG_CATEGORY_PERFORMANCE_AMD symbol.
/// </summary>
[RequiredByFeature("GL_AMD_debug_output")]
public const int DEBUG_CATEGORY_PERFORMANCE_AMD = 0x914D;
/// <summary>
/// [GL] Value of GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD symbol.
/// </summary>
[RequiredByFeature("GL_AMD_debug_output")]
public const int DEBUG_CATEGORY_SHADER_COMPILER_AMD = 0x914E;
/// <summary>
/// [GL] Value of GL_DEBUG_CATEGORY_APPLICATION_AMD symbol.
/// </summary>
[RequiredByFeature("GL_AMD_debug_output")]
public const int DEBUG_CATEGORY_APPLICATION_AMD = 0x914F;
/// <summary>
/// [GL] Value of GL_DEBUG_CATEGORY_OTHER_AMD symbol.
/// </summary>
[RequiredByFeature("GL_AMD_debug_output")]
public const int DEBUG_CATEGORY_OTHER_AMD = 0x9150;
/// <summary>
/// [GL] glDebugMessageEnableAMD: Binding for glDebugMessageEnableAMD.
/// </summary>
/// <param name="category">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="severity">
/// A <see cref="T:DebugSeverity"/>.
/// </param>
/// <param name="count">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="ids">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="enabled">
/// A <see cref="T:bool"/>.
/// </param>
[RequiredByFeature("GL_AMD_debug_output")]
public static void DebugMessageEnableAMD(int category, DebugSeverity severity, int count, uint[] ids, bool enabled)
{
unsafe {
fixed (uint* p_ids = ids)
{
Debug.Assert(Delegates.pglDebugMessageEnableAMD != null, "pglDebugMessageEnableAMD not implemented");
Delegates.pglDebugMessageEnableAMD(category, (int)severity, count, p_ids, enabled);
LogCommand("glDebugMessageEnableAMD", null, category, severity, count, ids, enabled );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glDebugMessageEnableAMD: Binding for glDebugMessageEnableAMD.
/// </summary>
/// <param name="category">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="severity">
/// A <see cref="T:DebugSeverity"/>.
/// </param>
/// <param name="ids">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="enabled">
/// A <see cref="T:bool"/>.
/// </param>
[RequiredByFeature("GL_AMD_debug_output")]
public static void DebugMessageEnableAMD(int category, DebugSeverity severity, uint[] ids, bool enabled)
{
unsafe {
fixed (uint* p_ids = ids)
{
Debug.Assert(Delegates.pglDebugMessageEnableAMD != null, "pglDebugMessageEnableAMD not implemented");
Delegates.pglDebugMessageEnableAMD(category, (int)severity, ids.Length, p_ids, enabled);
LogCommand("glDebugMessageEnableAMD", null, category, severity, ids.Length, ids, enabled );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glDebugMessageInsertAMD: Binding for glDebugMessageInsertAMD.
/// </summary>
/// <param name="category">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="severity">
/// A <see cref="T:DebugSeverity"/>.
/// </param>
/// <param name="id">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="length">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="buf">
/// A <see cref="T:string"/>.
/// </param>
[RequiredByFeature("GL_AMD_debug_output")]
public static void DebugMessageInsertAMD(int category, DebugSeverity severity, uint id, int length, string buf)
{
Debug.Assert(Delegates.pglDebugMessageInsertAMD != null, "pglDebugMessageInsertAMD not implemented");
Delegates.pglDebugMessageInsertAMD(category, (int)severity, id, length, buf);
LogCommand("glDebugMessageInsertAMD", null, category, severity, id, length, buf );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glDebugMessageCallbackAMD: Binding for glDebugMessageCallbackAMD.
/// </summary>
/// <param name="callback">
/// A <see cref="T:DebugProc"/>.
/// </param>
/// <param name="userParam">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("GL_AMD_debug_output")]
public static void DebugMessageCallbackAMD(DebugProc callback, IntPtr userParam)
{
Debug.Assert(Delegates.pglDebugMessageCallbackAMD != null, "pglDebugMessageCallbackAMD not implemented");
Delegates.pglDebugMessageCallbackAMD(callback, userParam);
LogCommand("glDebugMessageCallbackAMD", null, callback, userParam );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetDebugMessageLogAMD: Binding for glGetDebugMessageLogAMD.
/// </summary>
/// <param name="bufsize">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="categories">
/// A <see cref="T:int[]"/>.
/// </param>
/// <param name="severities">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="ids">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="lengths">
/// A <see cref="T:int[]"/>.
/// </param>
/// <param name="message">
/// A <see cref="T:StringBuilder"/>.
/// </param>
[RequiredByFeature("GL_AMD_debug_output")]
public static uint GetDebugMessageLogAMD(int bufsize, [Out] int[] categories, [Out] uint[] severities, [Out] uint[] ids, [Out] int[] lengths, StringBuilder message)
{
uint retValue;
unsafe {
fixed (int* p_categories = categories)
fixed (uint* p_severities = severities)
fixed (uint* p_ids = ids)
fixed (int* p_lengths = lengths)
{
Debug.Assert(Delegates.pglGetDebugMessageLogAMD != null, "pglGetDebugMessageLogAMD not implemented");
retValue = Delegates.pglGetDebugMessageLogAMD((uint)categories.Length, bufsize, p_categories, p_severities, p_ids, p_lengths, message);
LogCommand("glGetDebugMessageLogAMD", retValue, categories.Length, bufsize, categories, severities, ids, lengths, message );
}
}
DebugCheckErrors(retValue);
return (retValue);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_AMD_debug_output")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glDebugMessageEnableAMD(int category, int severity, int count, uint* ids, [MarshalAs(UnmanagedType.I1)] bool enabled);
[RequiredByFeature("GL_AMD_debug_output")]
[ThreadStatic]
internal static glDebugMessageEnableAMD pglDebugMessageEnableAMD;
[RequiredByFeature("GL_AMD_debug_output")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glDebugMessageInsertAMD(int category, int severity, uint id, int length, string buf);
[RequiredByFeature("GL_AMD_debug_output")]
[ThreadStatic]
internal static glDebugMessageInsertAMD pglDebugMessageInsertAMD;
[RequiredByFeature("GL_AMD_debug_output")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glDebugMessageCallbackAMD(DebugProc callback, IntPtr userParam);
[RequiredByFeature("GL_AMD_debug_output")]
[ThreadStatic]
internal static glDebugMessageCallbackAMD pglDebugMessageCallbackAMD;
[RequiredByFeature("GL_AMD_debug_output")]
[SuppressUnmanagedCodeSecurity]
internal delegate uint glGetDebugMessageLogAMD(uint count, int bufsize, int* categories, uint* severities, uint* ids, int* lengths, StringBuilder message);
[RequiredByFeature("GL_AMD_debug_output")]
[ThreadStatic]
internal static glGetDebugMessageLogAMD pglGetDebugMessageLogAMD;
}
}
}
| |
namespace XenAdmin.Dialogs
{
partial class InstallCertificateDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InstallCertificateDialog));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.labelKeyBlurb = new System.Windows.Forms.Label();
this.labelKey = new System.Windows.Forms.Label();
this.textBoxKey = new System.Windows.Forms.TextBox();
this.buttonBrowseKey = new System.Windows.Forms.Button();
this.labelKeyError = new System.Windows.Forms.Label();
this.labelCertificate = new System.Windows.Forms.Label();
this.textBoxCertificate = new System.Windows.Forms.TextBox();
this.buttonBrowseCertificate = new System.Windows.Forms.Button();
this.labelChain = new System.Windows.Forms.Label();
this.dataGridViewCertificates = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx();
this.columnCertificate = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonAddCertificate = new System.Windows.Forms.Button();
this.buttonRemove = new System.Windows.Forms.Button();
this.labelChainError = new System.Windows.Forms.Label();
this.buttonInstall = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.tlpActionProgress = new System.Windows.Forms.TableLayoutPanel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.labelActionProgress = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.labelCertificateError = new System.Windows.Forms.Label();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewCertificates)).BeginInit();
this.tlpActionProgress.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.labelKeyBlurb, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.labelKey, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.textBoxKey, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.buttonBrowseKey, 2, 1);
this.tableLayoutPanel1.Controls.Add(this.labelKeyError, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.labelCertificate, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.textBoxCertificate, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.buttonBrowseCertificate, 2, 3);
this.tableLayoutPanel1.Controls.Add(this.labelChain, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.dataGridViewCertificates, 0, 6);
this.tableLayoutPanel1.Controls.Add(this.buttonAddCertificate, 2, 6);
this.tableLayoutPanel1.Controls.Add(this.buttonRemove, 2, 7);
this.tableLayoutPanel1.Controls.Add(this.labelChainError, 0, 9);
this.tableLayoutPanel1.Controls.Add(this.buttonInstall, 1, 10);
this.tableLayoutPanel1.Controls.Add(this.buttonCancel, 2, 10);
this.tableLayoutPanel1.Controls.Add(this.tlpActionProgress, 0, 12);
this.tableLayoutPanel1.Controls.Add(this.progressBar1, 0, 11);
this.tableLayoutPanel1.Controls.Add(this.labelCertificateError, 1, 4);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// labelKeyBlurb
//
resources.ApplyResources(this.labelKeyBlurb, "labelKeyBlurb");
this.tableLayoutPanel1.SetColumnSpan(this.labelKeyBlurb, 3);
this.labelKeyBlurb.Name = "labelKeyBlurb";
//
// labelKey
//
resources.ApplyResources(this.labelKey, "labelKey");
this.labelKey.Name = "labelKey";
//
// textBoxKey
//
resources.ApplyResources(this.textBoxKey, "textBoxKey");
this.textBoxKey.Name = "textBoxKey";
this.textBoxKey.TextChanged += new System.EventHandler(this.textBoxKey_TextChanged);
//
// buttonBrowseKey
//
resources.ApplyResources(this.buttonBrowseKey, "buttonBrowseKey");
this.buttonBrowseKey.Name = "buttonBrowseKey";
this.buttonBrowseKey.UseVisualStyleBackColor = true;
this.buttonBrowseKey.Click += new System.EventHandler(this.buttonBrowseKey_Click);
//
// labelKeyError
//
resources.ApplyResources(this.labelKeyError, "labelKeyError");
this.labelKeyError.AutoEllipsis = true;
this.labelKeyError.ForeColor = System.Drawing.Color.Red;
this.labelKeyError.Name = "labelKeyError";
//
// labelCertificate
//
resources.ApplyResources(this.labelCertificate, "labelCertificate");
this.labelCertificate.Name = "labelCertificate";
//
// textBoxCertificate
//
resources.ApplyResources(this.textBoxCertificate, "textBoxCertificate");
this.textBoxCertificate.Name = "textBoxCertificate";
this.textBoxCertificate.TextChanged += new System.EventHandler(this.textBoxCertificate_TextChanged);
//
// buttonBrowseCertificate
//
resources.ApplyResources(this.buttonBrowseCertificate, "buttonBrowseCertificate");
this.buttonBrowseCertificate.Name = "buttonBrowseCertificate";
this.buttonBrowseCertificate.UseVisualStyleBackColor = true;
this.buttonBrowseCertificate.Click += new System.EventHandler(this.buttonBrowseCertificate_Click);
//
// labelChain
//
resources.ApplyResources(this.labelChain, "labelChain");
this.tableLayoutPanel1.SetColumnSpan(this.labelChain, 3);
this.labelChain.Name = "labelChain";
//
// dataGridViewCertificates
//
resources.ApplyResources(this.dataGridViewCertificates, "dataGridViewCertificates");
this.dataGridViewCertificates.AllowUserToResizeColumns = false;
this.dataGridViewCertificates.BackgroundColor = System.Drawing.SystemColors.Window;
this.dataGridViewCertificates.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dataGridViewCertificates.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.dataGridViewCertificates.ColumnHeadersVisible = false;
this.dataGridViewCertificates.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.columnCertificate});
this.tableLayoutPanel1.SetColumnSpan(this.dataGridViewCertificates, 2);
this.dataGridViewCertificates.Name = "dataGridViewCertificates";
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Segoe UI", 9F);
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridViewCertificates.RowHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.tableLayoutPanel1.SetRowSpan(this.dataGridViewCertificates, 3);
this.dataGridViewCertificates.SelectionChanged += new System.EventHandler(this.dataGridViewCertificates_SelectionChanged);
//
// columnCertificate
//
resources.ApplyResources(this.columnCertificate, "columnCertificate");
this.columnCertificate.Name = "columnCertificate";
//
// buttonAddCertificate
//
resources.ApplyResources(this.buttonAddCertificate, "buttonAddCertificate");
this.buttonAddCertificate.Name = "buttonAddCertificate";
this.buttonAddCertificate.UseVisualStyleBackColor = true;
this.buttonAddCertificate.Click += new System.EventHandler(this.buttonAddCertificate_Click);
//
// buttonRemove
//
resources.ApplyResources(this.buttonRemove, "buttonRemove");
this.buttonRemove.Name = "buttonRemove";
this.buttonRemove.UseVisualStyleBackColor = true;
this.buttonRemove.Click += new System.EventHandler(this.buttonRemove_Click);
//
// labelChainError
//
resources.ApplyResources(this.labelChainError, "labelChainError");
this.labelChainError.AutoEllipsis = true;
this.tableLayoutPanel1.SetColumnSpan(this.labelChainError, 2);
this.labelChainError.ForeColor = System.Drawing.Color.Red;
this.labelChainError.Name = "labelChainError";
//
// buttonInstall
//
resources.ApplyResources(this.buttonInstall, "buttonInstall");
this.buttonInstall.Name = "buttonInstall";
this.buttonInstall.UseVisualStyleBackColor = true;
this.buttonInstall.Click += new System.EventHandler(this.buttonInstall_Click);
//
// buttonCancel
//
resources.ApplyResources(this.buttonCancel, "buttonCancel");
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// tlpActionProgress
//
resources.ApplyResources(this.tlpActionProgress, "tlpActionProgress");
this.tableLayoutPanel1.SetColumnSpan(this.tlpActionProgress, 3);
this.tlpActionProgress.Controls.Add(this.pictureBox1, 0, 0);
this.tlpActionProgress.Controls.Add(this.labelActionProgress, 1, 0);
this.tlpActionProgress.Name = "tlpActionProgress";
//
// pictureBox1
//
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// labelActionProgress
//
resources.ApplyResources(this.labelActionProgress, "labelActionProgress");
this.labelActionProgress.Name = "labelActionProgress";
//
// progressBar1
//
resources.ApplyResources(this.progressBar1, "progressBar1");
this.tableLayoutPanel1.SetColumnSpan(this.progressBar1, 3);
this.progressBar1.ForeColor = System.Drawing.Color.DarkSlateBlue;
this.progressBar1.Name = "progressBar1";
//
// labelCertificateError
//
resources.ApplyResources(this.labelCertificateError, "labelCertificateError");
this.labelCertificateError.ForeColor = System.Drawing.Color.Red;
this.labelCertificateError.Name = "labelCertificateError";
//
// InstallCertificateDialog
//
resources.ApplyResources(this, "$this");
this.CancelButton = this.buttonCancel;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "InstallCertificateDialog";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewCertificates)).EndInit();
this.tlpActionProgress.ResumeLayout(false);
this.tlpActionProgress.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label labelKeyBlurb;
private System.Windows.Forms.Label labelKey;
private System.Windows.Forms.TextBox textBoxKey;
private System.Windows.Forms.Button buttonBrowseKey;
private System.Windows.Forms.Label labelChain;
private System.Windows.Forms.Label labelKeyError;
private System.Windows.Forms.Button buttonAddCertificate;
private System.Windows.Forms.Label labelChainError;
private System.Windows.Forms.Button buttonInstall;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.TableLayoutPanel tlpActionProgress;
private System.Windows.Forms.Label labelActionProgress;
private System.Windows.Forms.Button buttonRemove;
private Controls.DataGridViewEx.DataGridViewEx dataGridViewCertificates;
private System.Windows.Forms.DataGridViewTextBoxColumn columnCertificate;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label labelCertificate;
private System.Windows.Forms.TextBox textBoxCertificate;
private System.Windows.Forms.Button buttonBrowseCertificate;
private System.Windows.Forms.Label labelCertificateError;
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Nick Berard, http://www.coderjournal.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// All code in this file requires .NET Framework 2.0 or later.
#if !NET_1_1 && !NET_1_0
[assembly: Elmah.Scc("$Id: MySqlErrorLog.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Collections;
using System.Data;
using MySql.Data.MySqlClient;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses
/// <a href="http://www.mysql.com/">MySQL</a> as its backing store.
/// </summary>
public class MySqlErrorLog : ErrorLog
{
private readonly string _connectionString;
private const int _maxAppNameLength = 60;
/// <summary>
/// Initializes a new instance of the <see cref="SqlErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public MySqlErrorLog(IDictionary config)
{
if (config == null)
throw new ArgumentNullException("config");
string connectionString = ConnectionStringHelper.GetConnectionString(config);
//
// If there is no connection string to use then throw an
// exception to abort construction.
//
if (connectionString.Length == 0)
throw new ApplicationException("Connection string is missing for the SQL error log.");
_connectionString = connectionString;
//
// Set the application name as this implementation provides
// per-application isolation over a single store.
//
string appName = Mask.NullString((string)config["applicationName"]);
if (appName.Length > _maxAppNameLength)
{
throw new ApplicationException(string.Format(
"Application name is too long. Maximum length allowed is {0} characters.",
_maxAppNameLength.ToString("N0")));
}
ApplicationName = appName;
}
/// <summary>
/// Initializes a new instance of the <see cref="SqlErrorLog"/> class
/// to use a specific connection string for connecting to the database.
/// </summary>
public MySqlErrorLog(string connectionString)
{
if (connectionString == null)
throw new ArgumentNullException("connectionString");
if (connectionString.Length == 0)
throw new ArgumentException(null, "connectionString");
_connectionString = connectionString;
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "MySQL Server Error Log"; }
}
/// <summary>
/// Gets the connection string used by the log to connect to the database.
/// </summary>
public virtual string ConnectionString
{
get { return _connectionString; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Use the stored procedure called by this implementation to set a
/// policy on how long errors are kept in the log. The default
/// implementation stores all errors for an indefinite time.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
string errorXml = ErrorXml.EncodeString(error);
Guid id = Guid.NewGuid();
using (MySqlConnection connection = new MySqlConnection(ConnectionString))
using (MySqlCommand command = Commands.LogError(
id, ApplicationName,
error.HostName, error.Type, error.Source, error.Message, error.User,
error.StatusCode, error.Time.ToUniversalTime(), errorXml))
{
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
return id.ToString();
}
}
internal override void Delete(Guid id)
{
throw new NotImplementedException();
}
public override int GetErrors(int pageIndex, int pageSize, string filter, IList errorEntryList)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns a page of errors from the databse in descending order
/// of logged time.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
using (MySqlConnection connection = new MySqlConnection(ConnectionString))
using (MySqlCommand command = Commands.GetErrorsXml(ApplicationName, pageIndex, pageSize))
{
command.Connection = connection;
connection.Open();
using (MySqlDataReader reader = command.ExecuteReader())
{
Debug.Assert(reader != null);
if (errorEntryList != null)
{
while (reader.Read())
{
Error error = new Error();
error.ApplicationName = reader["Application"].ToString();
error.HostName = reader["Host"].ToString();
error.Type = reader["Type"].ToString();
error.Source = reader["Source"].ToString();
error.Message = reader["Message"].ToString();
error.User = reader["User"].ToString();
error.StatusCode = Convert.ToInt32(reader["StatusCode"]);
error.Time = Convert.ToDateTime(reader.GetString("TimeUtc")).ToLocalTime();
errorEntryList.Add(new ErrorLogEntry(this, reader["ErrorId"].ToString(), error));
}
}
reader.Close();
}
return (int)command.Parameters["TotalCount"].Value;
}
}
/// <summary>
/// Returns the specified error from the database, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (id.Length == 0)
throw new ArgumentException(null, "id");
Guid errorGuid;
try
{
errorGuid = new Guid(id);
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, "id", e);
}
string errorXml = null;
using (MySqlConnection connection = new MySqlConnection(ConnectionString))
using (MySqlCommand command = Commands.GetErrorXml(ApplicationName, errorGuid))
{
command.Connection = connection;
connection.Open();
using (MySqlDataReader reader = command.ExecuteReader())
{
Debug.Assert(reader != null);
while (reader.Read())
{
errorXml = reader.GetString("AllXml");
}
reader.Close();
}
}
if (errorXml == null)
return null;
Error error = ErrorXml.DecodeString(errorXml);
return new ErrorLogEntry(this, id, error);
}
private static class Commands
{
public static MySqlCommand LogError(
Guid id,
string appName,
string hostName,
string typeName,
string source,
string message,
string user,
int statusCode,
DateTime time,
string xml)
{
MySqlCommand command = new MySqlCommand("elmah_LogError");
command.CommandType = CommandType.StoredProcedure;
MySqlParameterCollection parameters = command.Parameters;
parameters.Add("ErrorId", MySqlDbType.String, 36).Value = id.ToString();
parameters.Add("Application", MySqlDbType.VarChar, _maxAppNameLength).Value = appName.Substring(0, Math.Min(_maxAppNameLength, appName.Length));
parameters.Add("Host", MySqlDbType.VarChar, 30).Value = hostName.Substring(0, Math.Min(30, hostName.Length));
parameters.Add("Type", MySqlDbType.VarChar, 100).Value = typeName.Substring(0, Math.Min(100, typeName.Length));
parameters.Add("Source", MySqlDbType.VarChar, 60).Value = source.Substring(0, Math.Min(60, source.Length));
parameters.Add("Message", MySqlDbType.VarChar, 500).Value = message.Substring(0, Math.Min(500, message.Length));
parameters.Add("User", MySqlDbType.VarChar, 50).Value = user.Substring(0, Math.Min(50, user.Length));
parameters.Add("AllXml", MySqlDbType.Text).Value = xml;
parameters.Add("StatusCode", MySqlDbType.Int32).Value = statusCode;
parameters.Add("TimeUtc", MySqlDbType.Datetime).Value = time;
return command;
}
public static MySqlCommand GetErrorXml(string appName, Guid id)
{
MySqlCommand command = new MySqlCommand("elmah_GetErrorXml");
command.CommandType = CommandType.StoredProcedure;
MySqlParameterCollection parameters = command.Parameters;
parameters.Add("Id", MySqlDbType.String, 36).Value = id.ToString();
parameters.Add("App", MySqlDbType.VarChar, _maxAppNameLength).Value = appName.Substring(0, Math.Min(_maxAppNameLength, appName.Length));
return command;
}
public static MySqlCommand GetErrorsXml(string appName, int pageIndex, int pageSize)
{
MySqlCommand command = new MySqlCommand("elmah_GetErrorsXml");
command.CommandType = CommandType.StoredProcedure;
MySqlParameterCollection parameters = command.Parameters;
parameters.Add("App", MySqlDbType.VarChar, _maxAppNameLength).Value = appName.Substring(0, Math.Min(_maxAppNameLength, appName.Length));
parameters.Add("PageIndex", MySqlDbType.Int32).Value = pageIndex;
parameters.Add("PageSize", MySqlDbType.Int32).Value = pageSize;
parameters.Add("TotalCount", MySqlDbType.Int32).Direction = ParameterDirection.Output;
return command;
}
public static void GetErrorsXmlOutputs(MySqlCommand command, out int totalCount)
{
Debug.Assert(command != null);
totalCount = (int)command.Parameters["TotalCount"].Value;
}
}
}
}
#endif //!NET_1_1 && !NET_1_0
| |
using System;
using System.Xml.Serialization;
using System.IO;
using MathNet.Numerics.LinearAlgebra;
namespace RoomAliveToolkit
{
public class Matrix
{
protected int m, n, mn;
protected double[] data;
protected Matrix squareWorkMatrix1, workColumn1, mbymWorkMatrix1;
protected int[] workIndx1;
public Matrix() {}
public Matrix(int m, int n)
{
this.m = m;
this.n = n;
mn = m*n;
data = new double[mn];
}
public Matrix(Matrix A)
{
m = A.m;
n = A.n;
mn = m*n;
data = new double[mn];
Copy(A);
}
public static Matrix Identity(int m, int n)
{
var A = new Matrix(m, n);
A.Identity();
return A;
}
public static Matrix Zero(int m, int n)
{
var A = new Matrix(m, n);
A.Zero();
return A;
}
// properties
// ValuesByColumn will be serialized to XML
public double[][] ValuesByColumn
{
get
{
double[][] A = new double[n][];
for (int j = 0; j < n; j++)
A[j] = new double[m];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
A[j][i] = this[i,j];
return A;
}
set
{
double[][] A = value;
n = A.Length;
m = A[0].Length;
mn = m*n;
data = new double[mn];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
this[i,j] = A[j][i];
// should verify that each column is same length...
squareWorkMatrix1 = null;
workColumn1 = null;
mbymWorkMatrix1 = null;
workIndx1 = null;
}
}
public int Rows
{
get { return m; }
}
public int Cols
{
get { return n; }
}
public int Size
{
get { return mn; }
}
// indexers
public double this[int i, int j]
{
get { return data[i*n + j]; }
set { data[i*n + j] = value; }
}
public double this[int i]
{
get { return data[i]; }
set { data[i] = value; }
}
public float[] AsFloatArray()
{
float[] array = new float[mn];
for (int i = 0; i < mn; i++)
{
array[i] = (float)data[i];
}
return array;
}
// copy
public void Copy(Matrix A)
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
this[i,j] = A[i,j];
}
public static void CopyRange(Matrix A, int ai, int aj, int m, int n, Matrix B, int bi, int bj)
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
B[bi + i,bj + j] = A[ai + i,aj + j];
}
public void Copy(int bi, int bj, Matrix A) { CopyRange(A, 0, 0, A.Rows, A.Cols, this, bi, bj); }
public void Copy(int bi, int bj, Matrix A, int ai, int aj, int rows, int cols) { CopyRange(A, ai, aj, rows, cols, this, bi, bj); }
public static void CopyRow(Matrix A, int row, Matrix B)
{
for (int j = 0; j < A.n; j++)
B.data[j] = A[row,j];
}
public void CopyRow(Matrix A, int row) { CopyRow(A, row, this); }
public static void CopyCol(Matrix A, int col, Matrix B)
{
for (int i = 0; i < A.m; i++)
B.data[i] = A[i,col];
}
public void CopyCol(Matrix A, int col) { CopyCol(A, col, this); }
public static void CopyDiag(Matrix A, Matrix B)
{
int maxd = (A.m > A.n) ? A.m : A.n;
for (int i = 0; i < maxd; i++)
B.data[i] = A[i,i];
}
public void CopyDiag(Matrix A) { CopyDiag(A, this); }
public void Diag(Matrix A, Matrix d)
{
A.Zero();
for (int i = 0; i < A.m; i++)
A[i, i] = d[i];
}
public void Diag(Matrix d)
{
Diag(this, d);
}
// equals
public static bool Equals(Matrix A, Matrix B)
{
for (int i = 0; i < A.mn; i++)
if (A.data[i] != B.data[i]) return false;
return true;
}
public bool Equals(Matrix A) { return Equals(A, this); }
// change shape
public static void Transpose(Matrix A, Matrix B)
{
if (A != B)
{
for (int i = 0; i < A.m; i++)
for (int j = 0; j < A.n; j++)
B[j,i] = A[i,j];
}
else // must be square
{
double s;
for (int i = 0; i < A.m; i++)
for (int j = 0; j < i; j++)
{
s = A[i,j];
A[i,j] = A[j,i];
A[j,i] = s;
}
A.squareWorkMatrix1 = null;
A.workColumn1 = null;
A.workIndx1 = null;
}
}
public void Transpose(Matrix A) { Transpose(A, this); }
public void Transpose() { Transpose(this, this); }
public static void Reshape(Matrix A, Matrix B)
{
int k = 0;
for (int i = 0; i < A.m; i++)
for (int j = 0; j < A.n; j++)
B.data[k++] = A[i,j];
}
public void Reshape(Matrix A) { Reshape(A, this); }
// matrix-scalar ops
public static void Identity(Matrix A)
{
for (int i = 0; i < A.m; i++)
for (int j = 0; j < A.n; j++)
if (i == j)
A[i,j] = 1.0;
else
A[i,j] = 0.0;
}
public void Identity() { Identity(this); }
public static void Set(Matrix A, double c)
{
for (int i = 0; i < A.mn; i++)
A.data[i] = c;
}
public void Set(double c) { Set(this, c); }
public void Zero() { Set(0.0); }
public void Randomize()
{
System.Random rnd = new System.Random();
for (int i = 0; i < mn; i++)
data[i] = rnd.NextDouble();
}
public void Linspace(double x0, double x1)
{
double dx = (x1 - x0) / (double)(mn - 1);
for (int i = 0; i < mn; i++)
data[i] = x0 + dx * i;
}
public static void Pow(Matrix A, double c, Matrix B)
{
for (int i = 0; i < A.mn; i++)
B.data[i] = Math.Pow(A.data[i], c);
}
public void Pow(Matrix A, double c) { Pow(A, c, this);}
public void Pow(double c) { Pow(this, c, this); }
public static void Exp(Matrix A, Matrix B)
{
for (int i = 0; i < A.mn; i++)
B.data[i] = Math.Exp(A.data[i]);
}
public void Exp(Matrix A) { Exp(A, this);}
public void Exp() { Exp(this, this); }
public static void Log(Matrix A, Matrix B)
{
for (int i = 0; i < A.mn; i++)
B.data[i] = Math.Log(A.data[i]);
}
public void Log(Matrix A) { Log(A, this);}
public void Log() { Log(this, this); }
public static void Abs(Matrix A, Matrix B)
{
for (int i = 0; i < A.mn; i++)
B.data[i] = Math.Abs(A.data[i]);
}
public void Abs(Matrix A) { Abs(A, this);}
public void Abs() { Abs(this, this); }
public static void Add(Matrix A, double c, Matrix B)
{
for (int i = 0; i < A.mn; i++)
B.data[i] = c + A.data[i];
}
public void Add(Matrix A, double c) { Add(A, c, this);}
public void Add(double c) { Add(this, c, this); }
public static void Scale(Matrix A, double c, Matrix B)
{
for (int i = 0; i < A.mn; i++)
B.data[i] = c * A.data[i];
}
public void Scale(Matrix A, double c) { Scale(A, c, this);}
public void Scale(double c) { Scale(this, c, this); }
public static void ScaleAdd(Matrix A, double c, Matrix B)
{
for (int i = 0; i < A.mn; i++)
B.data[i] += c * A.data[i];
}
public void ScaleAdd(Matrix A, double c) { ScaleAdd(A, c, this);}
public void ScaleAdd(double c) { ScaleAdd(this, c, this); }
public static void Reciprocal(Matrix A, Matrix B)
{
for (int i = 0; i < A.mn; i++)
B.data[i] = 1.0 / A.data[i];
}
public void Reciprocal(Matrix A) { Reciprocal(A, this); }
public void Reciprocal() { Reciprocal(this, this); }
public static void Bound(Matrix A, Matrix B, Matrix C)
{
for (int i = 0; i < A.mn; i++)
{
if (C.data[i] < A.data[i])
C.data[i] = A.data[i];
if (C.data[i] > B.data[i])
C.data[i] = B.data[i];
}
}
// limits data between elements of A and B
public void Bound(Matrix A, Matrix B) { Bound(A, B, this); }
// matrix-matrix elementwise ops
public static void Add(Matrix A, Matrix B, Matrix C)
{
for (int i = 0; i < A.Size; i++)
C.data[i] = A.data[i] + B.data[i];
}
public void Add(Matrix A, Matrix B) { Add(A, B, this); }
public void Add(Matrix B) { Add(this, B, this); }
public static void Sub(Matrix A, Matrix B, Matrix C)
{
for (int i = 0; i < A.mn; i++)
C.data[i] = A.data[i] - B.data[i];
}
public void Sub(Matrix A, Matrix B) { Sub(A, B, this);}
public void Sub(Matrix B) { Sub(this, B, this); }
public static void ElemMult(Matrix A, Matrix B, Matrix C)
{
for (int i = 0; i < A.mn; i++)
C.data[i] = A.data[i] * B.data[i];
}
public void ElemMult(Matrix A, Matrix B) { ElemMult(A, B, this);}
public void ElemMult(Matrix B) { ElemMult(this, B, this); }
public static void Divide(Matrix A, Matrix B, Matrix C)
{
for (int i = 0; i < A.mn; i++)
C.data[i] = A.data[i] / B.data[i];
}
public void Divide(Matrix A, Matrix B) { Divide(A, B, this);}
public void Divide(Matrix B) { Divide(this, B, this); }
// vector ops
public static double Dot(Matrix A, Matrix B)
{
double sum = 0.0;
for (int i = 0; i < A.mn; i++)
sum += A.data[i] * B.data[i];
return sum;
}
public double Dot(Matrix B) { return Dot(this, B); }
public static void Outer(Matrix A, Matrix B, Matrix C)
{
for (int i = 0; i < C.m; i++)
for (int j = 0; j < C.n; j++)
C[i,j] = A.data[i] * B.data[j];
}
public void Outer(Matrix A, Matrix B) { Outer(A, B, this); }
public static void Cross(Matrix A, Matrix B, Matrix C)
{
C.data[0] = A.data[1]*B.data[2] - A.data[2]*B.data[1];
C.data[1] = A.data[2]*B.data[0] - A.data[0]*B.data[2];
C.data[2] = A.data[0]*B.data[1] - A.data[1]*B.data[0];
}
public void Cross(Matrix A, Matrix B) { Cross(A, B, this); }
// matrix-matrix ops
public static void Mult(Matrix A, Matrix B, Matrix C)
{
for (int i = 0; i < A.m; i++)
for (int j = 0; j < B.n; j++)
{
double sum = 0;
for (int k = 0; k < A.n; k++)
sum += A[i,k] * B[k,j];
C[i, j] = sum;
}
}
public void Mult(Matrix A, Matrix B) { Mult(A, B, this); }
public static void MultAAT(Matrix A, Matrix B, Matrix C)
{
for (int i = 0; i < A.m; i++)
for (int j = 0; j < B.m; j++) // B.n
{
double sum = 0;
for (int k = 0; k < A.n; k++)
sum += A[i,k] * B[j,k];
C[i, j] = sum;
}
}
public void MultAAT(Matrix A, Matrix B) { MultAAT(A, B, this); }
public static void MultATA(Matrix A, Matrix B, Matrix C)
{
for (int i = 0; i < A.n; i++) // A.m
for (int j = 0; j < B.n; j++)
{
double sum = 0;
for (int k = 0; k < A.m; k++) // A.n
sum += A[k,i] * B[k,j];
C[i, j] = sum;
}
}
public void MultATA(Matrix A, Matrix B) { MultATA(A, B, this); }
public static Matrix<double> ToMathNet(Matrix A)
{
var B = Matrix<double>.Build.Dense(A.Rows, A.Cols);
for (int i = 0; i < A.Rows; i++)
for (int j = 0; j < A.Cols; j++)
B[i, j] = A[i, j];
return B;
}
public static void FromMathNet(Matrix<double> A, Matrix B)
{
for (int i = 0; i < A.RowCount; i++)
for (int j = 0; j < A.ColumnCount; j++)
B[i, j] = A[i, j];
}
public static void FromMathNet(Vector<double> a, Matrix B)
{
for (int i = 0; i < a.Count; i++)
B[i] = a[i];
}
public void Inverse(Matrix A)
{
// invert A and store in this
var Anet = ToMathNet(A);
var inverse = Anet.Inverse();
FromMathNet(inverse, this);
}
public static double Det3x3(Matrix A)
{
double a = A[0, 0];
double b = A[0, 1];
double c = A[0, 2];
double d = A[1, 0];
double e = A[1, 1];
double f = A[1, 2];
double g = A[2, 0];
double h = A[2, 1];
double i = A[2, 2];
return (a * e * i + b * f * g + c * d * h) - (c * e * g + b * d * i + a * f * h);
}
public double Det3x3()
{
return Det3x3(this);
}
public void Eig(Matrix v, Matrix d)
{
//Eig(this, v, d);
var evd = ToMathNet(this).Evd();
FromMathNet(evd.EigenVectors, v);
for (int i = 0; i < this.Rows; i++)
d[i] = evd.D[i, i];
}
public void Eig2x2(Matrix A, Matrix v, Matrix D)
{
double a = A[0, 0];
double b = A[0, 1];
double c = A[1, 0];
double d = A[1, 1];
// solve det(A - l*I) = 0 for eigenvalues l
double s = Math.Sqrt((a + d) * (a + d) + 4 * (b * c - a * d));
D[0] = (a + d + s) / 2;
D[1] = (a + d - s) / 2;
// solve for eigenvectors v in (A - l*I)*v = 0 for each eigenvalue
// set v1 = 1.0
double v0, n;
// first eigenvector
v0 = (D[0] - d) / c;
n = Math.Sqrt(v0 * v0 + 1);
v[0, 0] = v0 / n;
v[1, 0] = 1.0 / n;
// second eigenvector
v0 = (D[1] - d) / c;
n = Math.Sqrt(v0 * v0 + 1);
v[0, 1] = v0 / n;
v[1, 1] = 1.0 / n;
}
public void Eig2x2(Matrix v, Matrix d) { Eig2x2(this, v, d); }
public void SVD(Matrix U, Matrix w, Matrix V)
{
//SVD(this, U, w, V);
var svd = ToMathNet(this).Svd();
FromMathNet(svd.U, U);
FromMathNet(svd.S, w);
FromMathNet(svd.VT.Transpose(), V);
}
public static void LeastSquares(Matrix x, Matrix A, Matrix b)
{
// use svd
// for overdetermined systems A*x = b
// x = V * diag(1/wj) * U T * b
// NRC p. 66
int m = A.m;
int n = A.n;
Matrix U = new Matrix(m, n), V = new Matrix(n, n), w = new Matrix(n, 1), W = new Matrix(n, n);
A.SVD(U, w, V);
w.Reciprocal();
W.Diag(w);
Matrix M = new Matrix(n, n);
M.Mult(V, W);
Matrix N = new Matrix(n, m);
N.MultAAT(M, U);
x.Mult(N, b);
}
public void LeastSquares(Matrix A, Matrix b)
{
LeastSquares(this, A, b);
}
// rotation conversions
public static void Rot2D(Matrix A, double theta)
{
// clockwise rotation
double s = Math.Sin(theta);
double c = Math.Cos(theta);
A[0, 0] = c;
A[1, 0] = s;
A[0, 1] = -s;
A[1, 1] = c;
}
public void Rot2D(double theta)
{
Rot2D(this, theta);
}
public static void RotEuler2Matrix(double x, double y, double z, Matrix A)
{
double s1 = Math.Sin(x);
double s2 = Math.Sin(y);
double s3 = Math.Sin(z);
double c1 = Math.Cos(x);
double c2 = Math.Cos(y);
double c3 = Math.Cos(z);
A[0,0] = c3*c2;
A[0,1] = -s3*c1 + c3*s2*s1;
A[0,2] = s3*s1 + c3*s2*c1;
A[1,0] = s3*c2;
A[1,1] = c3*c1 + s3*s2*s1;
A[1,2] = -c3*s1 + s3*s2*c1;
A[2,0] = -s2;
A[2,1] = c2*s1;
A[2,2] = c2*c1;
}
public void RotEuler2Matrix(double x, double y, double z) { RotEuler2Matrix(x, y, z, this); }
public static void RotFromTo2Quat(Matrix x, Matrix y, Matrix q)
{
Matrix axis = new Matrix(3,1);
axis.Cross(y, x);
axis.Normalize();
double angle = Math.Acos(x.Dot(y));
double s = Math.Sin(angle/2.0);
q[0] = axis[0]*s;
q[1] = axis[1]*s;
q[2] = axis[2]*s;
q[3] = Math.Cos(angle/2.0);
}
public void RotFromTo2Quat(Matrix x, Matrix y) { RotFromTo2Quat(x, y, this); }
public static void RotQuat2Matrix(Matrix q, Matrix A)
{
double X = q[0];
double Y = q[1];
double Z = q[2];
double W = q[3];
// Watt and Watt p. 363
double s = 2.0/Math.Sqrt(X*X + Y*Y + Z*Z + W*W);
double xs = X*s; double ys = Y*s; double zs = Z*s;
double wx = W*xs; double wy = W*ys; double wz = W*zs;
double xx = X*xs; double xy = X*ys; double xz = X*zs;
double yy = Y*ys; double yz = Y*zs; double zz = Z*zs;
A[0,0] = 1 - (yy + zz);
A[0,1] = xy + wz;
A[0,2] = xz - wy;
A[1,0] = xy - wz;
A[1,1] = 1 - (xx + zz);
A[1,2] = yz + wx;
A[2,0] = xz + wy;
A[2,1] = yz - wx;
A[2,2] = 1 - (xx + yy);
}
public void RotQuat2Matrix(Matrix q) { RotQuat2Matrix(q, this); }
public static void RotAxisAngle2Quat(Matrix axis, double angle, Matrix q)
{
q[0] = axis[0] * Math.Sin(angle/2.0);
q[1] = axis[1] * Math.Sin(angle/2.0);
q[2] = axis[2] * Math.Sin(angle/2.0);
q[3] = Math.Cos(angle/2.0);
}
public void RotAxisAngle2Quat(Matrix axis, double angle) { RotAxisAngle2Quat(axis, angle, this); }
public static void RotMatrix2Quat(Matrix A, Matrix q)
{
// Watt and Watt p. 362
double trace = A[0,0] + A[1,1] + A[2,2] + 1.0;
q[3] = Math.Sqrt(trace);
q[0] = (A[2,1] - A[1,2])/(4*q[3]);
q[1] = (A[0,2] - A[2,0])/(4*q[3]);
q[2] = (A[1,0] - A[0,1])/(4*q[3]);
// not tested
}
public void RotMatrix2Quat(Matrix A) { RotMatrix2Quat(A, this); }
public void RotMatrix2Euler(ref double x, ref double y, ref double z)
{
RotMatrix2Euler(this, ref x, ref y, ref z);
}
public static void RotMatrix2Euler(Matrix A, ref double x, ref double y, ref double z)
{
y = -Math.Asin(A[2,0]);
double C = Math.Cos(y);
double cost3 = A[0,0] / C;
double sint3 = A[1,0] / C;
z = Math.Atan2(sint3, cost3);
double sint1 = A[2,1] / C;
double cost1 = A[2,2] / C;
x = Math.Atan2(sint1, cost1);
}
// quaternion ops; quat is ((X, Y, Z), W)
public static void QuatMult(Matrix a, Matrix b, Matrix c)
{
Matrix v1 = new Matrix(3,1);
Matrix v2 = new Matrix(3,1);
Matrix v3 = new Matrix(3,1);
v1[0] = a[0];
v1[1] = a[1];
v1[2] = a[2];
double s1 = a[3];
v2[0] = b[0];
v2[1] = b[1];
v2[2] = b[2];
double s2 = b[3];
v3.Cross(v1, v2);
c[0] = s1*v2[0] + s2*v1[0] + v3[0];
c[1] = s1*v2[1] + s2*v1[1] + v3[1];
c[2] = s1*v2[2] + s2*v1[2] + v3[2];
c[3] = s1*s2 - v1.Dot(v2);
}
public void QuatMult(Matrix a, Matrix b) { QuatMult(a, b, this); }
public static void QuatInvert(Matrix a, Matrix b)
{
b[0] = -a[0];
b[1] = -a[1];
b[2] = -a[2];
b[3] = a[3]; // w
}
public void QuatInvert(Matrix a) { QuatInvert(a, this); }
public void QuatInvert() { QuatInvert(this, this); }
public static void QuatRot(Matrix q, Matrix x, Matrix y)
{
// p. 361 Watt and Watt
Matrix p = new Matrix(4,1);
p[0] = x[0];
p[1] = x[1];
p[2] = x[2];
p[3] = 0.0;
Matrix q1 = new Matrix(4,1);
Matrix q2 = new Matrix(4,1);
Matrix qi = new Matrix(4,1);
qi.QuatInvert(q);
q1.QuatMult(q, p);
q2.QuatMult(q1, qi);
y[0] = q2[0];
y[1] = q2[1];
y[2] = q2[2];
}
public void QuatRot(Matrix q, Matrix x) { QuatRot(q, x, this); }
// norms
public double Minimum(ref int argmin)
{
double min = data[0];
int mini = 0;
for (int i = 1; i < mn; i++)
if (data[i] < min)
{
min = data[i];
mini = i;
}
argmin = mini;
return min;
}
public double Maximum(ref int argmax)
{
double max = data[0];
int maxi = 0;
for (int i = 1; i < mn; i++)
if (data[i] > max)
{
max = data[i];
maxi = i;
}
argmax = maxi;
return max;
}
public double Norm()
{
double sum = 0;
for (int i = 0; i < mn; i++)
sum += data[i]*data[i];
return Math.Sqrt(sum);
}
public double Sum()
{
double sum = 0;
for (int i = 0; i < mn; i++)
sum += data[i];
return sum;
}
public double SumSquares()
{
double sum = 0;
for (int i = 0; i < mn; i++)
sum += data[i]*data[i];
return sum;
}
public double Product()
{
double product = 1.0;
for (int i = 0; i < mn; i++)
product *= data[i];
return product;
}
public static double L1distance(Matrix a, Matrix b)
{
double s = 0.0;
double d;
for (int i = 0; i < a.mn; i++)
{
d = a.data[i] - b.data[i];
s += Math.Abs(d);
}
return s;
}
public double L1distance(Matrix a) { return L1distance(a, this); }
public static double L2distance(Matrix a, Matrix b)
{
double s = 0.0;
double d;
for (int i = 0; i < a.mn; i++)
{
d = a.data[i] - b.data[i];
s += d*d;
}
return Math.Sqrt(s);
}
public double L2distance(Matrix a) { return L2distance(a, this); }
public static void Normalize(Matrix A, Matrix B)
{
B.Scale(A, 1.0/A.Norm());
}
public void Normalize(Matrix A) { Normalize(A, this); }
public void Normalize() { Normalize(this, this); }
public double Magnitude()
{
double sum = 0;
for (int i = 0; i < mn; i++)
{
sum += data[i] * data[i];
}
return sum;
}
public class SingularMatrixException : Exception { }
public class EigException : Exception {}
public void NormalizeRows()
{
double sum;
for (int i = 0; i < m; i++)
{
sum = 0;
for (int j = 0; j < n; j++)
{
sum += this[i,j];
}
for (int j = 0; j < n; j++)
{
this[i,j] = this[i,j] / sum;
}
}
}
public override string ToString()
{
string s = "";
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
s += this[i,j].ToString();
if (j < n-1)
s += ", \t";
}
s += " \r\n";
}
return s;
}
public static void Test()
{
Matrix A = new Matrix(2,2);
A[0,0] = 1.0; A[0,1] = 2.0;
A[1,0] = 3.0; A[1,1] = 4.0;
Console.WriteLine(A.ToString());
// test serialization
XmlSerializer serializer = new XmlSerializer(typeof(Matrix));
TextWriter writer = new StreamWriter("test.xml");
serializer.Serialize(writer, A);
writer.Close();
XmlSerializer deserializer = new XmlSerializer(typeof(Matrix));
TextReader reader = new StreamReader("test.xml");
Matrix A2 = (Matrix) deserializer.Deserialize(reader);
Console.WriteLine(A2);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Int64AnimationUsingKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used to animate a Int64 property value along a set
/// of key frames.
/// </summary>
[ContentProperty("KeyFrames")]
public class Int64AnimationUsingKeyFrames : Int64AnimationBase, IKeyFrameAnimation, IAddChild
{
#region Data
private Int64KeyFrameCollection _keyFrames;
private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
private bool _areKeyTimesValid;
#endregion
#region Constructors
/// <Summary>
/// Creates a new KeyFrameInt64Animation.
/// </Summary>
public Int64AnimationUsingKeyFrames()
: base()
{
_areKeyTimesValid = true;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this KeyFrameInt64Animation.
/// </summary>
/// <returns>The copy</returns>
public new Int64AnimationUsingKeyFrames Clone()
{
return (Int64AnimationUsingKeyFrames)base.Clone();
}
/// <summary>
/// Returns a version of this class with all its base property values
/// set to the current animated values and removes the animations.
/// </summary>
/// <returns>
/// Since this class isn't animated, this method will always just return
/// this instance of the class.
/// </returns>
public new Int64AnimationUsingKeyFrames CloneCurrentValue()
{
return (Int64AnimationUsingKeyFrames)base.CloneCurrentValue();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
canFreeze &= Freezable.Freeze(_keyFrames, isChecking);
if (canFreeze & !_areKeyTimesValid)
{
ResolveKeyTimes();
}
return canFreeze;
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>.
/// </summary>
protected override void OnChanged()
{
_areKeyTimesValid = false;
base.OnChanged();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new Int64AnimationUsingKeyFrames();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
Int64AnimationUsingKeyFrames sourceAnimation = (Int64AnimationUsingKeyFrames) sourceFreezable;
base.CloneCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
Int64AnimationUsingKeyFrames sourceAnimation = (Int64AnimationUsingKeyFrames) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
Int64AnimationUsingKeyFrames sourceAnimation = (Int64AnimationUsingKeyFrames) source;
base.GetAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
Int64AnimationUsingKeyFrames sourceAnimation = (Int64AnimationUsingKeyFrames) source;
base.GetCurrentValueAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Helper used by the four Freezable clone methods to copy the resolved key times and
/// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core
/// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here.
/// </summary>
/// <param name="sourceAnimation"></param>
/// <param name="isCurrentValueClone"></param>
private void CopyCommon(Int64AnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone)
{
_areKeyTimesValid = sourceAnimation._areKeyTimesValid;
if ( _areKeyTimesValid
&& sourceAnimation._sortedResolvedKeyFrames != null)
{
// _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply
_sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone();
}
if (sourceAnimation._keyFrames != null)
{
if (isCurrentValueClone)
{
_keyFrames = (Int64KeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue();
}
else
{
_keyFrames = (Int64KeyFrameCollection)sourceAnimation._keyFrames.Clone();
}
OnFreezablePropertyChanged(null, _keyFrames);
}
}
#endregion // Freezable
#region IAddChild interface
/// <summary>
/// Adds a child object to this KeyFrameAnimation.
/// </summary>
/// <param name="child">
/// The child object to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation only accepts a KeyFrame of the proper type as
/// a child.
/// </remarks>
void IAddChild.AddChild(object child)
{
WritePreamble();
if (child == null)
{
throw new ArgumentNullException("child");
}
AddChild(child);
WritePostscript();
}
/// <summary>
/// Implemented to allow KeyFrames to be direct children
/// of KeyFrameAnimations in markup.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddChild(object child)
{
Int64KeyFrame keyFrame = child as Int64KeyFrame;
if (keyFrame != null)
{
KeyFrames.Add(keyFrame);
}
else
{
throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child");
}
}
/// <summary>
/// Adds a text string as a child of this KeyFrameAnimation.
/// </summary>
/// <param name="childText">
/// The text to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation does not accept text as a child, so this method will
/// raise an InvalididOperationException unless a derived class has
/// overridden the behavior to add text.
/// </remarks>
/// <exception cref="ArgumentNullException">The childText parameter is
/// null.</exception>
void IAddChild.AddText(string childText)
{
if (childText == null)
{
throw new ArgumentNullException("childText");
}
AddText(childText);
}
/// <summary>
/// This method performs the core functionality of the AddText()
/// method on the IAddChild interface. For a KeyFrameAnimation this means
/// throwing and InvalidOperationException because it doesn't
/// support adding text.
/// </summary>
/// <remarks>
/// This method is the only core implementation. It does not call
/// WritePreamble() or WritePostscript(). It also doesn't throw an
/// ArgumentNullException if the childText parameter is null. These tasks
/// are performed by the interface implementation. Therefore, it's OK
/// for a derived class to override this method and call the base
/// class implementation only if they determine that it's the right
/// course of action. The derived class can rely on KeyFrameAnimation's
/// implementation of IAddChild.AddChild or implement their own
/// following the Freezable pattern since that would be a public
/// method.
/// </remarks>
/// <param name="childText">A string representing the child text that
/// should be added. If this is a KeyFrameAnimation an exception will be
/// thrown.</param>
/// <exception cref="InvalidOperationException">Timelines have no way
/// of adding text.</exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddText(string childText)
{
throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren));
}
#endregion
#region Int64AnimationBase
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected sealed override Int64 GetCurrentValueCore(
Int64 defaultOriginValue,
Int64 defaultDestinationValue,
AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (_keyFrames == null)
{
return defaultDestinationValue;
}
// We resolved our KeyTimes when we froze, but also got notified
// of the frozen state and therefore invalidated ourselves.
if (!_areKeyTimesValid)
{
ResolveKeyTimes();
}
if (_sortedResolvedKeyFrames == null)
{
return defaultDestinationValue;
}
TimeSpan currentTime = animationClock.CurrentTime.Value;
Int32 keyFrameCount = _sortedResolvedKeyFrames.Length;
Int32 maxKeyFrameIndex = keyFrameCount - 1;
Int64 currentIterationValue;
Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames.");
Int32 currentResolvedKeyFrameIndex = 0;
// Skip all the key frames with key times lower than the current time.
// currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex
// if we are past the last key frame.
while ( currentResolvedKeyFrameIndex < keyFrameCount
&& currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
// If there are multiple key frames at the same key time, be sure to go to the last one.
while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex
&& currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
if (currentResolvedKeyFrameIndex == keyFrameCount)
{
// Past the last key frame.
currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex);
}
else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
// Exactly on a key frame.
currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex);
}
else
{
// Between two key frames.
Double currentSegmentProgress = 0.0;
Int64 fromValue;
if (currentResolvedKeyFrameIndex == 0)
{
// The current key frame is the first key frame so we have
// some special rules for determining the fromValue and an
// optimized method of calculating the currentSegmentProgress.
// If we're additive we want the base value to be a zero value
// so that if there isn't a key frame at time 0.0, we'll use
// the zero value for the time 0.0 value and then add that
// later to the base value.
if (IsAdditive)
{
fromValue = AnimatedTypeHelpers.GetZeroValueInt64(defaultOriginValue);
}
else
{
fromValue = defaultOriginValue;
}
// Current segment time divided by the segment duration.
// Note: the reason this works is that we know that we're in
// the first segment, so we can assume:
//
// currentTime.TotalMilliseconds = current segment time
// _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration
currentSegmentProgress = currentTime.TotalMilliseconds
/ _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds;
}
else
{
Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1;
TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime;
fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex);
TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime;
TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime;
currentSegmentProgress = segmentCurrentTime.TotalMilliseconds
/ segmentDuration.TotalMilliseconds;
}
currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress);
}
// If we're cumulative, we need to multiply the final key frame
// value by the current repeat count and add this to the return
// value.
if (IsCumulative)
{
Double currentRepeat = (Double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
currentIterationValue = AnimatedTypeHelpers.AddInt64(
currentIterationValue,
AnimatedTypeHelpers.ScaleInt64(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat));
}
}
// If we're additive we need to add the base value to the return value.
if (IsAdditive)
{
return AnimatedTypeHelpers.AddInt64(defaultOriginValue, currentIterationValue);
}
return currentIterationValue;
}
/// <summary>
/// Provide a custom natural Duration when the Duration property is set to Automatic.
/// </summary>
/// <param name="clock">
/// The Clock whose natural duration is desired.
/// </param>
/// <returns>
/// If the last KeyFrame of this animation is a KeyTime, then this will
/// be used as the NaturalDuration; otherwise it will be one second.
/// </returns>
protected override sealed Duration GetNaturalDurationCore(Clock clock)
{
return new Duration(LargestTimeSpanKeyTime);
}
#endregion
#region IKeyFrameAnimation
/// <summary>
/// Returns the Int64KeyFrameCollection used by this KeyFrameInt64Animation.
/// </summary>
IList IKeyFrameAnimation.KeyFrames
{
get
{
return KeyFrames;
}
set
{
KeyFrames = (Int64KeyFrameCollection)value;
}
}
/// <summary>
/// Returns the Int64KeyFrameCollection used by this KeyFrameInt64Animation.
/// </summary>
public Int64KeyFrameCollection KeyFrames
{
get
{
ReadPreamble();
// The reason we don't just set _keyFrames to the empty collection
// in the first place is that null tells us that the user has not
// asked for the collection yet. The first time they ask for the
// collection and we're unfrozen, policy dictates that we give
// them a new unfrozen collection. All subsequent times they will
// get whatever collection is present, whether frozen or unfrozen.
if (_keyFrames == null)
{
if (this.IsFrozen)
{
_keyFrames = Int64KeyFrameCollection.Empty;
}
else
{
WritePreamble();
_keyFrames = new Int64KeyFrameCollection();
OnFreezablePropertyChanged(null, _keyFrames);
WritePostscript();
}
}
return _keyFrames;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
WritePreamble();
if (value != _keyFrames)
{
OnFreezablePropertyChanged(_keyFrames, value);
_keyFrames = value;
WritePostscript();
}
}
}
/// <summary>
/// Returns true if we should serialize the KeyFrames, property for this Animation.
/// </summary>
/// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeKeyFrames()
{
ReadPreamble();
return _keyFrames != null
&& _keyFrames.Count > 0;
}
#endregion
#region Public Properties
/// <summary>
/// If this property is set to true, this animation will add its value
/// to the base value or the value of the previous animation in the
/// composition chain. Another way of saying this is that the units
/// specified in the animation are relative to the base value rather
/// than absolute units.
/// </summary>
/// <remarks>
/// In the case where the first key frame's resolved key time is not
/// 0.0 there is slightly different behavior between KeyFrameInt64Animations
/// with IsAdditive set and without. Animations with the property set to false
/// will behave as if there is a key frame at time 0.0 with the value of the
/// base value. Animations with the property set to true will behave as if
/// there is a key frame at time 0.0 with a zero value appropriate to the type
/// of the animation. These behaviors provide the results most commonly expected
/// and can be overridden by simply adding a key frame at time 0.0 with the preferred value.
/// </remarks>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// If this property is set to true, the value of this animation will
/// accumulate over repeat cycles. For example, if this is a point
/// animation and your key frames describe something approximating and
/// arc, setting this property to true will result in an animation that
/// would appear to bounce the point across the screen.
/// </summary>
/// <remarks>
/// This property works along with the IsAdditive property. Setting
/// this value to true has no effect unless IsAdditive is also set
/// to true.
/// </remarks>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
#region Private Methods
private struct KeyTimeBlock
{
public int BeginIndex;
public int EndIndex;
}
private Int64 GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue");
return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value;
}
private Int64KeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame");
return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex];
}
/// <summary>
/// Returns the largest time span specified key time from all of the key frames.
/// If there are not time span key times a time span of one second is returned
/// to match the default natural duration of the From/To/By animations.
/// </summary>
private TimeSpan LargestTimeSpanKeyTime
{
get
{
bool hasTimeSpanKeyTime = false;
TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero;
if (_keyFrames != null)
{
Int32 keyFrameCount = _keyFrames.Count;
for (int index = 0; index < keyFrameCount; index++)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
if (keyTime.Type == KeyTimeType.TimeSpan)
{
hasTimeSpanKeyTime = true;
if (keyTime.TimeSpan > largestTimeSpanKeyTime)
{
largestTimeSpanKeyTime = keyTime.TimeSpan;
}
}
}
}
if (hasTimeSpanKeyTime)
{
return largestTimeSpanKeyTime;
}
else
{
return TimeSpan.FromSeconds(1.0);
}
}
}
private void ResolveKeyTimes()
{
Debug.Assert(!_areKeyTimesValid, "KeyFrameInt64Animaton.ResolveKeyTimes() shouldn't be called if the key times are already valid.");
int keyFrameCount = 0;
if (_keyFrames != null)
{
keyFrameCount = _keyFrames.Count;
}
if (keyFrameCount == 0)
{
_sortedResolvedKeyFrames = null;
_areKeyTimesValid = true;
return;
}
_sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount];
int index = 0;
// Initialize the _originalKeyFrameIndex.
for ( ; index < keyFrameCount; index++)
{
_sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index;
}
// calculationDuration represents the time span we will use to resolve
// percent key times. This is defined as the value in the following
// precedence order:
// 1. The animation's duration, but only if it is a time span, not auto or forever.
// 2. The largest time span specified key time of all the key frames.
// 3. 1 second, to match the From/To/By animations.
TimeSpan calculationDuration = TimeSpan.Zero;
Duration duration = Duration;
if (duration.HasTimeSpan)
{
calculationDuration = duration.TimeSpan;
}
else
{
calculationDuration = LargestTimeSpanKeyTime;
}
int maxKeyFrameIndex = keyFrameCount - 1;
ArrayList unspecifiedBlocks = new ArrayList();
bool hasPacedKeyTimes = false;
//
// Pass 1: Resolve Percent and Time key times.
//
index = 0;
while (index < keyFrameCount)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
switch (keyTime.Type)
{
case KeyTimeType.Percent:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds(
keyTime.Percent * calculationDuration.TotalMilliseconds);
index++;
break;
case KeyTimeType.TimeSpan:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan;
index++;
break;
case KeyTimeType.Paced:
case KeyTimeType.Uniform:
if (index == maxKeyFrameIndex)
{
// If the last key frame doesn't have a specific time
// associated with it its resolved key time will be
// set to the calculationDuration, which is the
// defined in the comments above where it is set.
// Reason: We only want extra time at the end of the
// key frames if the user specifically states that
// the last key frame ends before the animation ends.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration;
index++;
}
else if ( index == 0
&& keyTime.Type == KeyTimeType.Paced)
{
// Note: It's important that this block come after
// the previous if block because of rule precendence.
// If the first key frame in a multi-frame key frame
// collection is paced, we set its resolved key time
// to 0.0 for performance reasons. If we didn't, the
// resolved key time list would be dependent on the
// base value which can change every animation frame
// in many cases.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero;
index++;
}
else
{
if (keyTime.Type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
KeyTimeBlock block = new KeyTimeBlock();
block.BeginIndex = index;
// NOTE: We don't want to go all the way up to the
// last frame because if it is Uniform or Paced its
// resolved key time will be set to the calculation
// duration using the logic above.
//
// This is why the logic is:
// ((++index) < maxKeyFrameIndex)
// instead of:
// ((++index) < keyFrameCount)
while ((++index) < maxKeyFrameIndex)
{
KeyTimeType type = _keyFrames[index].KeyTime.Type;
if ( type == KeyTimeType.Percent
|| type == KeyTimeType.TimeSpan)
{
break;
}
else if (type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
}
Debug.Assert(index < keyFrameCount,
"The end index for a block of unspecified key frames is out of bounds.");
block.EndIndex = index;
unspecifiedBlocks.Add(block);
}
break;
}
}
//
// Pass 2: Resolve Uniform key times.
//
for (int j = 0; j < unspecifiedBlocks.Count; j++)
{
KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j];
TimeSpan blockBeginTime = TimeSpan.Zero;
if (block.BeginIndex > 0)
{
blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime;
}
// The number of segments is equal to the number of key
// frames we're working on plus 1. Think about the case
// where we're working on a single key frame. There's a
// segment before it and a segment after it.
//
// Time known Uniform Time known
// ^ ^ ^
// | | |
// | (segment 1) | (segment 2) |
Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1;
TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount);
index = block.BeginIndex;
TimeSpan resolvedTime = blockBeginTime + uniformTimeStep;
while (index < block.EndIndex)
{
_sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime;
resolvedTime += uniformTimeStep;
index++;
}
}
//
// Pass 3: Resolve Paced key times.
//
if (hasPacedKeyTimes)
{
ResolvePacedKeyTimes();
}
//
// Sort resolved key frame entries.
//
Array.Sort(_sortedResolvedKeyFrames);
_areKeyTimesValid = true;
return;
}
/// <summary>
/// This should only be called from ResolveKeyTimes and only at the
/// appropriate time.
/// </summary>
private void ResolvePacedKeyTimes()
{
Debug.Assert(_keyFrames != null && _keyFrames.Count > 2,
"Caller must guard against calling this method when there are insufficient keyframes.");
// If the first key frame is paced its key time has already
// been resolved, so we start at index 1.
int index = 1;
int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1;
do
{
if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced)
{
//
// We've found a paced key frame so this is the
// beginning of a paced block.
//
// The first paced key frame in this block.
int firstPacedBlockKeyFrameIndex = index;
// List of segment lengths for this paced block.
List<Double> segmentLengths = new List<Double>();
// The resolved key time for the key frame before this
// block which we'll use as our starting point.
TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime;
// The total of the segment lengths of the paced key
// frames in this block.
Double totalLength = 0.0;
// The key value of the previous key frame which will be
// used to determine the segment length of this key frame.
Int64 prevKeyValue = _keyFrames[index - 1].Value;
do
{
Int64 currentKeyValue = _keyFrames[index].Value;
// Determine the segment length for this key frame and
// add to the total length.
totalLength += AnimatedTypeHelpers.GetSegmentLengthInt64(prevKeyValue, currentKeyValue);
// Temporarily store the distance into the total length
// that this key frame represents in the resolved
// key times array to be converted to a resolved key
// time outside of this loop.
segmentLengths.Add(totalLength);
// Prepare for the next iteration.
prevKeyValue = currentKeyValue;
index++;
}
while ( index < maxKeyFrameIndex
&& _keyFrames[index].KeyTime.Type == KeyTimeType.Paced);
// index is currently set to the index of the key frame
// after the last paced key frame. This will always
// be a valid index because we limit ourselves with
// maxKeyFrameIndex.
// We need to add the distance between the last paced key
// frame and the next key frame to get the total distance
// inside the key frame block.
totalLength += AnimatedTypeHelpers.GetSegmentLengthInt64(prevKeyValue, _keyFrames[index].Value);
// Calculate the time available in the resolved key time space.
TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime;
// Convert lengths in segmentLengths list to resolved
// key times for the paced key frames in this block.
for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++)
{
// The resolved key time for each key frame is:
//
// The key time of the key frame before this paced block
// + ((the percentage of the way through the total length)
// * the resolved key time space available for the block)
_sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds(
(segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds);
}
}
else
{
index++;
}
}
while (index < maxKeyFrameIndex);
}
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Billing.Budgets.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedBudgetServiceClientTest
{
[xunit::FactAttribute]
public void CreateBudgetRequestObject()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
CreateBudgetRequest request = new CreateBudgetRequest
{
ParentAsBillingAccountName = gagr::BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
Budget = new Budget(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.CreateBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.CreateBudget(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateBudgetRequestObjectAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
CreateBudgetRequest request = new CreateBudgetRequest
{
ParentAsBillingAccountName = gagr::BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
Budget = new Budget(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.CreateBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.CreateBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.CreateBudgetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateBudget()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
CreateBudgetRequest request = new CreateBudgetRequest
{
ParentAsBillingAccountName = gagr::BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
Budget = new Budget(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.CreateBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.CreateBudget(request.Parent, request.Budget);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateBudgetAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
CreateBudgetRequest request = new CreateBudgetRequest
{
ParentAsBillingAccountName = gagr::BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
Budget = new Budget(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.CreateBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.CreateBudgetAsync(request.Parent, request.Budget, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.CreateBudgetAsync(request.Parent, request.Budget, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateBudgetResourceNames()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
CreateBudgetRequest request = new CreateBudgetRequest
{
ParentAsBillingAccountName = gagr::BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
Budget = new Budget(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.CreateBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.CreateBudget(request.ParentAsBillingAccountName, request.Budget);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateBudgetResourceNamesAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
CreateBudgetRequest request = new CreateBudgetRequest
{
ParentAsBillingAccountName = gagr::BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
Budget = new Budget(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.CreateBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.CreateBudgetAsync(request.ParentAsBillingAccountName, request.Budget, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.CreateBudgetAsync(request.ParentAsBillingAccountName, request.Budget, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateBudgetRequestObject()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
UpdateBudgetRequest request = new UpdateBudgetRequest
{
Budget = new Budget(),
UpdateMask = new wkt::FieldMask(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.UpdateBudget(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateBudgetRequestObjectAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
UpdateBudgetRequest request = new UpdateBudgetRequest
{
Budget = new Budget(),
UpdateMask = new wkt::FieldMask(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.UpdateBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.UpdateBudgetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateBudget()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
UpdateBudgetRequest request = new UpdateBudgetRequest
{
Budget = new Budget(),
UpdateMask = new wkt::FieldMask(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.UpdateBudget(request.Budget, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateBudgetAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
UpdateBudgetRequest request = new UpdateBudgetRequest
{
Budget = new Budget(),
UpdateMask = new wkt::FieldMask(),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.UpdateBudgetAsync(request.Budget, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.UpdateBudgetAsync(request.Budget, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetBudgetRequestObject()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
GetBudgetRequest request = new GetBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.GetBudget(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetBudgetRequestObjectAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
GetBudgetRequest request = new GetBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.GetBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.GetBudgetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetBudget()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
GetBudgetRequest request = new GetBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.GetBudget(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetBudgetAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
GetBudgetRequest request = new GetBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.GetBudgetAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.GetBudgetAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetBudgetResourceNames()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
GetBudgetRequest request = new GetBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget response = client.GetBudget(request.BudgetName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetBudgetResourceNamesAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
GetBudgetRequest request = new GetBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
Budget expectedResponse = new Budget
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
DisplayName = "display_name137f65c2",
BudgetFilter = new Filter(),
Amount = new BudgetAmount(),
ThresholdRules =
{
new ThresholdRule(),
},
NotificationsRule = new NotificationsRule(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Budget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
Budget responseCallSettings = await client.GetBudgetAsync(request.BudgetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Budget responseCancellationToken = await client.GetBudgetAsync(request.BudgetName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteBudgetRequestObject()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
DeleteBudgetRequest request = new DeleteBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteBudget(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteBudgetRequestObjectAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
DeleteBudgetRequest request = new DeleteBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteBudgetAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteBudget()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
DeleteBudgetRequest request = new DeleteBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteBudget(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteBudgetAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
DeleteBudgetRequest request = new DeleteBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteBudgetAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteBudgetAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteBudgetResourceNames()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
DeleteBudgetRequest request = new DeleteBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteBudget(request.BudgetName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteBudgetResourceNamesAsync()
{
moq::Mock<BudgetService.BudgetServiceClient> mockGrpcClient = new moq::Mock<BudgetService.BudgetServiceClient>(moq::MockBehavior.Strict);
DeleteBudgetRequest request = new DeleteBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BudgetServiceClient client = new BudgetServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteBudgetAsync(request.BudgetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteBudgetAsync(request.BudgetName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
// ReSharper disable once CheckNamespace
namespace Sandbox4.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator _simpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return _simpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
var genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
var collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
var closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
var dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
var closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
var genericArgs = type.GetGenericArguments();
var parameterValues = new object[genericArgs.Length];
var failedToCreateTuple = true;
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
var result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
var genericArgs = keyValuePairType.GetGenericArguments();
var typeK = genericArgs[0];
var typeV = genericArgs[1];
var objectGenerator = new ObjectGenerator();
var keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
var valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
var result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
var type = arrayType.GetElementType();
var result = Array.CreateInstance(type, size);
var areAllElementsNull = true;
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < size; i++)
{
var element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
var typeK = typeof(object);
var typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
var genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
var result = Activator.CreateInstance(dictionaryType);
var addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
var containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < size; i++)
{
var newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
var containsKey = (bool)containsMethod.Invoke(result, new[] { newKey });
if (!containsKey)
{
var newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
var possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
var isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
var listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
var argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
var asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return ((IEnumerable)list).AsQueryable();
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
var type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
var result = Activator.CreateInstance(collectionType);
var addMethod = collectionType.GetMethod("Add");
var areAllElementsNull = true;
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < size; i++)
{
var element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
var type = nullableType.GetGenericArguments()[0];
var objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
var defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var objectGenerator = new ObjectGenerator();
foreach (var property in properties)
{
if (property.CanWrite)
{
var propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
var objectGenerator = new ObjectGenerator();
foreach (var field in fields)
{
var fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => index + 0.1 },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index => String.Format(CultureInfo.CurrentCulture, "sample string {0}", index)
},
{
typeof(TimeSpan), index => TimeSpan.FromTicks(1234567)
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index => new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index))
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using DotSpatial.Data;
using DotSpatial.Symbology;
namespace DotSpatial.Controls
{
/// <summary>
/// This is a specialized layer that specifically handles image drawing.
/// </summary>
public class MapImageLayer : ImageLayer, IMapImageLayer
{
#region Fields
private Color _transparent;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MapImageLayer"/> class.
/// </summary>
public MapImageLayer()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MapImageLayer"/> class.
/// </summary>
/// <param name="baseImage">The image to draw as a layer</param>
public MapImageLayer(IImageData baseImage)
: base(baseImage)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MapImageLayer"/> class.
/// </summary>
/// <param name="baseImage">The image to draw as a layer</param>
/// <param name="container">The Layers collection that keeps track of the image layer</param>
public MapImageLayer(IImageData baseImage, ICollection<ILayer> container)
: base(baseImage, container)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MapImageLayer"/> class.
/// </summary>
/// <param name="baseImage">The image to draw as a layer</param>
/// <param name="transparent">The color to make transparent when drawing the image.</param>
public MapImageLayer(IImageData baseImage, Color transparent)
: base(baseImage)
{
_transparent = transparent;
}
#endregion
#region Events
/// <summary>
/// Fires an event that indicates to the parent map-frame that it should first
/// redraw the specified clip.
/// </summary>
public event EventHandler<ClipArgs> BufferChanged;
#endregion
#region Properties
/// <summary>
/// Gets or sets the back buffer that will be drawn to as part of the initialization process.
/// </summary>
public Image BackBuffer { get; set; }
/// <summary>
/// Gets or sets the current buffer.
/// </summary>
public Image Buffer { get; set; }
/// <summary>
/// Gets or sets the geographic region represented by the buffer
/// Calling Initialize will set this automatically.
/// </summary>
public Extent BufferExtent { get; set; }
/// <summary>
/// Gets or sets the rectangle in pixels to use as the back buffer.
/// Calling Initialize will set this automatically.
/// </summary>
public Rectangle BufferRectangle { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the image layer is initialized.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new bool IsInitialized { get; set; }
#endregion
#region Methods
/// <summary>
/// This will draw any features that intersect this region. To specify the features directly, use OnDrawFeatures.
/// This will not clear existing buffer content. For that call Initialize instead.
/// </summary>
/// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param>
/// <param name="regions">The geographic regions to draw</param>
/// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features. Because images can't be selected they won't be drawn if selected is true.</param>
public void DrawRegions(MapArgs args, List<Extent> regions, bool selected)
{
if (selected) return;
List<Rectangle> clipRects = args.ProjToPixel(regions);
for (int i = clipRects.Count - 1; i >= 0; i--)
{
if (clipRects[i].Width != 0 && clipRects[i].Height != 0) continue;
regions.RemoveAt(i);
clipRects.RemoveAt(i);
}
DrawWindows(args, regions, clipRects);
}
/// <summary>
/// Fires the OnBufferChanged event.
/// </summary>
/// <param name="clipRectangles">The Rectangle in pixels</param>
protected virtual void OnBufferChanged(List<Rectangle> clipRectangles)
{
BufferChanged?.Invoke(this, new ClipArgs(clipRectangles));
}
/// <summary>
/// This updates the things that depend on the DataSet so that they fit to the changed DataSet.
/// </summary>
/// <param name="value">DataSet that was changed.</param>
protected override void OnDataSetChanged(IImageData value)
{
base.OnDataSetChanged(value);
BufferRectangle = value == null ? Rectangle.Empty : new Rectangle(0, 0, value.Width, value.Height);
BufferExtent = value?.Bounds.Extent;
MyExtent = value?.Extent;
OnFinishedLoading();
}
/// <summary>
/// This draws to the back buffer. If the Backbuffer doesn't exist, this will create one.
/// This will not flip the back buffer to the front.
/// </summary>
/// <param name="args">The map args.</param>
/// <param name="regions">The regions.</param>
/// <param name="clipRectangles">The clip rectangles.</param>
private void DrawWindows(MapArgs args, IList<Extent> regions, IList<Rectangle> clipRectangles)
{
Graphics g;
if (args.Device != null)
{
g = args.Device; // A device on the MapArgs is optional, but overrides the normal buffering behaviors.
}
else
{
if (BackBuffer == null) BackBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height);
g = Graphics.FromImage(BackBuffer);
}
int numBounds = Math.Min(regions.Count, clipRectangles.Count);
for (int i = 0; i < numBounds; i++)
{
// For panning tiles, the region needs to be expanded.
// This is not always 1 pixel. When very zoomed in, this could be many pixels,
// but should correspond to 1 pixel in the source image.
int dx = (int)Math.Ceiling(DataSet.Bounds.AffineCoefficients[1] * clipRectangles[i].Width / regions[i].Width);
int dy = (int)Math.Ceiling(-DataSet.Bounds.AffineCoefficients[5] * clipRectangles[i].Height / regions[i].Height);
Rectangle r = clipRectangles[i].ExpandBy(dx * 2, dy * 2);
if (r.X < 0) r.X = 0;
if (r.Y < 0) r.Y = 0;
if (r.Width > 2 * clipRectangles[i].Width) r.Width = 2 * clipRectangles[i].Width;
if (r.Height > 2 * clipRectangles[i].Height) r.Height = 2 * clipRectangles[i].Height;
Extent env = regions[i].Reproportion(clipRectangles[i], r);
Bitmap bmp = null;
try
{
bmp = DataSet.GetBitmap(env, r);
if (!_transparent.Name.Equals("0"))
{
bmp.MakeTransparent(_transparent);
}
}
catch
{
bmp?.Dispose();
continue;
}
if (bmp == null) continue;
if (Symbolizer != null && Symbolizer.Opacity < 1)
{
ColorMatrix matrix = new ColorMatrix
{
Matrix33 = Symbolizer.Opacity // draws the image not completely opaque
};
using (var attributes = new ImageAttributes())
{
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(bmp, r, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, attributes);
}
}
else
{
g.DrawImage(bmp, r);
}
bmp.Dispose();
}
if (args.Device == null) g.Dispose();
}
#endregion
}
}
| |
// Reddit.Client.cs
// ------------------------------------------------------------------
//
// Part of CleanModQueue .
//
// Defines a class containing methods to facilitate interactions and
// communications to reddit, including Login, get mod queue, get user
// status, and so on.
//
// For some limited documentation of the reddit API see
// http://www.reddit.com/dev/api/ and
// https://github.com/reddit/reddit/wiki/API . (old)
//
// last saved: <2012-July-31 06:33:42>
// ------------------------------------------------------------------
//
// Copyright (c) 2012 Dino Chiesa
// All rights reserved.
//
// This code is Licensed under the New BSD license.
// See the License.txt file that accompanies this module.
//
// ------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net; // CookieCollection, CookieContainer
using System.Linq;
namespace Dino.Reddit
{
internal static class Util
{
/// <summary>
/// Memoize a function.
/// </summary>
/// <remarks>
/// <para>
/// This is used as a general way to cache results of
/// network communications to reddit.
/// </para>
/// </remarks>
public static Func<A, R> Memoize<A, R>(Func<A, R> f)
{
var mem = new Dictionary<A, R>();
// A function that wraps the originally-passed function.
// This wrapper checks the cache before invoking the
// wrapped function.
Func<A, R> wrapper = (a) =>
{
R value;
if (mem.TryGetValue(a, out value))
return value;
value = f(a);
mem.Add(a, value);
return value;
};
return wrapper;
}
}
/// <summary>
/// Exposes methods for connecting to Reddit and doing various things.
/// </summary>
public class Client
{
private static readonly String redditLoginAddr = "https://ssl.reddit.com/api/login";
private static readonly String redditBaseAddr = "http://www.reddit.com";
System.DateTime lastRequest = new System.DateTime(0);
Dictionary<String, bool> checkedUserCache;
TimeSpan requiredDelta;
TimeSpan fifteenDays;
string userHash;
string modHash;
Func<String, Reddit.Data.Account> mGetAccount;
Func<String, Reddit.Data.Listing> mGetUserRecentPosts;
Func<String, Reddit.Data.UserList> mGetModsForSub;
List<String> reportedUsers;
HttpClient client;
HttpClientHandler handler;
/// <summary>
/// Constructor for the Reddit Client. Uses the specified
/// request delay (in milliseconds).
/// </summary>
/// <remarks>
/// <para>
/// For example a delay of 800
/// specifies that this class will delay so that it makes no more
/// than 1 request for every 800 milliseconds. Reddit says that
/// clients should make no more than 1 request every 2 seconds, but
/// allows for short bursts as long as there are fewer than 30
/// requests per minute, over the long term.
/// </para>
/// </remarks>
///
public Client(int requestDelayInMs)
{
requiredDelta = new System.TimeSpan(0, 0, 0, 0, requestDelayInMs);
fifteenDays = new System.TimeSpan(15, 0, 0, 0);
mGetModsForSub = Util.Memoize<String,Data.UserList>(GetModsForSub);
mGetAccount = Util.Memoize<String,Data.Account>(uncachedGetAccount);
mGetUserRecentPosts = Util.Memoize<String,Data.Listing>(GetUserRecentPosts);
reportedUsers = new List<String>();
checkedUserCache = new Dictionary<String, bool>();
// avoid the "too many delimiter characters"
//System.Net.Http.Formatting.MediaTypeFormatter.SkipStreamLimitChecks = true;
handler = new HttpClientHandler
{
UseCookies = true,
CookieContainer = Dino.Http.CookieManager.GetCookieContainerForUrl(redditBaseAddr)
};
client = new HttpClient(handler);
client.DefaultRequestHeaders.UserAgent.Clear();
client.DefaultRequestHeaders.Add("User-Agent", "AyeMateyCleanModQueue");
// client.DefaultRequestHeaders.UserAgent.Add
// ( new ProductInfoHeaderValue("CleanModQueue by /u/AyeMatey", "1.0") );
}
/// <summary>
/// Default constructor for the Reddit Client. Uses a request delay of
/// 2 seconds.
/// </summary>
public Client() : this(2001) { }
/// <summary>
/// Enforce the rate throttle.
/// </summary>
/// <remarks>
/// <para>
/// For internal use only. Reddit says client applications
/// should send at most one request every 2 seconds.
/// </para>
/// </remarks>
private void EnforceDelay()
{
int miniRestPeriod = 125;
var delta = System.DateTime.Now - lastRequest;
while (delta < requiredDelta)
{
System.Threading.Thread.Sleep(miniRestPeriod);
System.Windows.Forms.Application.DoEvents();
delta = System.DateTime.Now - lastRequest;
}
}
public List<String> ExternalDeadList { get; set; }
/// <summary>
/// Returns the full link to the post or the comment.
/// </summary>
/// <remarks>
/// <para>
/// OneItemData is a class that holds metadata about one post, or
/// one comment.
/// </para>
/// <para>
/// This method returns the link for either the post or the
/// comment referenced in the object. This works whether
/// post refers to a comment or a post.
/// </para>
/// </remarks>
/// <seealso cref='GetItemUrl'/>
/// <seealso cref='GetCommentUrl'/>
public static string GetItemUrl(Reddit.Data.OneItemData post)
{
return (String.IsNullOrEmpty(post.permalink))
? Dino.Reddit.Client.GetCommentUrl(post)
: Dino.Reddit.Client.GetPermalink(post);
}
public static string GetItemUrl(string id, string postid, string subreddit)
{
if (subreddit==null) return null;
if (id==null) return null;
//if (postid==null) return null;
if (id.StartsWith("t1_") && postid!=null)
return string.Format("{0}/r/{1}/comments/{2}/x/{3}",
redditBaseAddr, subreddit,
Lop3(postid),
Lop3(id));
if (id.StartsWith("t3_"))
return string.Format("{0}/r/{1}/comments/{2}",
redditBaseAddr, subreddit, Lop3(id));
return null;
}
public static string GetAuthorUrl(Reddit.Data.OneItemData post)
{
return GetAuthorUrl(post.author);
}
public static string GetAuthorUrl(String authorName)
{
return (String.IsNullOrEmpty(authorName))
? null
: redditBaseAddr + "/user/" + authorName;
}
private static string Lop3(string s)
{
return s.Substring(3,s.Length-3);
}
/// <summary>
/// Get the URL link for a particular comment on a post.
/// </summary>
/// <seealso cref='GetItemUrl'/>
/// <seealso cref='GetPermalink'/>
public static string GetCommentUrl(Reddit.Data.OneItemData post)
{
// eg, /r/news/comments/t8298/Man_bites_dog/c4keg94
//
// The middle segment can be anything, but must be present.
// The first id is for the link/post, the second is for the
// comment.
return string.Format("{0}/r/{1}/comments/{2}/x/{3}",
redditBaseAddr, post.subreddit,
Lop3(post.link_id),
Lop3(post.name));
}
/// <summary>
/// Get the full permalink for a post.
/// </summary>
/// <seealso cref='GetItemUrl'/>
/// <seealso cref='GetCommentUrl'/>
public static string GetPermalink(Reddit.Data.OneItemData post)
{
return System.Net.WebUtility.HtmlDecode(redditBaseAddr + post.permalink);
}
/// <summary>
/// Replace newlines and carriage-returns from titles with
/// a vertical bar. This cleans the title for display.
/// </summary>
public static string CleanTitle(Reddit.Data.OneItemData post)
{
var title = post.title;
if (title == null) return "--no title--";
string t = title.Replace('\r', '|').Replace('\n', '|');
return t;
}
private static string MsgForPost(Reddit.Data.OneItemData post)
{
return (post == null || post.title == null)
? "..comment from " + post.author + ".."
: CleanTitle(post);
}
/// <summary>
/// This event fires before and after network communications
/// to reddit. This is intended to aid in user applications
/// that want to update their UI with status information.
/// </summary>
public event EventHandler<ProgressArgs> Progress;
private void FireProgress(Stage stage, Activity activity, string msg=null)
{
// Copy to a temporary variable to be thread-safe.
EventHandler<ProgressArgs> h = Progress;
if (h != null)
{
h(this, new ProgressArgs(stage, activity, msg));
}
}
private string DoPostAction(string addr, string postData)
{
var msg = new StringContent(postData,
System.Text.Encoding.UTF8,
"application/x-www-form-urlencoded");
//handler.AllowAutoRedirect = followRedirects;
var task = client.PostAsync(addr, msg);
task.Wait();
var submitResult = task.Result.Content.ReadAsStringAsync().Result;
lastRequest = System.DateTime.Now;
return submitResult;
}
/// <summary>
/// Remove a post.
/// </summary>
/// <remarks>
/// <para>
/// Like clicking the "remove" button on the modqueue page.
/// </para>
/// </remarks>
public string RemovePost(Data.OneItemData post, bool notSpam = false)
{
var m = MsgForPost(post);
FireProgress(Stage.Before, Activity.RemoveItem, m);
EnforceDelay();
string addr = redditBaseAddr + "/api/remove.json";
string postData = String.Format("id={0}&uh={1}&r={2}",
post.name,
modHash,
post.subreddit);
if (notSpam)
postData += "&spam=false";
var r = DoPostAction(addr, postData);
FireProgress(Stage.After, Activity.RemoveItem, m);
post.handled = true;
return r;
}
/// <summary>
/// Approve a post.
/// </summary>
/// <remarks>
/// <para>
/// Like clicking the "approve" button on the modqueue page.
/// </para>
/// </remarks>
public string ApprovePost(Data.OneItemData post)
{
var m = MsgForPost(post);
FireProgress(Stage.Before, Activity.ApproveItem, m);
// this.lblStatus.Text = "approving " + post.title;
// this.Update();
EnforceDelay();
string addr = redditBaseAddr + "/api/approve.json";
string postData = String.Format("id={0}&uh={1}&r={2}",
post.name,
modHash,
post.subreddit);
var r = DoPostAction(addr, postData);
FireProgress(Stage.After, Activity.ApproveItem, m);
post.handled = true;
return r;
}
private T GetRedditThing<T>(string addr)
{
// Cookies are sent implicitly for this request,
// via the HttpHandler.
EnforceDelay();
var task = client.GetAsync(addr);
T result;
try
{
task.Wait();
HttpResponseMessage resp = task.Result;
// Wed, 02 May 2012 10:50
//
// The problem with using ReadAsAsync<T> with reddit responses
// is that the JSON is a different schema, but uses the same
// prop name. This is sort of bogus, but ... there it
// is. Ideally there would be a way to do data-dependent
// de-serialization: look at the value of one property to
// determine how to de-serialize the content for another
// property. I haven't figure that out yet. p
var t2 = resp.Content.ReadAsAsync<T>();
t2.Wait();
result = t2.Result;
lastRequest = System.DateTime.Now;
}
catch
{
result = default(T);
}
return result;
}
/// <summary>
/// Report a user as a spammer, maybe.
/// </summary>
/// <remarks>
/// <para>
/// This method submits a user to /r/reportthespammers, maybe.
/// </para>
/// <para>
/// The method first queries the user. If the user is
/// already shadow-banned, this method does nothing further,
/// and returns.
/// </para>
/// <para>
/// If the user has an age of over 15 days, and has posted more than 3 items,
// and has a link karma below 20, then the account gets
// reported as a spammer.
/// </para>
/// </remarks>
public void MaybeReportUserAsSpammer(string username)
{
if (GetDeadUsers().Contains(username)) return;
Data.Listing list = mGetUserRecentPosts(username);
if (list==null || list.error != null) return;
Data.Account acct = mGetAccount(username);
if (acct==null || acct.data == null) return;
// report as spammer if....
// .... account is older than 15 days
// .... has link karma less than 20
// .... has posted more than 3 items
// .... has not been reported already
var age = DateTime.Now - acct.data.createdTime;
if (age > fifteenDays &&
//!acct.data.is_mod &&
acct.data.link_karma < 20 &&
list.data.children.Count(x => x.kind.Equals("t3")) > 3 &&
!reportedUsers.Contains(username) &&
(!checkedUserCache.ContainsKey(username) ||
!checkedUserCache[username] ))
{
ReportUserAsSpammer(username);
reportedUsers.Add(username);
if (ExternalDeadList != null)
{
if (!ExternalDeadList.Contains(username))
ExternalDeadList.Add(username);
}
checkedUserCache[username] = true; // dead
}
}
private string ReportUserAsSpammer(string username)
{
FireProgress(Stage.Before, Activity.ReportSpammer, username);
if (String.IsNullOrEmpty(username)) return null;
username = username.Trim();
// format of the ID: either FrostyNJ
// or http://www.reddit.com/user/FrostyNJ
string id = username.Replace("http://www.reddit.com/user/", "");
string addr = redditBaseAddr + "/api/submit";
// To delete a user:
// uh=f0f0f0f0&kind=link&url=yourlink.com&sr=funny&title=omg-look-at-this&id%23newlink&r=funny&renderstyle=html
// uh = user modhash
// kind = "link" or "self"
// sr = the subreddit (reportthespammers)
// title = can be anything
// url = link tp post
// r = the subreddit, again
string url = string.Format("{0}/user/{1}", redditBaseAddr, id);
string postData = string.Format("uh={0}&kind=link&url={1}&sr={2}&title={3}&r={2}",
userHash, url, "reportthespammers", id);
var r = DoPostAction(addr, postData);
FireProgress(Stage.After, Activity.ReportSpammer, username);
return r;
}
/// <summary>
/// Get the contents of the aggregate Mod Queue for the logged-in user.
/// </summary>
/// <remarks>
/// <para>
/// This method does not get the mod queue for a particular
/// reddit, but for a particular user, specifically the logged-in
/// user. The aggregate mod queue is different for each moderator,
/// depending on the various reddits he moderates.
/// </para>
/// </remarks>
/// <seealso cref='GetModQueue'/>
public Reddit.Data.Listing GetUserModQueue()
{
FireProgress(Stage.Before, Activity.GetModQueue, null);
string addr = redditBaseAddr + "/r/mod/about/modqueue.json";
var r = GetRedditThing<Reddit.Data.Listing>(addr);
FireProgress(Stage.After, Activity.GetModQueue, "");
if (r != null && r.data!=null)
modHash = r.data.modhash;
return r;
}
/// <summary>
/// Get the contents of the Mod Queue for a particular reddit.
/// </summary>
/// <seealso cref='GetUserModQueue'/>
/// <seealso cref='GetNewQueue'/>
public Reddit.Data.Listing GetModQueue(string subreddit)
{
// eg, http://www.reddit.com/r/news/about/modqueue/
var r = GetQueue(Activity.GetModQueue,"{0}/r/{1}/about/modqueue.json",
subreddit);
if (r != null && r.data!=null)
modHash = r.data.modhash;
return r;
}
/// <summary>
/// Get the contents of the New Queue for a particular reddit.
/// </summary>
/// <seealso cref='GetModQueue'/>
public Reddit.Data.Listing GetNewQueue(string subreddit)
{
// eg, http://www.reddit.com/r/redditdev/new.json
var r = GetQueue(Activity.GetNewQueue, "{0}/r/{1}/new.json", subreddit);
return r;
}
private Reddit.Data.Listing GetQueue(Activity activity,
string format,
string subreddit)
{
FireProgress(Stage.Before, activity, subreddit);
string addr = String.Format(format, redditBaseAddr, subreddit);
var r = GetRedditThing<Reddit.Data.Listing>(addr);
FireProgress(Stage.After, activity, subreddit);
return r;
}
/// <summary>
/// Gets the list of dead users.
/// </summary>
/// <remarks>
/// <para>
/// This is the number of users determined to be "dead" or
/// shadow-banned. The module determines this by going to the
/// user's page (/user/AyeMatey) and if a 404 results, then
/// it marks the user as dead.
/// </para>
/// <para>
/// This is exposed to allow client applications to store
/// the list of presumed dead users in a persistent
/// store. This allows an app to cache the list. See <see
/// cref='MarkUsersDead'/> for a companion method, which
/// would allow an application to apply the contents of a
/// cache to an instance of Reddit.Client.
/// </para>
/// </remarks>
public System.Collections.ObjectModel.ReadOnlyCollection<String> GetDeadUsers()
{
return checkedUserCache.Keys
.Where(x => checkedUserCache[x]) // true = dead
//.Select(x=>x)
.ToList()
.AsReadOnly();
}
/// <summary>
/// Tells the Reddit.Client instance which users to treat as "Dead"
/// or known spammers.
/// </summary>
public void MarkUsersDead(IEnumerable<string> deadToMe)
{
foreach (var x in deadToMe)
{
if (!checkedUserCache.ContainsKey(x))
checkedUserCache.Add(x, true); // dead
}
}
/// <summary>
/// Tells the Reddit.Client to drop a set of users from its list of
/// known spammers.
/// </summary>
/// <remarks>
/// <para>
/// An app may wish to re-habilitate a user, or remove it from
/// the list of known spammers. It can call this method to do so.
/// </para>
/// <para>
/// Reddit.Client may yet determine the user is dead by
/// visiting his /user/Foo page, and getting a 404. If that
/// happens, Reddit.Client places that user back on the
/// "known spammers" list.
/// </para>
/// </remarks>
public void MarkUsersUndead(IEnumerable<string> undead)
{
foreach (var x in undead)
{
if (checkedUserCache.ContainsKey(x))
checkedUserCache.Remove(x);
}
}
/// <summary>
/// Explicitly test to see if a user is shadow-banned,
/// which means the user is a known spammer.
/// </summary>
/// <remarks>
/// <para>
/// This is done by HTTP GET on /user/Foo . If that link returns a
/// 404, then the user is shadow-banned.
/// </para>
/// </remarks>
public bool IsUserDead(string username)
{
if (!checkedUserCache.ContainsKey(username))
{
Data.Listing list = mGetUserRecentPosts(username);
checkedUserCache[username] = (list != null && list.error != null);
}
return checkedUserCache[username];
}
/// <summary>
/// Is the given user a mod for the given subreddit?
/// </summary>
/// <remarks>
/// <para>
/// This may perform an HTTP GET to inquire the
/// list of mods for the subreddit. That result is cached
/// for future use.
/// </para>
/// </remarks>
public bool IsUserMod(string username, string subreddit)
{
Data.UserList mods = mGetModsForSub(subreddit);
if (mods == null || mods.data == null || mods.data.children == null)
return false;
return mods.data.children.Any(x => username.Equals(x.name));
}
/// <summary>
/// Gets the list of recent posts for a user.
/// </summary>
public Data.Listing GetUserRecentPosts(string username)
{
// To determine if the user is "shadow-banned", retrieve
// his recent posts, with this:
// http://www.reddit.com/user/Foo.json
//
// If you get an error 404, then he is shadow-banned.
//
// Could also get
// http://www.reddit.com/user/Foo/submitted.json
//
// The former includes comments submitted; the latter
// gets only posts.
//
FireProgress(Stage.Before, Activity.GetPostHistory, username);
string addr = String.Format("{0}/user/{1}.json",
redditBaseAddr, username);
var r = GetRedditThing<Data.Listing>(addr);
FireProgress(Stage.After, Activity.GetPostHistory, username);
return r;
}
/// <summary>
/// Gets the list of mods for a subreddit.
/// </summary>
/// <remarks>
/// <para>
/// This method does not use a cache. Calling it will always
/// result in an HTTP GET.
/// </para>
/// </remarks>
public Data.UserList GetModsForSub(string subreddit)
{
FireProgress(Stage.Before, Activity.GetMods, subreddit);
string addr = String.Format("{0}/r/{1}/about/moderators.json",
redditBaseAddr, subreddit);
var r = GetRedditThing<Data.UserList>(addr);
FireProgress(Stage.After, Activity.GetMods, subreddit);
return r;
}
public Data.Listing GetSubsIMod()
{
// http://www.reddit.com/dev/api#GET_reddits_mine_moderator
FireProgress(Stage.Before, Activity.GetSubs);
string addr = String.Format("{0}/reddits/mine/moderator.json",
redditBaseAddr);
var r = GetRedditThing<Data.Listing>(addr);
FireProgress(Stage.After, Activity.GetSubs);
return r;
}
/// <summary>
/// Gets information about a reddit user or account - including
/// account creation date, link karma, comment karma, and etc.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method will result in an HTTP GET to retrieve the
/// information.
/// </para>
/// </remarks>
private Data.Account uncachedGetAccount(string username)
{
// To get information about the user:
// http://www.reddit.com/user/Foo/about.json
FireProgress(Stage.Before, Activity.AboutUser, username);
string addr = String.Format("{0}/user/{1}/about.json",
redditBaseAddr, username);
var r = GetRedditThing<Data.Account>(addr);
FireProgress(Stage.After, Activity.AboutUser, username);
return r;
}
public Data.Account GetAccount(string username)
{
Data.Account acct = mGetAccount(username);
return acct;
}
/// <summary>
/// Is the instance logged in?
/// </summary>
/// <seealso cref='Login'/>
public bool LoggedIn
{
get
{
return (userHash!=null);
}
}
/// <summary>
/// Logout from reddit.
/// </summary>
/// <seealso cref='Login'/>
public string Logout()
{
FireProgress(Stage.Before, Activity.Logout, null);
string addr = redditBaseAddr + "/logout";
string postData = string.Format("uh={0}", userHash);
var r = DoPostAction(addr, postData);
userHash = null;
FireProgress(Stage.After, Activity.Logout, null);
return r;
}
/// <summary>
/// Authenticate to reddit.
/// </summary>
/// <seealso cref='LoggedIn'/>
public bool Login(string user, string pwd)
{
FireProgress(Stage.Before, Activity.Login, null);
string postData = string.Format("api_type=json&user={0}&passwd={1}",
user, pwd);
var msg = new StringContent(postData,
System.Text.Encoding.UTF8,
"application/x-www-form-urlencoded");
Dino.Reddit.Data.LoginResponse result = null;
try
{
var task = client.PostAsync(redditLoginAddr, msg);
task.Wait();
var t2 = task.Result.Content.ReadAsAsync<Dino.Reddit.Data.LoginResponse>();
t2.Wait();
result = t2.Result;
if (result != null && result.json != null && result.json.errors.Length == 0)
userHash = result.json.data.modhash;
else
userHash = null;
}
catch
{
userHash = null;
}
FireProgress(Stage.After, Activity.Login, userHash);
return (userHash != null);
}
public enum Activity
{
Login,
Logout,
RemoveItem,
ApproveItem,
AboutUser,
GetPostHistory,
GetMods,
GetSubs,
GetModQueue,
GetNewQueue,
ReportSpammer
}
public enum Stage
{
Before,
After
}
public class ProgressArgs : EventArgs
{
public ProgressArgs(Stage stage, Activity activity, string message)
{
@Stage = stage;
@Activity = activity;
Message = message;
}
public string Message { get; set;}
public Activity @Activity { get; set;}
public Stage @Stage { get; set;}
}
}
}
| |
// Radial Menu|Prefabs|0040
namespace VRTK
{
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public delegate void HapticPulseEventHandler(float strength);
/// <summary>
/// This adds a UI element into the world space that can be dropped into a Controller object and used to create and use Radial Menus from the touchpad.
/// </summary>
/// <remarks>
/// If the RadialMenu is placed inside a controller, it will automatically find a `VRTK_ControllerEvents` in its parent to use at the input. However, a `VRTK_ControllerEvents` can be defined explicitly by setting the `Events` parameter of the `Radial Menu Controller` script also attached to the prefab.
///
/// The RadialMenu can also be placed inside a `VRTK_InteractableObject` for the RadialMenu to be anchored to a world object instead of the controller. The `Events Manager` parameter will automatically be set if the RadialMenu is a child of an InteractableObject, but it can also be set manually in the inspector. Additionally, for the RadialMenu to be anchored in the world, the `RadialMenuController` script in the prefab must be replaced with `VRTK_IndependentRadialMenuController`. See the script information for further details on making the RadialMenu independent of the controllers.
/// </remarks>
/// <example>
/// `VRTK/Examples/030_Controls_RadialTouchpadMenu` displays a radial menu for each controller. The left controller uses the `Hide On Release` variable, so it will only be visible if the left touchpad is being touched. It also uses the `Execute On Unclick` variable to delay execution until the touchpad button is unclicked. The example scene also contains a demonstration of anchoring the RadialMenu to an interactable cube instead of a controller.
/// </example>
[ExecuteInEditMode]
public class RadialMenu : MonoBehaviour
{
#region Variables
[Tooltip("An array of Buttons that define the interactive buttons required to be displayed as part of the radial menu.")]
public List<RadialMenuButton> buttons;
[Tooltip("The base for each button in the menu, by default set to a dynamic circle arc that will fill up a portion of the menu.")]
public GameObject buttonPrefab;
[Tooltip("If checked, then the buttons will be auto generated on awake.")]
public bool generateOnAwake = true;
[Tooltip("Percentage of the menu the buttons should fill, 1.0 is a pie slice, 0.1 is a thin ring.")]
[Range(0f, 1f)]
public float buttonThickness = 0.5f;
[Tooltip("The background colour of the buttons, default is white.")]
public Color buttonColor = Color.white;
[Tooltip("The distance the buttons should move away from the centre. This creates space between the individual buttons.")]
public float offsetDistance = 1;
[Tooltip("The additional rotation of the Radial Menu.")]
[Range(0, 359)]
public float offsetRotation;
[Tooltip("Whether button icons should rotate according to their arc or be vertical compared to the controller.")]
public bool rotateIcons;
[Tooltip("The margin in pixels that the icon should keep within the button.")]
public float iconMargin;
[Tooltip("Whether the buttons are shown")]
public bool isShown;
[Tooltip("Whether the buttons should be visible when not in use.")]
public bool hideOnRelease;
[Tooltip("Whether the button action should happen when the button is released, as opposed to happening immediately when the button is pressed.")]
public bool executeOnUnclick;
[Tooltip("The base strength of the haptic pulses when the selected button is changed, or a button is pressed. Set to zero to disable.")]
[Range(0, 1)]
public float baseHapticStrength;
public event HapticPulseEventHandler FireHapticPulse;
//Has to be public to keep state from editor -> play mode?
[Tooltip("The actual GameObjects that make up the radial menu.")]
public List<GameObject> menuButtons;
private int currentHover = -1;
private int currentPress = -1;
#endregion
#region Unity Methods
private void Awake()
{
if (Application.isPlaying)
{
if (!isShown)
{
transform.localScale = Vector3.zero;
}
if (generateOnAwake)
{
RegenerateButtons();
}
}
}
private void Update()
{
//Keep track of pressed button and constantly invoke Hold event
if (currentPress != -1)
{
buttons[currentPress].OnHold.Invoke();
}
}
#endregion
#region Interaction
//Turns and Angle and Event type into a button action
private void InteractButton(float angle, ButtonEvent evt) //Can't pass ExecuteEvents as parameter? Unity gives error
{
//Get button ID from angle
float buttonAngle = 360f / buttons.Count; //Each button is an arc with this angle
angle = mod((angle + -offsetRotation), 360); //Offset the touch coordinate with our offset
int buttonID = (int)mod(((angle + (buttonAngle / 2f)) / buttonAngle), buttons.Count); //Convert angle into ButtonID (This is the magic)
var pointer = new PointerEventData(EventSystem.current); //Create a new EventSystem (UI) Event
//If we changed buttons while moving, un-hover and un-click the last button we were on
if (currentHover != buttonID && currentHover != -1)
{
ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerUpHandler);
ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler);
buttons[currentHover].OnHoverExit.Invoke();
if (executeOnUnclick && currentPress != -1)
{
ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler);
AttempHapticPulse(baseHapticStrength * 1.666f);
}
}
if (evt == ButtonEvent.click) //Click button if click, and keep track of current press (executes button action)
{
ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler);
currentPress = buttonID;
if (!executeOnUnclick)
{
buttons[buttonID].OnClick.Invoke();
AttempHapticPulse(baseHapticStrength * 2.5f);
}
}
else if (evt == ButtonEvent.unclick) //Clear press id to stop invoking OnHold method (hide menu)
{
ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerUpHandler);
currentPress = -1;
if (executeOnUnclick)
{
AttempHapticPulse(baseHapticStrength * 2.5f);
buttons[buttonID].OnClick.Invoke();
}
}
else if (evt == ButtonEvent.hoverOn && currentHover != buttonID) // Show hover UI event (darken button etc). Show menu
{
ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerEnterHandler);
buttons[buttonID].OnHoverEnter.Invoke();
AttempHapticPulse(baseHapticStrength);
}
currentHover = buttonID; //Set current hover ID, need this to un-hover if selected button changes
}
/*
* Public methods to call Interact
*/
public void HoverButton(float angle)
{
InteractButton(angle, ButtonEvent.hoverOn);
}
public void ClickButton(float angle)
{
InteractButton(angle, ButtonEvent.click);
}
public void UnClickButton(float angle)
{
InteractButton(angle, ButtonEvent.unclick);
}
public void ToggleMenu()
{
if (isShown)
{
HideMenu(true);
}
else
{
ShowMenu();
}
}
public void StopTouching()
{
if (currentHover != -1)
{
var pointer = new PointerEventData(EventSystem.current);
ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler);
buttons[currentHover].OnHoverExit.Invoke();
currentHover = -1;
}
}
/*
* Public methods to Show/Hide menu
*/
public void ShowMenu()
{
if (!isShown)
{
isShown = true;
StopCoroutine("TweenMenuScale");
StartCoroutine("TweenMenuScale", isShown);
}
}
public RadialMenuButton GetButton(int id)
{
if (id < buttons.Count)
{
return buttons[id];
}
return null;
}
public void HideMenu(bool force)
{
if (isShown && (hideOnRelease || force))
{
isShown = false;
StopCoroutine("TweenMenuScale");
StartCoroutine("TweenMenuScale", isShown);
}
}
//Simple tweening for menu, scales linearly from 0 to 1 and 1 to 0
private IEnumerator TweenMenuScale(bool show)
{
float targetScale = 0;
Vector3 Dir = -1 * Vector3.one;
if (show)
{
targetScale = 1;
Dir = Vector3.one;
}
int i = 0; //Sanity check for infinite loops
while (i < 250 && ((show && transform.localScale.x < targetScale) || (!show && transform.localScale.x > targetScale)))
{
transform.localScale += Dir * Time.deltaTime * 4f; //Tweening function - currently 0.25 second linear
yield return true;
i++;
}
transform.localScale = Dir * targetScale;
StopCoroutine("TweenMenuScale");
}
private void AttempHapticPulse(float strength)
{
if (strength > 0 && FireHapticPulse != null)
{
FireHapticPulse(strength);
}
}
#endregion
#region Generation
//Creates all the button Arcs and populates them with desired icons
public void RegenerateButtons()
{
RemoveAllButtons();
for (int i = 0; i < buttons.Count; i++)
{
// Initial placement/instantiation
GameObject newButton = Instantiate(buttonPrefab);
newButton.transform.SetParent(transform);
newButton.transform.localScale = Vector3.one;
newButton.GetComponent<RectTransform>().offsetMax = Vector2.zero;
newButton.GetComponent<RectTransform>().offsetMin = Vector2.zero;
//Setup button arc
UICircle circle = newButton.GetComponent<UICircle>();
if (buttonThickness == 1)
{
circle.fill = true;
}
else
{
circle.thickness = (int)(buttonThickness * (GetComponent<RectTransform>().rect.width / 2f));
}
int fillPerc = (int)(100f / buttons.Count);
circle.fillPercent = fillPerc;
circle.color = buttonColor;
//Final placement/rotation
float angle = ((360 / buttons.Count) * i) + offsetRotation;
newButton.transform.localEulerAngles = new Vector3(0, 0, angle);
newButton.layer = 4; //UI Layer
newButton.transform.localPosition = Vector3.zero;
if (circle.fillPercent < 55)
{
float angleRad = (angle * Mathf.PI) / 180f;
Vector2 angleVector = new Vector2(-Mathf.Cos(angleRad), -Mathf.Sin(angleRad));
newButton.transform.localPosition += (Vector3)angleVector * offsetDistance;
}
//Place and populate Button Icon
GameObject buttonIcon = newButton.GetComponentInChildren<RadialButtonIcon>().gameObject;
if (buttons[i].ButtonIcon == null)
{
buttonIcon.SetActive(false);
}
else
{
buttonIcon.GetComponent<Image>().sprite = buttons[i].ButtonIcon;
buttonIcon.transform.localPosition = new Vector2(-1 * ((newButton.GetComponent<RectTransform>().rect.width / 2f) - (circle.thickness / 2f)), 0);
//Min icon size from thickness and arc
float scale1 = Mathf.Abs(circle.thickness);
float R = Mathf.Abs(buttonIcon.transform.localPosition.x);
float bAngle = (359f * circle.fillPercent * 0.01f * Mathf.PI) / 180f;
float scale2 = (R * 2 * Mathf.Sin(bAngle / 2f));
if (circle.fillPercent > 24) //Scale calc doesn't work for > 90 degrees
{
scale2 = float.MaxValue;
}
float iconScale = Mathf.Min(scale1, scale2) - iconMargin;
buttonIcon.GetComponent<RectTransform>().sizeDelta = new Vector2(iconScale, iconScale);
//Rotate icons all vertically if desired
if (!rotateIcons)
{
buttonIcon.transform.eulerAngles = GetComponentInParent<Canvas>().transform.eulerAngles;
}
}
menuButtons.Add(newButton);
}
}
public void AddButton(RadialMenuButton newButton)
{
buttons.Add(newButton);
RegenerateButtons();
}
private void RemoveAllButtons()
{
if (menuButtons == null)
{
menuButtons = new List<GameObject>();
}
for (int i = 0; i < menuButtons.Count; i++)
{
DestroyImmediate(menuButtons[i]);
}
menuButtons = new List<GameObject>();
}
#endregion
#region Utility
private float mod(float a, float b)
{
return a - b * Mathf.Floor(a / b);
}
#endregion
}
[System.Serializable]
public class RadialMenuButton
{
public Sprite ButtonIcon;
public UnityEvent OnClick;
public UnityEvent OnHold;
public UnityEvent OnHoverEnter;
public UnityEvent OnHoverExit;
}
public enum ButtonEvent
{
hoverOn,
hoverOff,
click,
unclick
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// ItemPricing
/// </summary>
[DataContract]
public partial class ItemPricing : IEquatable<ItemPricing>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ItemPricing" /> class.
/// </summary>
/// <param name="allowArbitraryCost">Allow arbitrary cost.</param>
/// <param name="arbitraryCostVelocityCode">Arbitrary cost velocity code.</param>
/// <param name="autoOrderCost">Cost if customer selects to receive item on auto order. Set to zero to delete..</param>
/// <param name="automaticPricingTierName">Automatic pricing tier name.</param>
/// <param name="automaticPricingTierOid">Automatic pricing tier object identifier.</param>
/// <param name="cogs">Cost of goods sold.</param>
/// <param name="cost">Cost.</param>
/// <param name="currencyCode">Currency code.</param>
/// <param name="manufacturerSuggestedRetailPrice">Manufacturer suggested retail price.</param>
/// <param name="maximumArbitraryCost">Maximum arbitrary cost.</param>
/// <param name="minimumAdvertisedPrice">Minimum advertised price.</param>
/// <param name="minimumArbitraryCost">Minimum arbitrary cost.</param>
/// <param name="mixAndMatchGroup">Mix and match group.</param>
/// <param name="mixAndMatchGroupOid">Mix and match group object identifier.</param>
/// <param name="saleCost">Sale cost.</param>
/// <param name="saleEnd">Sale end.</param>
/// <param name="saleStart">Sale start.</param>
/// <param name="tiers">Tiers.</param>
public ItemPricing(bool? allowArbitraryCost = default(bool?), string arbitraryCostVelocityCode = default(string), decimal? autoOrderCost = default(decimal?), string automaticPricingTierName = default(string), int? automaticPricingTierOid = default(int?), decimal? cogs = default(decimal?), decimal? cost = default(decimal?), string currencyCode = default(string), decimal? manufacturerSuggestedRetailPrice = default(decimal?), decimal? maximumArbitraryCost = default(decimal?), decimal? minimumAdvertisedPrice = default(decimal?), decimal? minimumArbitraryCost = default(decimal?), string mixAndMatchGroup = default(string), int? mixAndMatchGroupOid = default(int?), decimal? saleCost = default(decimal?), string saleEnd = default(string), string saleStart = default(string), List<ItemPricingTier> tiers = default(List<ItemPricingTier>))
{
this.AllowArbitraryCost = allowArbitraryCost;
this.ArbitraryCostVelocityCode = arbitraryCostVelocityCode;
this.AutoOrderCost = autoOrderCost;
this.AutomaticPricingTierName = automaticPricingTierName;
this.AutomaticPricingTierOid = automaticPricingTierOid;
this.Cogs = cogs;
this.Cost = cost;
this.CurrencyCode = currencyCode;
this.ManufacturerSuggestedRetailPrice = manufacturerSuggestedRetailPrice;
this.MaximumArbitraryCost = maximumArbitraryCost;
this.MinimumAdvertisedPrice = minimumAdvertisedPrice;
this.MinimumArbitraryCost = minimumArbitraryCost;
this.MixAndMatchGroup = mixAndMatchGroup;
this.MixAndMatchGroupOid = mixAndMatchGroupOid;
this.SaleCost = saleCost;
this.SaleEnd = saleEnd;
this.SaleStart = saleStart;
this.Tiers = tiers;
}
/// <summary>
/// Allow arbitrary cost
/// </summary>
/// <value>Allow arbitrary cost</value>
[DataMember(Name="allow_arbitrary_cost", EmitDefaultValue=false)]
public bool? AllowArbitraryCost { get; set; }
/// <summary>
/// Arbitrary cost velocity code
/// </summary>
/// <value>Arbitrary cost velocity code</value>
[DataMember(Name="arbitrary_cost_velocity_code", EmitDefaultValue=false)]
public string ArbitraryCostVelocityCode { get; set; }
/// <summary>
/// Cost if customer selects to receive item on auto order. Set to zero to delete.
/// </summary>
/// <value>Cost if customer selects to receive item on auto order. Set to zero to delete.</value>
[DataMember(Name="auto_order_cost", EmitDefaultValue=false)]
public decimal? AutoOrderCost { get; set; }
/// <summary>
/// Automatic pricing tier name
/// </summary>
/// <value>Automatic pricing tier name</value>
[DataMember(Name="automatic_pricing_tier_name", EmitDefaultValue=false)]
public string AutomaticPricingTierName { get; set; }
/// <summary>
/// Automatic pricing tier object identifier
/// </summary>
/// <value>Automatic pricing tier object identifier</value>
[DataMember(Name="automatic_pricing_tier_oid", EmitDefaultValue=false)]
public int? AutomaticPricingTierOid { get; set; }
/// <summary>
/// Cost of goods sold
/// </summary>
/// <value>Cost of goods sold</value>
[DataMember(Name="cogs", EmitDefaultValue=false)]
public decimal? Cogs { get; set; }
/// <summary>
/// Cost
/// </summary>
/// <value>Cost</value>
[DataMember(Name="cost", EmitDefaultValue=false)]
public decimal? Cost { get; set; }
/// <summary>
/// Currency code
/// </summary>
/// <value>Currency code</value>
[DataMember(Name="currency_code", EmitDefaultValue=false)]
public string CurrencyCode { get; set; }
/// <summary>
/// Manufacturer suggested retail price
/// </summary>
/// <value>Manufacturer suggested retail price</value>
[DataMember(Name="manufacturer_suggested_retail_price", EmitDefaultValue=false)]
public decimal? ManufacturerSuggestedRetailPrice { get; set; }
/// <summary>
/// Maximum arbitrary cost
/// </summary>
/// <value>Maximum arbitrary cost</value>
[DataMember(Name="maximum_arbitrary_cost", EmitDefaultValue=false)]
public decimal? MaximumArbitraryCost { get; set; }
/// <summary>
/// Minimum advertised price
/// </summary>
/// <value>Minimum advertised price</value>
[DataMember(Name="minimum_advertised_price", EmitDefaultValue=false)]
public decimal? MinimumAdvertisedPrice { get; set; }
/// <summary>
/// Minimum arbitrary cost
/// </summary>
/// <value>Minimum arbitrary cost</value>
[DataMember(Name="minimum_arbitrary_cost", EmitDefaultValue=false)]
public decimal? MinimumArbitraryCost { get; set; }
/// <summary>
/// Mix and match group
/// </summary>
/// <value>Mix and match group</value>
[DataMember(Name="mix_and_match_group", EmitDefaultValue=false)]
public string MixAndMatchGroup { get; set; }
/// <summary>
/// Mix and match group object identifier
/// </summary>
/// <value>Mix and match group object identifier</value>
[DataMember(Name="mix_and_match_group_oid", EmitDefaultValue=false)]
public int? MixAndMatchGroupOid { get; set; }
/// <summary>
/// Sale cost
/// </summary>
/// <value>Sale cost</value>
[DataMember(Name="sale_cost", EmitDefaultValue=false)]
public decimal? SaleCost { get; set; }
/// <summary>
/// Sale end
/// </summary>
/// <value>Sale end</value>
[DataMember(Name="sale_end", EmitDefaultValue=false)]
public string SaleEnd { get; set; }
/// <summary>
/// Sale start
/// </summary>
/// <value>Sale start</value>
[DataMember(Name="sale_start", EmitDefaultValue=false)]
public string SaleStart { get; set; }
/// <summary>
/// Tiers
/// </summary>
/// <value>Tiers</value>
[DataMember(Name="tiers", EmitDefaultValue=false)]
public List<ItemPricingTier> Tiers { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ItemPricing {\n");
sb.Append(" AllowArbitraryCost: ").Append(AllowArbitraryCost).Append("\n");
sb.Append(" ArbitraryCostVelocityCode: ").Append(ArbitraryCostVelocityCode).Append("\n");
sb.Append(" AutoOrderCost: ").Append(AutoOrderCost).Append("\n");
sb.Append(" AutomaticPricingTierName: ").Append(AutomaticPricingTierName).Append("\n");
sb.Append(" AutomaticPricingTierOid: ").Append(AutomaticPricingTierOid).Append("\n");
sb.Append(" Cogs: ").Append(Cogs).Append("\n");
sb.Append(" Cost: ").Append(Cost).Append("\n");
sb.Append(" CurrencyCode: ").Append(CurrencyCode).Append("\n");
sb.Append(" ManufacturerSuggestedRetailPrice: ").Append(ManufacturerSuggestedRetailPrice).Append("\n");
sb.Append(" MaximumArbitraryCost: ").Append(MaximumArbitraryCost).Append("\n");
sb.Append(" MinimumAdvertisedPrice: ").Append(MinimumAdvertisedPrice).Append("\n");
sb.Append(" MinimumArbitraryCost: ").Append(MinimumArbitraryCost).Append("\n");
sb.Append(" MixAndMatchGroup: ").Append(MixAndMatchGroup).Append("\n");
sb.Append(" MixAndMatchGroupOid: ").Append(MixAndMatchGroupOid).Append("\n");
sb.Append(" SaleCost: ").Append(SaleCost).Append("\n");
sb.Append(" SaleEnd: ").Append(SaleEnd).Append("\n");
sb.Append(" SaleStart: ").Append(SaleStart).Append("\n");
sb.Append(" Tiers: ").Append(Tiers).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ItemPricing);
}
/// <summary>
/// Returns true if ItemPricing instances are equal
/// </summary>
/// <param name="input">Instance of ItemPricing to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ItemPricing input)
{
if (input == null)
return false;
return
(
this.AllowArbitraryCost == input.AllowArbitraryCost ||
(this.AllowArbitraryCost != null &&
this.AllowArbitraryCost.Equals(input.AllowArbitraryCost))
) &&
(
this.ArbitraryCostVelocityCode == input.ArbitraryCostVelocityCode ||
(this.ArbitraryCostVelocityCode != null &&
this.ArbitraryCostVelocityCode.Equals(input.ArbitraryCostVelocityCode))
) &&
(
this.AutoOrderCost == input.AutoOrderCost ||
(this.AutoOrderCost != null &&
this.AutoOrderCost.Equals(input.AutoOrderCost))
) &&
(
this.AutomaticPricingTierName == input.AutomaticPricingTierName ||
(this.AutomaticPricingTierName != null &&
this.AutomaticPricingTierName.Equals(input.AutomaticPricingTierName))
) &&
(
this.AutomaticPricingTierOid == input.AutomaticPricingTierOid ||
(this.AutomaticPricingTierOid != null &&
this.AutomaticPricingTierOid.Equals(input.AutomaticPricingTierOid))
) &&
(
this.Cogs == input.Cogs ||
(this.Cogs != null &&
this.Cogs.Equals(input.Cogs))
) &&
(
this.Cost == input.Cost ||
(this.Cost != null &&
this.Cost.Equals(input.Cost))
) &&
(
this.CurrencyCode == input.CurrencyCode ||
(this.CurrencyCode != null &&
this.CurrencyCode.Equals(input.CurrencyCode))
) &&
(
this.ManufacturerSuggestedRetailPrice == input.ManufacturerSuggestedRetailPrice ||
(this.ManufacturerSuggestedRetailPrice != null &&
this.ManufacturerSuggestedRetailPrice.Equals(input.ManufacturerSuggestedRetailPrice))
) &&
(
this.MaximumArbitraryCost == input.MaximumArbitraryCost ||
(this.MaximumArbitraryCost != null &&
this.MaximumArbitraryCost.Equals(input.MaximumArbitraryCost))
) &&
(
this.MinimumAdvertisedPrice == input.MinimumAdvertisedPrice ||
(this.MinimumAdvertisedPrice != null &&
this.MinimumAdvertisedPrice.Equals(input.MinimumAdvertisedPrice))
) &&
(
this.MinimumArbitraryCost == input.MinimumArbitraryCost ||
(this.MinimumArbitraryCost != null &&
this.MinimumArbitraryCost.Equals(input.MinimumArbitraryCost))
) &&
(
this.MixAndMatchGroup == input.MixAndMatchGroup ||
(this.MixAndMatchGroup != null &&
this.MixAndMatchGroup.Equals(input.MixAndMatchGroup))
) &&
(
this.MixAndMatchGroupOid == input.MixAndMatchGroupOid ||
(this.MixAndMatchGroupOid != null &&
this.MixAndMatchGroupOid.Equals(input.MixAndMatchGroupOid))
) &&
(
this.SaleCost == input.SaleCost ||
(this.SaleCost != null &&
this.SaleCost.Equals(input.SaleCost))
) &&
(
this.SaleEnd == input.SaleEnd ||
(this.SaleEnd != null &&
this.SaleEnd.Equals(input.SaleEnd))
) &&
(
this.SaleStart == input.SaleStart ||
(this.SaleStart != null &&
this.SaleStart.Equals(input.SaleStart))
) &&
(
this.Tiers == input.Tiers ||
this.Tiers != null &&
this.Tiers.SequenceEqual(input.Tiers)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AllowArbitraryCost != null)
hashCode = hashCode * 59 + this.AllowArbitraryCost.GetHashCode();
if (this.ArbitraryCostVelocityCode != null)
hashCode = hashCode * 59 + this.ArbitraryCostVelocityCode.GetHashCode();
if (this.AutoOrderCost != null)
hashCode = hashCode * 59 + this.AutoOrderCost.GetHashCode();
if (this.AutomaticPricingTierName != null)
hashCode = hashCode * 59 + this.AutomaticPricingTierName.GetHashCode();
if (this.AutomaticPricingTierOid != null)
hashCode = hashCode * 59 + this.AutomaticPricingTierOid.GetHashCode();
if (this.Cogs != null)
hashCode = hashCode * 59 + this.Cogs.GetHashCode();
if (this.Cost != null)
hashCode = hashCode * 59 + this.Cost.GetHashCode();
if (this.CurrencyCode != null)
hashCode = hashCode * 59 + this.CurrencyCode.GetHashCode();
if (this.ManufacturerSuggestedRetailPrice != null)
hashCode = hashCode * 59 + this.ManufacturerSuggestedRetailPrice.GetHashCode();
if (this.MaximumArbitraryCost != null)
hashCode = hashCode * 59 + this.MaximumArbitraryCost.GetHashCode();
if (this.MinimumAdvertisedPrice != null)
hashCode = hashCode * 59 + this.MinimumAdvertisedPrice.GetHashCode();
if (this.MinimumArbitraryCost != null)
hashCode = hashCode * 59 + this.MinimumArbitraryCost.GetHashCode();
if (this.MixAndMatchGroup != null)
hashCode = hashCode * 59 + this.MixAndMatchGroup.GetHashCode();
if (this.MixAndMatchGroupOid != null)
hashCode = hashCode * 59 + this.MixAndMatchGroupOid.GetHashCode();
if (this.SaleCost != null)
hashCode = hashCode * 59 + this.SaleCost.GetHashCode();
if (this.SaleEnd != null)
hashCode = hashCode * 59 + this.SaleEnd.GetHashCode();
if (this.SaleStart != null)
hashCode = hashCode * 59 + this.SaleStart.GetHashCode();
if (this.Tiers != null)
hashCode = hashCode * 59 + this.Tiers.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// ArbitraryCostVelocityCode (string) maxLength
if(this.ArbitraryCostVelocityCode != null && this.ArbitraryCostVelocityCode.Length > 10000)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ArbitraryCostVelocityCode, length must be less than 10000.", new [] { "ArbitraryCostVelocityCode" });
}
// CurrencyCode (string) maxLength
if(this.CurrencyCode != null && this.CurrencyCode.Length > 3)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CurrencyCode, length must be less than 3.", new [] { "CurrencyCode" });
}
yield break;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.HttpListenerResponse
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Globalization;
using System.IO;
using System.Text;
namespace System.Net
{
public sealed partial class HttpListenerResponse : IDisposable
{
private long _contentLength;
private Version _version = HttpVersion.Version11;
private int _statusCode = 200;
internal object _headersLock = new object();
private bool _forceCloseChunked;
internal HttpListenerResponse(HttpListenerContext context)
{
_httpContext = context;
}
internal bool ForceCloseChunked => _forceCloseChunked;
private void EnsureResponseStream()
{
if (_responseStream == null)
{
_responseStream = _httpContext.Connection.GetResponseStream();
}
}
public Version ProtocolVersion
{
get => _version;
set
{
CheckDisposed();
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
{
throw new ArgumentException(SR.net_wrongversion, nameof(value));
}
_version = new Version(value.Major, value.Minor); // match Windows behavior, trimming to just Major.Minor
}
}
public int StatusCode
{
get => _statusCode;
set
{
CheckDisposed();
if (value < 100 || value > 999)
throw new ProtocolViolationException(SR.net_invalidstatus);
_statusCode = value;
}
}
private void Dispose() => Close(true);
public void Close()
{
if (Disposed)
return;
Close(false);
}
public void Abort()
{
if (Disposed)
return;
Close(true);
}
private void Close(bool force)
{
Disposed = true;
_httpContext.Connection.Close(force);
}
public void Close(byte[] responseEntity, bool willBlock)
{
CheckDisposed();
if (responseEntity == null)
{
throw new ArgumentNullException(nameof(responseEntity));
}
if (!SentHeaders && _boundaryType != BoundaryType.Chunked)
{
ContentLength64 = responseEntity.Length;
}
if (willBlock)
{
try
{
OutputStream.Write(responseEntity, 0, responseEntity.Length);
}
finally
{
Close(false);
}
}
else
{
OutputStream.BeginWrite(responseEntity, 0, responseEntity.Length, iar =>
{
var thisRef = (HttpListenerResponse)iar.AsyncState;
try
{
thisRef.OutputStream.EndWrite(iar);
}
finally
{
thisRef.Close(false);
}
}, this);
}
}
public void CopyFrom(HttpListenerResponse templateResponse)
{
_webHeaders.Clear();
_webHeaders.Add(templateResponse._webHeaders);
_contentLength = templateResponse._contentLength;
_statusCode = templateResponse._statusCode;
_statusDescription = templateResponse._statusDescription;
_keepAlive = templateResponse._keepAlive;
_version = templateResponse._version;
}
internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandshake = false)
{
if (!isWebSocketHandshake)
{
if (_webHeaders[HttpKnownHeaderNames.Server] == null)
{
_webHeaders.Set(HttpKnownHeaderNames.Server, HttpHeaderStrings.NetCoreServerName);
}
if (_webHeaders[HttpKnownHeaderNames.Date] == null)
{
_webHeaders.Set(HttpKnownHeaderNames.Date, DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture));
}
if (_boundaryType == BoundaryType.None)
{
if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
{
_keepAlive = false;
}
else
{
_boundaryType = BoundaryType.Chunked;
}
if (CanSendResponseBody(_httpContext.Response.StatusCode))
{
_contentLength = -1;
}
else
{
_boundaryType = BoundaryType.ContentLength;
_contentLength = 0;
}
}
if (_boundaryType != BoundaryType.Chunked)
{
if (_boundaryType != BoundaryType.ContentLength && closing)
{
_contentLength = CanSendResponseBody(_httpContext.Response.StatusCode) ? -1 : 0;
}
if (_boundaryType == BoundaryType.ContentLength)
{
_webHeaders.Set(HttpKnownHeaderNames.ContentLength, _contentLength.ToString("D", CultureInfo.InvariantCulture));
}
}
/* Apache forces closing the connection for these status codes:
* HttpStatusCode.BadRequest 400
* HttpStatusCode.RequestTimeout 408
* HttpStatusCode.LengthRequired 411
* HttpStatusCode.RequestEntityTooLarge 413
* HttpStatusCode.RequestUriTooLong 414
* HttpStatusCode.InternalServerError 500
* HttpStatusCode.ServiceUnavailable 503
*/
bool conn_close = (_statusCode == (int)HttpStatusCode.BadRequest || _statusCode == (int)HttpStatusCode.RequestTimeout
|| _statusCode == (int)HttpStatusCode.LengthRequired || _statusCode == (int)HttpStatusCode.RequestEntityTooLarge
|| _statusCode == (int)HttpStatusCode.RequestUriTooLong || _statusCode == (int)HttpStatusCode.InternalServerError
|| _statusCode == (int)HttpStatusCode.ServiceUnavailable);
if (!conn_close)
{
conn_close = !_httpContext.Request.KeepAlive;
}
// They sent both KeepAlive: true and Connection: close
if (!_keepAlive || conn_close)
{
_webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.Close);
conn_close = true;
}
if (SendChunked)
{
_webHeaders.Set(HttpKnownHeaderNames.TransferEncoding, HttpHeaderStrings.Chunked);
}
int reuses = _httpContext.Connection.Reuses;
if (reuses >= 100)
{
_forceCloseChunked = true;
if (!conn_close)
{
_webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.Close);
conn_close = true;
}
}
if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
{
if (_keepAlive)
{
Headers[HttpResponseHeader.KeepAlive] = "true";
}
if (!conn_close)
{
_webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.KeepAlive);
}
}
ComputeCookies();
}
Encoding encoding = Encoding.Default;
StreamWriter writer = new StreamWriter(ms, encoding, 256);
writer.Write("HTTP/1.1 {0} ", _statusCode); // "1.1" matches Windows implementation, which ignores the response version
writer.Flush();
byte[] statusDescriptionBytes = WebHeaderEncoding.GetBytes(StatusDescription);
ms.Write(statusDescriptionBytes, 0, statusDescriptionBytes.Length);
writer.Write("\r\n");
writer.Write(FormatHeaders(_webHeaders));
writer.Flush();
int preamble = encoding.Preamble.Length;
EnsureResponseStream();
/* Assumes that the ms was at position 0 */
ms.Position = preamble;
SentHeaders = !isWebSocketHandshake;
}
private static bool HeaderCanHaveEmptyValue(string name) =>
!string.Equals(name, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase);
private static string FormatHeaders(WebHeaderCollection headers)
{
var sb = new StringBuilder();
for (int i = 0; i < headers.Count; i++)
{
string key = headers.GetKey(i);
string[] values = headers.GetValues(i);
int startingLength = sb.Length;
sb.Append(key).Append(": ");
bool anyValues = false;
for (int j = 0; j < values.Length; j++)
{
string value = values[j];
if (!string.IsNullOrWhiteSpace(value))
{
if (anyValues)
{
sb.Append(", ");
}
sb.Append(value);
anyValues = true;
}
}
if (anyValues || HeaderCanHaveEmptyValue(key))
{
// Complete the header
sb.Append("\r\n");
}
else
{
// Empty header; remove it.
sb.Length = startingLength;
}
}
return sb.Append("\r\n").ToString();
}
private bool Disposed { get; set; }
internal bool SentHeaders { get; set; }
}
}
| |
// MIT License
//
// Copyright (c) 2017 Maarten van Sambeek.
//
// 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 ConnectQl.Tools.Mef.Intellisense
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using AssemblyLoader;
using ConnectQl.Intellisense;
using ConnectQl.Interfaces;
using ConnectQl.Results;
using EnvDTE;
using EnvDTE80;
using JetBrains.Annotations;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using VSLangProj;
using Task = System.Threading.Tasks.Task;
/// <summary>
/// The intellisense proxy.
/// </summary>
internal class IntellisenseProxy : IIntellisenseSession
{
/// <summary>
/// The app domain.
/// </summary>
private AppDomain appDomain;
/// <summary>
/// The assembly paths.
/// </summary>
private string[] watchPaths;
/// <summary>
/// The handler.
/// </summary>
private RemoteEventHandler<byte[]> handler;
/// <summary>
/// The imports events.
/// </summary>
private ImportsEvents importsEvents;
/// <summary>
/// The session.
/// </summary>
private AppDomainIntellisenseSession intellisenseSession;
/// <summary>
/// The references events.
/// </summary>
private ReferencesEvents referencesEvents;
/// <summary>
/// The watchers.
/// </summary>
private List<FileSystemWatcher> watchers;
/// <summary>
/// Initializes a new instance of the <see cref="IntellisenseProxy"/> class.
/// </summary>
/// <param name="projectUniqueName">
/// The project unique name.
/// </param>
public IntellisenseProxy(string projectUniqueName)
{
this.Init(projectUniqueName);
}
/// <summary>
/// Occurs when a document is updated.
/// </summary>
public event EventHandler<DocumentUpdatedEventArgs> DocumentUpdated;
/// <summary>
/// The initialized.
/// </summary>
public event EventHandler Initialized;
/// <summary>
/// The reload requested.
/// </summary>
public event EventHandler ReloadRequested;
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (this.referencesEvents != null)
{
this.referencesEvents.ReferenceAdded -= this.ReferencesUpdated;
this.referencesEvents.ReferenceChanged -= this.ReferencesUpdated;
this.referencesEvents.ReferenceRemoved -= this.ReferencesUpdated;
this.referencesEvents = null;
}
if (this.importsEvents != null)
{
this.importsEvents.ImportAdded -= this.ImportsUpdated;
this.importsEvents.ImportRemoved -= this.ImportsUpdated;
this.importsEvents = null;
}
if (this.watchers != null)
{
foreach (var watcher in this.watchers)
{
watcher.Changed -= this.FileChanged;
watcher.Renamed -= this.FileChanged;
watcher.Deleted -= this.FileChanged;
watcher.Created -= this.FileChanged;
watcher.Dispose();
}
this.watchers.Clear();
this.watchers = null;
}
if (this.intellisenseSession != null)
{
if (this.handler != null)
{
this.intellisenseSession.DocumentUpdated -= this.handler.Handler;
this.handler = null;
}
this.intellisenseSession = null;
}
if (this.appDomain != null)
{
AppDomain.Unload(this.appDomain);
}
this.appDomain = null;
}
/// <summary>
/// Updates the document.
/// </summary>
/// <param name="filename">
/// The filename.
/// </param>
/// <param name="contents">
/// The contents.
/// </param>
/// <param name="documentVersion">
/// The version of the document.
/// </param>
public void UpdateDocument(string filename, string contents, int documentVersion)
{
this.intellisenseSession.UpdateDocument(filename, contents, documentVersion);
}
/// <summary>
/// Updates the document span.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="endIndex">The end index.</param>
/// <param name="newSpan">The new span text.</param>
/// <param name="documentVersion">The new document version number.</param>
public void UpdateDocumentSpan(string filename, int startIndex, int endIndex, string newSpan, int documentVersion)
{
this.intellisenseSession.UpdateDocumentSpan(filename, startIndex, endIndex, newSpan, documentVersion);
}
/// <summary>
/// Removes a document.
/// </summary>
/// <param name="filename">
/// The name of the document to remove.
/// </param>
public void RemoveDocument(string filename)
{
this.intellisenseSession.RemoveDocument(filename);
}
/// <summary>
/// Gets the document.
/// </summary>
/// <param name="filename">The file name.</param>
/// <returns>
/// The document desciptor or <c>null</c> if it wasn't found.
/// </returns>
[CanBeNull]
public IDocumentDescriptor GetDocument(string filename)
{
return Descriptor.Document(this.intellisenseSession.GetDocumentAsByteArray(filename));
}
/// <summary>
/// Executes the queries in the file or stream.
/// </summary>
/// <param name="filename">The name of the file.</param>
/// <param name="stream">The stream.</param>
/// <returns>
/// The result.
/// </returns>
public async Task<IExecuteResult> ExecuteAsync(string filename, Stream stream)
{
var result = new ResultCallback<byte[]>();
this.intellisenseSession.ExecuteWithCallback(filename, stream, result);
return Result.Deserialize(await result.Task);
}
/// <summary>
/// Loads the correct (already loaded) assembly.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The event arguments.
/// </param>
/// <returns>
/// The <see cref="Assembly"/>.
/// </returns>
[CanBeNull]
private static Assembly AppDomainFix(object sender, [NotNull] ResolveEventArgs e)
{
return e.Name == typeof(AppDomainIntellisenseSession).Assembly.FullName ? typeof(AppDomainIntellisenseSession).Assembly : null;
}
/// <summary>
/// Gets the projects recursively.
/// </summary>
/// <param name="project">
/// The project.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{T}"/>.
/// </returns>
private static IEnumerable<Project> GetProjectsRecursive([NotNull] Project project)
{
if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder)
{
var subProjects = project.ProjectItems
.Cast<ProjectItem>()
.Select(p => p.SubProject)
.Where(p => p != null)
.SelectMany(IntellisenseProxy.GetProjectsRecursive);
foreach (var subProject in subProjects)
{
yield return subProject;
}
}
else
{
yield return project;
}
}
/// <summary>
/// Gets a visual studio project by its unique name.
/// </summary>
/// <param name="uniqueName">
/// The unique name.
/// </param>
/// <returns>
/// The <see cref="VSProject"/>.
/// </returns>
[CanBeNull]
private static VSProject GetVisualStudioProjectByUniqueName(string uniqueName)
{
return ((DTE)Package.GetGlobalService(typeof(SDTE))).Solution.Projects
.Cast<Project>()
.SelectMany(IntellisenseProxy.GetProjectsRecursive)
.FirstOrDefault(p => p.UniqueName == uniqueName)?.Object as VSProject;
}
/// <summary>
/// Initializes the proxy.
/// </summary>
/// <param name="projectId">
/// The project id.
/// </param>
private void Init(string projectId)
{
Task.Run(() =>
{
try
{
var visualStudioProject = IntellisenseProxy.GetVisualStudioProjectByUniqueName(projectId);
var projectName = "Unknown project";
var configFile = (string)null;
var assemblies = new string[0];
if (visualStudioProject != null)
{
projectName = visualStudioProject.Project.Name;
try
{
this.referencesEvents = visualStudioProject.Events.ReferencesEvents;
this.referencesEvents.ReferenceAdded += this.ReferencesUpdated;
this.referencesEvents.ReferenceChanged += this.ReferencesUpdated;
this.referencesEvents.ReferenceRemoved += this.ReferencesUpdated;
}
catch (NotImplementedException)
{
//// CPS does not have reference events.
}
try
{
this.importsEvents = visualStudioProject.Events.ImportsEvents;
this.importsEvents.ImportAdded += this.ImportsUpdated;
this.importsEvents.ImportRemoved += this.ImportsUpdated;
}
catch (NotImplementedException)
{
//// CPS does not have import events.
}
configFile = visualStudioProject.Project.ProjectItems.OfType<ProjectItem>().FirstOrDefault(i => i.Name.EndsWith(".config", StringComparison.OrdinalIgnoreCase))?.FileNames[0];
assemblies = visualStudioProject.References.Cast<Reference>()
.Where(r =>
{
try
{
return !string.IsNullOrEmpty(r.Path);
}
catch
{
return false;
}
})
.Select(r => r.Path)
.ToArray();
}
var setupInfomation = AppDomain.CurrentDomain.SetupInformation;
setupInfomation.ApplicationBase = string.Empty;
setupInfomation.ConfigurationFile = configFile;
setupInfomation.LoaderOptimization = LoaderOptimization.SingleDomain;
AppDomain.CurrentDomain.AssemblyResolve += IntellisenseProxy.AppDomainFix;
this.appDomain = AppDomain.CreateDomain($"Intellisense project {projectName} domain", null, setupInfomation);
object[] arguments =
{
assemblies,
typeof(ConnectQlContext).Assembly.Location
};
this.watchPaths = assemblies
.Concat(new[]
{
configFile
}).ToArray();
this.WatchPaths(this.watchPaths);
this.handler = new RemoteEventHandler<byte[]>(this.IntellisenseSessionOnDocumentUpdated);
this.intellisenseSession = (AppDomainIntellisenseSession)this.appDomain.CreateInstanceFromAndUnwrap(
typeof(AppDomainIntellisenseSession).Assembly.Location,
typeof(AppDomainIntellisenseSession).FullName ?? string.Empty,
false,
BindingFlags.CreateInstance,
null,
arguments,
CultureInfo.CurrentCulture,
null);
this.intellisenseSession.DocumentUpdated += this.handler.Handler;
this.Initialized?.Invoke(this, EventArgs.Empty);
}
catch (Exception)
{
this.Dispose();
Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(1));
this.Init(projectId);
});
}
finally
{
AppDomain.CurrentDomain.AssemblyResolve -= IntellisenseProxy.AppDomainFix;
}
});
}
/// <summary>
/// The file changed.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="fileSystemEventArgs">
/// The file system event args.
/// </param>
private void FileChanged(object sender, FileSystemEventArgs fileSystemEventArgs)
{
if (!this.watchPaths.Any(path => path?.Equals(fileSystemEventArgs.FullPath, StringComparison.OrdinalIgnoreCase) ?? false))
{
return;
}
this.ReloadRequested?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// The imports updated.
/// </summary>
/// <param name="import">
/// The import.
/// </param>
private void ImportsUpdated(string import)
{
this.ReloadRequested?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Handles the <see cref="AppDomainIntellisenseSession.DocumentUpdated"/> event.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="serializedDocumentDescriptor">
/// The serialized document descriptor.
/// </param>
private void IntellisenseSessionOnDocumentUpdated(object sender, byte[] serializedDocumentDescriptor)
{
this.DocumentUpdated?.Invoke(this, new DocumentUpdatedEventArgs(serializedDocumentDescriptor));
}
/// <summary>
/// The references updated.
/// </summary>
/// <param name="reference">
/// The p reference.
/// </param>
private void ReferencesUpdated(Reference reference)
{
this.ReloadRequested?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// The watch paths.
/// </summary>
/// <param name="arguments">
/// The arguments.
/// </param>
private void WatchPaths([NotNull] IReadOnlyCollection<string> arguments)
{
this.watchers = new List<FileSystemWatcher>();
var paths = arguments.Select(Path.GetDirectoryName).OrderBy(argument => argument).Where(argument => argument != null).ToArray();
if (paths.Length == 0)
{
return;
}
var last = paths[0];
this.watchers.Add(new FileSystemWatcher
{
Path = last,
IncludeSubdirectories = true,
EnableRaisingEvents = true,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.DirectoryName,
Filter = "*.*"
});
foreach (var path in paths.Skip(1))
{
if (path.StartsWith(last, StringComparison.OrdinalIgnoreCase))
{
continue;
}
this.watchers.Add(new FileSystemWatcher
{
Path = path,
IncludeSubdirectories = true,
EnableRaisingEvents = true,
NotifyFilter = (NotifyFilters)383,
Filter = "*.*"
});
last = path;
}
foreach (var fileSystemWatcher in this.watchers)
{
fileSystemWatcher.Changed += this.FileChanged;
fileSystemWatcher.Renamed += this.FileChanged;
fileSystemWatcher.Deleted += this.FileChanged;
fileSystemWatcher.Created += this.FileChanged;
}
}
}
}
| |
//
// WindowBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
// Andres G. Aragoneses <andres.aragoneses@7digital.com>
// Konrad M. Kruczynski <kkruczynski@antmicro.com>
//
// Copyright (c) 2011 Xamarin Inc
// Copyright (c) 2012 7Digital Media Ltd
// Copyright (c) 2016 Antmicro Ltd
//
// 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 Xwt.Backends;
using System.Drawing;
#if MONOMAC
using nint = System.Int32;
using nfloat = System.Single;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
using CGRect = System.Drawing.RectangleF;
#else
using Foundation;
using AppKit;
using ObjCRuntime;
using CoreGraphics;
#endif
namespace Xwt.Mac
{
public class WindowBackend: NSWindow, IWindowBackend
{
WindowBackendController controller;
IWindowFrameEventSink eventSink;
Window frontend;
ViewBackend child;
NSView childView;
bool sensitive = true;
public WindowBackend (IntPtr ptr): base (ptr)
{
}
public WindowBackend ()
{
this.controller = new WindowBackendController ();
controller.Window = this;
StyleMask |= NSWindowStyle.Resizable | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable;
AutorecalculatesKeyViewLoop = true;
ContentView.AutoresizesSubviews = true;
ContentView.Hidden = true;
// TODO: do it only if mouse move events are enabled in a widget
AcceptsMouseMovedEvents = true;
WillClose += delegate {
OnClosed ();
};
Center ();
}
object IWindowFrameBackend.Window {
get { return this; }
}
public IntPtr NativeHandle {
get { return Handle; }
}
public IWindowFrameEventSink EventSink {
get { return (IWindowFrameEventSink)eventSink; }
}
public virtual void InitializeBackend (object frontend, ApplicationContext context)
{
this.ApplicationContext = context;
this.frontend = (Window) frontend;
}
public void Initialize (IWindowFrameEventSink eventSink)
{
this.eventSink = eventSink;
}
public ApplicationContext ApplicationContext {
get;
private set;
}
public object NativeWidget {
get {
return this;
}
}
public string Name { get; set; }
internal void InternalShow ()
{
MakeKeyAndOrderFront (MacEngine.App);
}
public void Present ()
{
MakeKeyAndOrderFront (MacEngine.App);
}
public bool Visible {
get {
return IsVisible;
}
set {
if (value)
MacEngine.App.ShowWindow(this);
ContentView.Hidden = !value; // handle shown/hidden events
IsVisible = value;
}
}
public double Opacity {
get { return AlphaValue; }
set { AlphaValue = (float)value; }
}
public bool Sensitive {
get {
return sensitive;
}
set {
sensitive = value;
if (child != null)
child.UpdateSensitiveStatus (child.Widget, sensitive);
}
}
public bool HasFocus {
get {
return IsKeyWindow;
}
}
public bool FullScreen {
get {
if (MacSystemInformation.OsVersion < MacSystemInformation.Lion)
return false;
return (StyleMask & NSWindowStyle.FullScreenWindow) != 0;
}
set {
if (MacSystemInformation.OsVersion < MacSystemInformation.Lion)
return;
if (value != ((StyleMask & NSWindowStyle.FullScreenWindow) != 0))
ToggleFullScreen (null);
}
}
object IWindowFrameBackend.Screen {
get {
return Screen;
}
}
#region IWindowBackend implementation
void IBackend.EnableEvent (object eventId)
{
if (eventId is WindowFrameEvent) {
var @event = (WindowFrameEvent)eventId;
switch (@event) {
case WindowFrameEvent.BoundsChanged:
DidResize += HandleDidResize;
#if MONOMAC
DidMoved += HandleDidResize;
#else
DidMove += HandleDidResize;
#endif
break;
case WindowFrameEvent.Hidden:
EnableVisibilityEvent (@event);
this.WillClose += OnWillClose;
break;
case WindowFrameEvent.Shown:
EnableVisibilityEvent (@event);
break;
case WindowFrameEvent.CloseRequested:
WindowShouldClose = OnShouldClose;
break;
}
}
}
void OnWillClose (object sender, EventArgs args) {
OnHidden ();
}
bool OnShouldClose (NSObject ob)
{
return closePerformed = RequestClose ();
}
internal bool RequestClose ()
{
bool res = true;
ApplicationContext.InvokeUserCode (() => res = eventSink.OnCloseRequested ());
return res;
}
protected virtual void OnClosed ()
{
if (!disposing)
ApplicationContext.InvokeUserCode (eventSink.OnClosed);
}
bool closePerformed;
bool IWindowFrameBackend.Close ()
{
closePerformed = true;
if ((StyleMask & NSWindowStyle.Titled) != 0 && (StyleMask & NSWindowStyle.Closable) != 0)
PerformClose(this);
else
Close ();
return closePerformed;
}
bool VisibilityEventsEnabled ()
{
return eventsEnabled != WindowFrameEvent.BoundsChanged;
}
WindowFrameEvent eventsEnabled = WindowFrameEvent.BoundsChanged;
NSString HiddenProperty {
get { return new NSString ("hidden"); }
}
void EnableVisibilityEvent (WindowFrameEvent ev)
{
if (!VisibilityEventsEnabled ()) {
ContentView.AddObserver (this, HiddenProperty, NSKeyValueObservingOptions.New, IntPtr.Zero);
}
if (!eventsEnabled.HasFlag (ev)) {
eventsEnabled |= ev;
}
}
public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
if (keyPath.ToString () == HiddenProperty.ToString () && ofObject.Equals (ContentView)) {
if (ContentView.Hidden) {
if (eventsEnabled.HasFlag (WindowFrameEvent.Hidden)) {
OnHidden ();
}
} else {
if (eventsEnabled.HasFlag (WindowFrameEvent.Shown)) {
OnShown ();
}
}
}
}
void OnHidden () {
ApplicationContext.InvokeUserCode (delegate ()
{
eventSink.OnHidden ();
});
}
void OnShown () {
ApplicationContext.InvokeUserCode (delegate ()
{
eventSink.OnShown ();
});
}
void DisableVisibilityEvent (WindowFrameEvent ev)
{
if (eventsEnabled.HasFlag (ev)) {
eventsEnabled ^= ev;
if (!VisibilityEventsEnabled ()) {
ContentView.RemoveObserver (this, HiddenProperty);
}
}
}
void IBackend.DisableEvent (object eventId)
{
if (eventId is WindowFrameEvent) {
var @event = (WindowFrameEvent)eventId;
switch (@event) {
case WindowFrameEvent.BoundsChanged:
DidResize -= HandleDidResize;
#if MONOMAC
DidMoved -= HandleDidResize;
#else
DidMove -= HandleDidResize;
#endif
break;
case WindowFrameEvent.Hidden:
this.WillClose -= OnWillClose;
DisableVisibilityEvent (@event);
break;
case WindowFrameEvent.Shown:
DisableVisibilityEvent (@event);
break;
}
}
}
void HandleDidResize (object sender, EventArgs e)
{
OnBoundsChanged ();
}
protected virtual void OnBoundsChanged ()
{
LayoutWindow ();
ApplicationContext.InvokeUserCode (delegate {
eventSink.OnBoundsChanged (((IWindowBackend)this).Bounds);
});
}
void IWindowBackend.SetChild (IWidgetBackend child)
{
if (this.child != null) {
ViewBackend.RemoveChildPlacement (this.child.Widget);
this.child.Widget.RemoveFromSuperview ();
childView = null;
}
this.child = (ViewBackend) child;
if (child != null) {
childView = ViewBackend.GetWidgetWithPlacement (child);
ContentView.AddSubview (childView);
LayoutWindow ();
childView.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
}
}
public virtual void UpdateChildPlacement (IWidgetBackend childBackend)
{
var w = ViewBackend.SetChildPlacement (childBackend);
LayoutWindow ();
w.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
}
bool IWindowFrameBackend.Decorated {
get {
return (StyleMask & NSWindowStyle.Titled) != 0;
}
set {
if (value)
StyleMask |= NSWindowStyle.Titled;
else
StyleMask &= ~(NSWindowStyle.Titled | NSWindowStyle.Borderless);
}
}
bool IWindowFrameBackend.ShowInTaskbar {
get {
return false;
}
set {
}
}
void IWindowFrameBackend.SetTransientFor (IWindowFrameBackend window)
{
// Generally, TransientFor is used to implement dialog, we reproduce the assumption here
Level = window == null ? NSWindowLevel.Normal : NSWindowLevel.ModalPanel;
}
bool IWindowFrameBackend.Resizable {
get {
return (StyleMask & NSWindowStyle.Resizable) != 0;
}
set {
if (value)
StyleMask |= NSWindowStyle.Resizable;
else
StyleMask &= ~NSWindowStyle.Resizable;
}
}
public void SetPadding (double left, double top, double right, double bottom)
{
LayoutWindow ();
}
void IWindowFrameBackend.Move (double x, double y)
{
var r = FrameRectFor (new CGRect ((nfloat)x, (nfloat)y, Frame.Width, Frame.Height));
SetFrame (r, true);
}
void IWindowFrameBackend.SetSize (double width, double height)
{
var cr = ContentRectFor (Frame);
if (width == -1)
width = cr.Width;
if (height == -1)
height = cr.Height;
var r = FrameRectFor (new CGRect ((nfloat)cr.X, (nfloat)cr.Y, (nfloat)width, (nfloat)height));
SetFrame (r, true);
LayoutWindow ();
}
Rectangle IWindowFrameBackend.Bounds {
get {
var b = ContentRectFor (Frame);
var r = MacDesktopBackend.ToDesktopRect (b);
return new Rectangle ((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height);
}
set {
var r = MacDesktopBackend.FromDesktopRect (value);
var fr = FrameRectFor (r);
SetFrame (fr, true);
}
}
public void SetMainMenu (IMenuBackend menu)
{
var m = (MenuBackend) menu;
m.SetMainMenuMode ();
NSApplication.SharedApplication.Menu = m;
// base.Menu = m;
}
#endregion
static Selector closeSel = new Selector ("close");
#if MONOMAC
static Selector retainSel = new Selector("retain");
#endif
bool disposing, disposed;
protected override void Dispose(bool disposing)
{
if (!disposed && disposing)
{
this.disposing = true;
try
{
if (VisibilityEventsEnabled() && ContentView != null)
ContentView.RemoveObserver(this, HiddenProperty);
// HACK: Xamarin.Mac/MonoMac limitation: no direct way to release a window manually
// A NSWindow instance will be removed from NSApplication.SharedApplication.Windows
// only if it is being closed with ReleasedWhenClosed set to true but not on Dispose
// and there is no managed way to tell Cocoa to release the window manually (and to
// remove it from the active window list).
// see also: https://bugzilla.xamarin.com/show_bug.cgi?id=45298
// WORKAROUND:
// bump native reference count by calling DangerousRetain()
// base.Dispose will now unref the window correctly without crashing
#if MONOMAC
Messaging.void_objc_msgSend(this.Handle, retainSel.Handle);
#else
DangerousRetain();
#endif
// tell Cocoa to release the window on Close
ReleasedWhenClosed = true;
// Close the window (Cocoa will do its job even if the window is already closed)
Messaging.void_objc_msgSend (this.Handle, closeSel.Handle);
} finally {
this.disposing = false;
this.disposed = true;
}
}
if (controller != null) {
controller.Dispose ();
controller = null;
}
base.Dispose (disposing);
}
public void DragStart (TransferDataSource data, DragDropAction dragAction, object dragImage, double xhot, double yhot)
{
throw new NotImplementedException ();
}
public void SetDragSource (string[] types, DragDropAction dragAction)
{
}
public void SetDragTarget (string[] types, DragDropAction dragAction)
{
}
public virtual void SetMinSize (Size s)
{
var b = ((IWindowBackend)this).Bounds;
if (b.Size.Width < s.Width)
b.Width = s.Width;
if (b.Size.Height < s.Height)
b.Height = s.Height;
if (b != ((IWindowBackend)this).Bounds)
((IWindowBackend)this).Bounds = b;
var r = FrameRectFor (new CGRect (0, 0, (nfloat)s.Width, (nfloat)s.Height));
MinSize = r.Size;
}
public void SetIcon (ImageDescription icon)
{
}
public virtual void GetMetrics (out Size minSize, out Size decorationSize)
{
minSize = decorationSize = Size.Zero;
}
public virtual void LayoutWindow ()
{
LayoutContent (ContentView.Frame);
}
public void LayoutContent (CGRect frame)
{
if (child != null) {
frame.X += (nfloat) frontend.Padding.Left;
frame.Width -= (nfloat) (frontend.Padding.HorizontalSpacing);
frame.Y += (nfloat) frontend.Padding.Top;
frame.Height -= (nfloat) (frontend.Padding.VerticalSpacing);
childView.Frame = frame;
}
}
}
public partial class WindowBackendController : NSWindowController
{
public WindowBackendController ()
{
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.IO;
namespace fyiReporting.RdlDesktop
{
class FileCache
{
Hashtable urls;
int cachehits;
int cacherequests;
public FileCache ()
{
urls = new Hashtable();
cachehits = 0;
cacherequests = 0;
}
// Add an URL to the cache. There are times where double work is performed.
// e.g. if we get multiple simultaneous requests for the same URL
// both might have gotten not found requests and proceeded to create
// new entries. This is a waste as we end up only using one. But this
// shouldn't occur very often and the inefficiency should be slight and
// temporary.
// In this case, the passed files are deleted and the old ones are used
public IList Add(string url, IList files)
{
CacheEntry ce=null;
lock (this)
{
ce = (CacheEntry) urls[url];
if (ce == null)
{ // entry isn't found; create new one
ce = new CacheEntry(url, files);
urls.Add(url, ce);
}
else
{ // We already had this entry; delete the new files
Console.WriteLine("debug: Double execution of url {0}", url);
ce.Timestamp = DateTime.Now; // update the timestamp
foreach (string file in files)
{
try
{
File.Delete(file);
}
catch (Exception e)
{
Console.WriteLine("An Exception occurred while clearing file cache :" +e.ToString());
}
}
}
}
return ce.Files;
}
public int CacheHits
{
get { return cachehits; }
set { cachehits = value; }
}
public int Count
{
get { return urls.Count; }
}
public IList Find(string url)
{
return Find(url, DateTime.MinValue);
}
public IList Find(string url, DateTime lastUpdateTime)
{
CacheEntry ce = null;
lock (this)
{
cacherequests++;
ce = (CacheEntry) urls[url];
if (ce != null)
{
if (lastUpdateTime > ce.CreatedTime)
{ // the url has been updated since the cache entry was created
DeleteUrlEntry(ce); // remove from cache
ce = null; // tell caller we didn't find it
}
else
{ // cache entry should still be valid
ce.Timestamp = DateTime.Now; // update the reference timestamp
cachehits++;
}
}
}
if (ce == null)
return null;
else
return ce.Files;
}
// Clear out the files based on the when they were last accessed. Caller passes
// the timespan they want to retain. Anything older gets tossed.
public int Clear(TimeSpan ts)
{
int numDeletedFiles=0;
lock (this)
{
DateTime ctime = DateTime.Now - ts; // anything older than this is deleted
// Build list of entries to be deleted
ArrayList f = new ArrayList();
foreach (CacheEntry ce in urls.Values)
{
if (ce.Timestamp < ctime)
f.Add(ce);
}
// Now delete them from the URL hash (and from the file system)
foreach (CacheEntry ce in f)
{
numDeletedFiles += DeleteUrlEntry(ce);
}
}
return numDeletedFiles;
}
private int DeleteUrlEntry(CacheEntry ce)
{
int numDeletedFiles=0;
urls.Remove(ce.Url);
foreach (string file in ce.Files)
{
try
{
File.Delete(file);
numDeletedFiles++;
}
catch (Exception e)
{
Console.WriteLine("An Exception occurred while clearing file cache :" +e.ToString());
}
}
return numDeletedFiles;
}
// Clear out all the cached files.
public int ClearAll()
{
int numDeletedFiles=0;
lock (this)
{
// Build list of entries to be deleted
foreach (CacheEntry ce in urls.Values)
{
foreach (string file in ce.Files)
{
try
{
File.Delete(file);
numDeletedFiles++;
}
catch (Exception e)
{
Console.WriteLine("An Exception occurred while clearing file cache :" +e.ToString());
}
}
}
// restart the cache
urls = new Hashtable();
cachehits=0;
cacherequests=0;
}
return numDeletedFiles;
}
}
class CacheEntry
{
string _Url; // URL of the report (including args)
IList _Files; // list of files associated with URL
DateTime _Timestamp; // time cache entry last referenced
DateTime _CreatedTime; // time cache entry created
public CacheEntry(string url, IList files)
{
_Url = url;
_Files = files;
_CreatedTime = _Timestamp = DateTime.Now;
}
public string Url
{
get { return _Url; }
}
public IList Files
{
get { return _Files; }
}
public DateTime Timestamp
{
get { return _Timestamp; }
set { _Timestamp = value; }
}
public DateTime CreatedTime
{
get { return _CreatedTime; }
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.ComponentModel;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Delegate used by tests that execute code and
/// capture any thrown exception.
/// </summary>
public delegate void TestDelegate();
#if NET_4_0 || NET_4_5 || PORTABLE
/// <summary>
/// Delegate used by tests that execute async code and
/// capture any thrown exception.
/// </summary>
public delegate System.Threading.Tasks.Task AsyncTestDelegate();
#endif
/// <summary>
/// The Assert class contains a collection of static methods that
/// implement the most common assertions used in NUnit.
/// </summary>
public partial class Assert
{
#region Constructor
/// <summary>
/// We don't actually want any instances of this object, but some people
/// like to inherit from it to add other static methods. Hence, the
/// protected constructor disallows any instances of this object.
/// </summary>
protected Assert() { }
#endregion
#region Equals and ReferenceEquals
/// <summary>
/// The Equals method throws an AssertionException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool Equals(object a, object b)
{
throw new InvalidOperationException("Assert.Equals should not be used for Assertions");
}
/// <summary>
/// override the default ReferenceEquals to throw an AssertionException. This
/// implementation makes sure there is no mistake in calling this function
/// as part of Assert.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
public static new void ReferenceEquals(object a, object b)
{
throw new InvalidOperationException("Assert.ReferenceEquals should not be used for Assertions");
}
#endregion
#region Pass
/// <summary>
/// Throws a <see cref="SuccessException"/> with the message and arguments
/// that are passed in. This allows a test to be cut short, with a result
/// of success returned to NUnit.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Pass(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
throw new SuccessException(message);
}
/// <summary>
/// Throws a <see cref="SuccessException"/> with the message and arguments
/// that are passed in. This allows a test to be cut short, with a result
/// of success returned to NUnit.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
static public void Pass(string message)
{
Assert.Pass(message, null);
}
/// <summary>
/// Throws a <see cref="SuccessException"/> with the message and arguments
/// that are passed in. This allows a test to be cut short, with a result
/// of success returned to NUnit.
/// </summary>
static public void Pass()
{
Assert.Pass(string.Empty, null);
}
#endregion
#region Fail
/// <summary>
/// Throws an <see cref="AssertionException"/> with the message and arguments
/// that are passed in. This is used by the other Assert functions.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Fail(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
throw new AssertionException(message);
}
/// <summary>
/// Throws an <see cref="AssertionException"/> with the message that is
/// passed in. This is used by the other Assert functions.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
static public void Fail(string message)
{
Assert.Fail(message, null);
}
/// <summary>
/// Throws an <see cref="AssertionException"/>.
/// This is used by the other Assert functions.
/// </summary>
static public void Fail()
{
Assert.Fail(string.Empty, null);
}
#endregion
#region Ignore
/// <summary>
/// Throws an <see cref="IgnoreException"/> with the message and arguments
/// that are passed in. This causes the test to be reported as ignored.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Ignore(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
throw new IgnoreException(message);
}
/// <summary>
/// Throws an <see cref="IgnoreException"/> with the message that is
/// passed in. This causes the test to be reported as ignored.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
static public void Ignore(string message)
{
Assert.Ignore(message, null);
}
/// <summary>
/// Throws an <see cref="IgnoreException"/>.
/// This causes the test to be reported as ignored.
/// </summary>
static public void Ignore()
{
Assert.Ignore(string.Empty, null);
}
#endregion
#region InConclusive
/// <summary>
/// Throws an <see cref="InconclusiveException"/> with the message and arguments
/// that are passed in. This causes the test to be reported as inconclusive.
/// </summary>
/// <param name="message">The message to initialize the <see cref="InconclusiveException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Inconclusive(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
throw new InconclusiveException(message);
}
/// <summary>
/// Throws an <see cref="InconclusiveException"/> with the message that is
/// passed in. This causes the test to be reported as inconclusive.
/// </summary>
/// <param name="message">The message to initialize the <see cref="InconclusiveException"/> with.</param>
static public void Inconclusive(string message)
{
Assert.Inconclusive(message, null);
}
/// <summary>
/// Throws an <see cref="InconclusiveException"/>.
/// This causes the test to be reported as Inconclusive.
/// </summary>
static public void Inconclusive()
{
Assert.Inconclusive(string.Empty, null);
}
#endregion
#region Contains
/// <summary>
/// Asserts that an object is contained in a list.
/// </summary>
/// <param name="expected">The expected object</param>
/// <param name="actual">The list to be examined</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Contains(object expected, ICollection actual, string message, params object[] args)
{
Assert.That(actual, new CollectionContainsConstraint(expected) ,message, args);
}
/// <summary>
/// Asserts that an object is contained in a list.
/// </summary>
/// <param name="expected">The expected object</param>
/// <param name="actual">The list to be examined</param>
public static void Contains(object expected, ICollection actual)
{
Assert.That(actual, new CollectionContainsConstraint(expected) ,null, null);
}
#endregion
#region Multiple
///// <summary>
///// If an assert fails within this block, execution will continue and
///// the errors will be reported at the end of the block.
///// </summary>
///// <param name="del">The test delegate</param>
//public static void Multiple(TestDelegate del)
//{
// del();
//}
#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;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Rules for the Hijri calendar:
// - The Hijri calendar is a strictly Lunar calendar.
// - Days begin at sunset.
// - Islamic Year 1 (Muharram 1, 1 A.H.) is equivalent to absolute date
// 227015 (Friday, July 16, 622 C.E. - Julian).
// - Leap Years occur in the 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, & 29th
// years of a 30-year cycle. Year = leap iff ((11y+14) mod 30 < 11).
// - There are 12 months which contain alternately 30 and 29 days.
// - The 12th month, Dhu al-Hijjah, contains 30 days instead of 29 days
// in a leap year.
// - Common years have 354 days. Leap years have 355 days.
// - There are 10,631 days in a 30-year cycle.
// - The Islamic months are:
// 1. Muharram (30 days) 7. Rajab (30 days)
// 2. Safar (29 days) 8. Sha'ban (29 days)
// 3. Rabi I (30 days) 9. Ramadan (30 days)
// 4. Rabi II (29 days) 10. Shawwal (29 days)
// 5. Jumada I (30 days) 11. Dhu al-Qada (30 days)
// 6. Jumada II (29 days) 12. Dhu al-Hijjah (29 days) {30}
//
// NOTENOTE
// The calculation of the HijriCalendar is based on the absolute date. And the
// absolute date means the number of days from January 1st, 1 A.D.
// Therefore, we do not support the days before the January 1st, 1 A.D.
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0622/07/18 9999/12/31
** Hijri 0001/01/01 9666/04/03
*/
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public partial class HijriCalendar : Calendar
{
public static readonly int HijriEra = 1;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
internal const int MinAdvancedHijri = -2;
internal const int MaxAdvancedHijri = 2;
internal static readonly int[] HijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 };
private int _hijriAdvance = Int32.MinValue;
// DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3).
internal const int MaxCalendarYear = 9666;
internal const int MaxCalendarMonth = 4;
internal const int MaxCalendarDay = 3;
// Hijri calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 7, day: 18)
// This is the minimal Gregorian date that we support in the HijriCalendar.
internal static readonly DateTime calendarMinValue = new DateTime(622, 7, 18);
internal static readonly DateTime calendarMaxValue = DateTime.MaxValue;
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (calendarMaxValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.LunarCalendar;
}
}
public HijriCalendar()
{
}
internal override CalendarId ID
{
get
{
return CalendarId.HIJRI;
}
}
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// the year before the 1st year of the cycle would have been the 30th year
// of the previous cycle which is not a leap year. Common years have 354 days.
return 354;
}
}
/*=================================GetAbsoluteDateHijri==========================
**Action: Gets the Absolute date for the given Hijri date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
private long GetAbsoluteDateHijri(int y, int m, int d)
{
return (long)(DaysUpToHijriYear(y) + HijriMonthDays[m - 1] + d - 1 - HijriAdjustment);
}
/*=================================DaysUpToHijriYear==========================
**Action: Gets the total number of days (absolute date) up to the given Hijri Year.
** The absolute date means the number of days from January 1st, 1 A.D.
**Returns: Gets the total number of days (absolute date) up to the given Hijri Year.
**Arguments: HijriYear year value in Hijri calendar.
**Exceptions: None
**Notes:
============================================================================*/
private long DaysUpToHijriYear(int HijriYear)
{
long NumDays; // number of absolute days
int NumYear30; // number of years up to current 30 year cycle
int NumYearsLeft; // number of years into 30 year cycle
//
// Compute the number of years up to the current 30 year cycle.
//
NumYear30 = ((HijriYear - 1) / 30) * 30;
//
// Compute the number of years left. This is the number of years
// into the 30 year cycle for the given year.
//
NumYearsLeft = HijriYear - NumYear30 - 1;
//
// Compute the number of absolute days up to the given year.
//
NumDays = ((NumYear30 * 10631L) / 30L) + 227013L;
while (NumYearsLeft > 0)
{
// Common year is 354 days, and leap year is 355 days.
NumDays += 354 + (IsLeapYear(NumYearsLeft, CurrentEra) ? 1 : 0);
NumYearsLeft--;
}
//
// Return the number of absolute days.
//
return (NumDays);
}
public int HijriAdjustment
{
get
{
if (_hijriAdvance == Int32.MinValue)
{
// Never been set before. Use the system value from registry.
_hijriAdvance = GetHijriDateAdjustment();
}
return (_hijriAdvance);
}
set
{
// NOTE: Check the value of Min/MaxAdavncedHijri with Arabic speakers to see if the assumption is good.
if (value < MinAdvancedHijri || value > MaxAdvancedHijri)
{
throw new ArgumentOutOfRangeException(
"HijriAdjustment",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
MinAdvancedHijri,
MaxAdvancedHijri));
}
Contract.EndContractBlock();
VerifyWritable();
_hijriAdvance = value;
}
}
internal static void CheckTicksRange(long ticks)
{
if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
String.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
calendarMinValue,
calendarMaxValue));
}
}
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != HijriEra)
{
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal static void CheckYearRange(int year, int era)
{
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
}
internal static void CheckYearMonthRange(int year, int month, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
if (month > MaxCalendarMonth)
{
throw new ArgumentOutOfRangeException(
"month",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarMonth));
}
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
}
/*=================================GetDatePart==========================
**Action: Returns a given date part of this <i>DateTime</i>. This method is used
** to compute the year, day-of-year, month, or day part.
**Returns:
**Arguments:
**Exceptions: ArgumentException if part is incorrect.
**Notes:
** First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks.
** Use the formula (((AbsoluteDate - 227013) * 30) / 10631) + 1, we can a rough value for the Hijri year.
** In order to get the exact Hijri year, we compare the exact absolute date for HijriYear and (HijriYear + 1).
** From here, we can get the correct Hijri year.
============================================================================*/
internal virtual int GetDatePart(long ticks, int part)
{
int HijriYear; // Hijri year
int HijriMonth; // Hijri month
int HijriDay; // Hijri day
long NumDays; // The calculation buffer in number of days.
CheckTicksRange(ticks);
//
// Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
//
NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
//
// See how much we need to backup or advance
//
NumDays += HijriAdjustment;
//
// Calculate the appromixate Hijri Year from this magic formula.
//
HijriYear = (int)(((NumDays - 227013) * 30) / 10631) + 1;
long daysToHijriYear = DaysUpToHijriYear(HijriYear); // The absoulte date for HijriYear
long daysOfHijriYear = GetDaysInYear(HijriYear, CurrentEra); // The number of days for (HijriYear+1) year.
if (NumDays < daysToHijriYear)
{
daysToHijriYear -= daysOfHijriYear;
HijriYear--;
}
else if (NumDays == daysToHijriYear)
{
HijriYear--;
daysToHijriYear -= GetDaysInYear(HijriYear, CurrentEra);
}
else
{
if (NumDays > daysToHijriYear + daysOfHijriYear)
{
daysToHijriYear += daysOfHijriYear;
HijriYear++;
}
}
if (part == DatePartYear)
{
return (HijriYear);
}
//
// Calculate the Hijri Month.
//
HijriMonth = 1;
NumDays -= daysToHijriYear;
if (part == DatePartDayOfYear)
{
return ((int)NumDays);
}
while ((HijriMonth <= 12) && (NumDays > HijriMonthDays[HijriMonth - 1]))
{
HijriMonth++;
}
HijriMonth--;
if (part == DatePartMonth)
{
return (HijriMonth);
}
//
// Calculate the Hijri Day.
//
HijriDay = (int)(NumDays - HijriMonthDays[HijriMonth - 1]);
if (part == DatePartDay)
{
return (HijriDay);
}
// Incorrect part value.
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
// Get the date in Hijri calendar.
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = GetAbsoluteDateHijri(y, m, d) * TicksPerDay + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
[Pure]
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
if (month == 12)
{
// For the 12th month, leap year has 30 days, and common year has 29 days.
return (IsLeapYear(year, CurrentEra) ? 30 : 29);
}
// Other months contain 30 and 29 days alternatively. The 1st month has 30 days.
return (((month % 2) == 1) ? 30 : 29);
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
CheckYearRange(year, era);
// Common years have 354 days. Leap years have 355 days.
return (IsLeapYear(year, CurrentEra) ? 355 : 354);
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
CheckTicksRange(time.Ticks);
return (HijriEra);
}
public override int[] Eras
{
get
{
return (new int[] { HijriEra });
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
CheckYearRange(year, era);
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and MaxCalendarYear.
//
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
return (IsLeapYear(year, era) && month == 12 && day == 30);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearRange(year, era);
return ((((year * 11) + 14) % 30) < 11);
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
// The year/month/era checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
long lDate = GetAbsoluteDateHijri(year, month, day);
if (lDate >= 0)
{
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1451;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"value",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxCalendarYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return (base.ToFourDigitYear(year));
}
if (year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
return (year);
}
}
}
| |
// 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.
/*=============================================================================
**
**
**
** Purpose: ITypeInfo interface definition.
**
**
=============================================================================*/
using System;
namespace System.Runtime.InteropServices.ComTypes
{
public enum TYPEKIND
{
TKIND_ENUM = 0,
TKIND_RECORD = TKIND_ENUM + 1,
TKIND_MODULE = TKIND_RECORD + 1,
TKIND_INTERFACE = TKIND_MODULE + 1,
TKIND_DISPATCH = TKIND_INTERFACE + 1,
TKIND_COCLASS = TKIND_DISPATCH + 1,
TKIND_ALIAS = TKIND_COCLASS + 1,
TKIND_UNION = TKIND_ALIAS + 1,
TKIND_MAX = TKIND_UNION + 1
}
[Flags()]
public enum TYPEFLAGS : short
{
TYPEFLAG_FAPPOBJECT = 0x1,
TYPEFLAG_FCANCREATE = 0x2,
TYPEFLAG_FLICENSED = 0x4,
TYPEFLAG_FPREDECLID = 0x8,
TYPEFLAG_FHIDDEN = 0x10,
TYPEFLAG_FCONTROL = 0x20,
TYPEFLAG_FDUAL = 0x40,
TYPEFLAG_FNONEXTENSIBLE = 0x80,
TYPEFLAG_FOLEAUTOMATION = 0x100,
TYPEFLAG_FRESTRICTED = 0x200,
TYPEFLAG_FAGGREGATABLE = 0x400,
TYPEFLAG_FREPLACEABLE = 0x800,
TYPEFLAG_FDISPATCHABLE = 0x1000,
TYPEFLAG_FREVERSEBIND = 0x2000,
TYPEFLAG_FPROXY = 0x4000
}
[Flags()]
public enum IMPLTYPEFLAGS
{
IMPLTYPEFLAG_FDEFAULT = 0x1,
IMPLTYPEFLAG_FSOURCE = 0x2,
IMPLTYPEFLAG_FRESTRICTED = 0x4,
IMPLTYPEFLAG_FDEFAULTVTABLE = 0x8,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct TYPEATTR
{
// Constant used with the memid fields.
public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF);
// Actual fields of the TypeAttr struct.
public Guid guid;
public Int32 lcid;
public Int32 dwReserved;
public Int32 memidConstructor;
public Int32 memidDestructor;
public IntPtr lpstrSchema;
public Int32 cbSizeInstance;
public TYPEKIND typekind;
public Int16 cFuncs;
public Int16 cVars;
public Int16 cImplTypes;
public Int16 cbSizeVft;
public Int16 cbAlignment;
public TYPEFLAGS wTypeFlags;
public Int16 wMajorVerNum;
public Int16 wMinorVerNum;
public TYPEDESC tdescAlias;
public IDLDESC idldescType;
}
[StructLayout(LayoutKind.Sequential)]
public struct FUNCDESC
{
public int memid; //MEMBERID memid;
public IntPtr lprgscode; // /* [size_is(cScodes)] */ SCODE RPC_FAR *lprgscode;
public IntPtr lprgelemdescParam; // /* [size_is(cParams)] */ ELEMDESC __RPC_FAR *lprgelemdescParam;
public FUNCKIND funckind; //FUNCKIND funckind;
public INVOKEKIND invkind; //INVOKEKIND invkind;
public CALLCONV callconv; //CALLCONV callconv;
public Int16 cParams; //short cParams;
public Int16 cParamsOpt; //short cParamsOpt;
public Int16 oVft; //short oVft;
public Int16 cScodes; //short cScodes;
public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc;
public Int16 wFuncFlags; //WORD wFuncFlags;
}
[Flags()]
public enum IDLFLAG : short
{
IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE,
IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN,
IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT,
IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID,
IDLFLAG_FRETVAL = PARAMFLAG.PARAMFLAG_FRETVAL
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct IDLDESC
{
public IntPtr dwReserved;
public IDLFLAG wIDLFlags;
}
[Flags()]
public enum PARAMFLAG : short
{
PARAMFLAG_NONE = 0,
PARAMFLAG_FIN = 0x1,
PARAMFLAG_FOUT = 0x2,
PARAMFLAG_FLCID = 0x4,
PARAMFLAG_FRETVAL = 0x8,
PARAMFLAG_FOPT = 0x10,
PARAMFLAG_FHASDEFAULT = 0x20,
PARAMFLAG_FHASCUSTDATA = 0x40
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct PARAMDESC
{
public IntPtr lpVarValue;
public PARAMFLAG wParamFlags;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct TYPEDESC
{
public IntPtr lpValue;
public Int16 vt;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct ELEMDESC
{
public TYPEDESC tdesc;
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
public struct DESCUNION
{
[FieldOffset(0)]
public IDLDESC idldesc;
[FieldOffset(0)]
public PARAMDESC paramdesc;
};
public DESCUNION desc;
}
public enum VARKIND : int
{
VAR_PERINSTANCE = 0x0,
VAR_STATIC = 0x1,
VAR_CONST = 0x2,
VAR_DISPATCH = 0x3
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct VARDESC
{
public int memid;
public String lpstrSchema;
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
public struct DESCUNION
{
[FieldOffset(0)]
public int oInst;
[FieldOffset(0)]
public IntPtr lpvarValue;
};
public DESCUNION desc;
public ELEMDESC elemdescVar;
public short wVarFlags;
public VARKIND varkind;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DISPPARAMS
{
public IntPtr rgvarg;
public IntPtr rgdispidNamedArgs;
public int cArgs;
public int cNamedArgs;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct EXCEPINFO
{
public Int16 wCode;
public Int16 wReserved;
[MarshalAs(UnmanagedType.BStr)] public String bstrSource;
[MarshalAs(UnmanagedType.BStr)] public String bstrDescription;
[MarshalAs(UnmanagedType.BStr)] public String bstrHelpFile;
public int dwHelpContext;
public IntPtr pvReserved;
public IntPtr pfnDeferredFillIn;
public Int32 scode;
}
public enum FUNCKIND : int
{
FUNC_VIRTUAL = 0,
FUNC_PUREVIRTUAL = 1,
FUNC_NONVIRTUAL = 2,
FUNC_STATIC = 3,
FUNC_DISPATCH = 4
}
[Flags]
public enum INVOKEKIND : int
{
INVOKE_FUNC = 0x1,
INVOKE_PROPERTYGET = 0x2,
INVOKE_PROPERTYPUT = 0x4,
INVOKE_PROPERTYPUTREF = 0x8
}
public enum CALLCONV : int
{
CC_CDECL = 1,
CC_MSCPASCAL = 2,
CC_PASCAL = CC_MSCPASCAL,
CC_MACPASCAL = 3,
CC_STDCALL = 4,
CC_RESERVED = 5,
CC_SYSCALL = 6,
CC_MPWCDECL = 7,
CC_MPWPASCAL = 8,
CC_MAX = 9
}
[Flags()]
public enum FUNCFLAGS : short
{
FUNCFLAG_FRESTRICTED = 0x1,
FUNCFLAG_FSOURCE = 0x2,
FUNCFLAG_FBINDABLE = 0x4,
FUNCFLAG_FREQUESTEDIT = 0x8,
FUNCFLAG_FDISPLAYBIND = 0x10,
FUNCFLAG_FDEFAULTBIND = 0x20,
FUNCFLAG_FHIDDEN = 0x40,
FUNCFLAG_FUSESGETLASTERROR = 0x80,
FUNCFLAG_FDEFAULTCOLLELEM = 0x100,
FUNCFLAG_FUIDEFAULT = 0x200,
FUNCFLAG_FNONBROWSABLE = 0x400,
FUNCFLAG_FREPLACEABLE = 0x800,
FUNCFLAG_FIMMEDIATEBIND = 0x1000
}
[Flags()]
public enum VARFLAGS : short
{
VARFLAG_FREADONLY = 0x1,
VARFLAG_FSOURCE = 0x2,
VARFLAG_FBINDABLE = 0x4,
VARFLAG_FREQUESTEDIT = 0x8,
VARFLAG_FDISPLAYBIND = 0x10,
VARFLAG_FDEFAULTBIND = 0x20,
VARFLAG_FHIDDEN = 0x40,
VARFLAG_FRESTRICTED = 0x80,
VARFLAG_FDEFAULTCOLLELEM = 0x100,
VARFLAG_FUIDEFAULT = 0x200,
VARFLAG_FNONBROWSABLE = 0x400,
VARFLAG_FREPLACEABLE = 0x800,
VARFLAG_FIMMEDIATEBIND = 0x1000
}
[Guid("00020401-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ITypeInfo
{
void GetTypeAttr(out IntPtr ppTypeAttr);
void GetTypeComp(out ITypeComp ppTComp);
void GetFuncDesc(int index, out IntPtr ppFuncDesc);
void GetVarDesc(int index, out IntPtr ppVarDesc);
void GetNames(int memid, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2), Out] String[] rgBstrNames, int cMaxNames, out int pcNames);
void GetRefTypeOfImplType(int index, out int href);
void GetImplTypeFlags(int index, out IMPLTYPEFLAGS pImplTypeFlags);
void GetIDsOfNames([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1), In] String[] rgszNames, int cNames, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] int[] pMemId);
void Invoke([MarshalAs(UnmanagedType.IUnknown)] Object pvInstance, int memid, Int16 wFlags, ref DISPPARAMS pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, out int puArgErr);
void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile);
void GetDllEntry(int memid, INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal);
void GetRefTypeInfo(int hRef, out ITypeInfo ppTI);
void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv);
void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] Object pUnkOuter, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out Object ppvObj);
void GetMops(int memid, out String pBstrMops);
void GetContainingTypeLib(out ITypeLib ppTLB, out int pIndex);
[PreserveSig]
void ReleaseTypeAttr(IntPtr pTypeAttr);
[PreserveSig]
void ReleaseFuncDesc(IntPtr pFuncDesc);
[PreserveSig]
void ReleaseVarDesc(IntPtr pVarDesc);
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Base for handling both client side and server side calls.
/// Manages native call lifecycle and provides convenience methods.
/// </summary>
internal abstract class AsyncCallBase<TWrite, TRead>
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>();
protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message.");
readonly Func<TWrite, byte[]> serializer;
readonly Func<byte[], TRead> deserializer;
protected readonly GrpcEnvironment environment;
protected readonly object myLock = new object();
protected INativeCall call;
protected bool disposed;
protected bool started;
protected bool cancelRequested;
protected AsyncCompletionDelegate<object> sendCompletionDelegate; // Completion of a pending send or sendclose if not null.
protected AsyncCompletionDelegate<TRead> readCompletionDelegate; // Completion of a pending send or sendclose if not null.
protected bool readingDone; // True if last read (i.e. read with null payload) was already received.
protected bool halfcloseRequested; // True if send close have been initiated.
protected bool finished; // True if close has been received from the peer.
protected bool initialMetadataSent;
protected long streamingWritesCounter; // Number of streaming send operations started so far.
public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer, GrpcEnvironment environment)
{
this.serializer = GrpcPreconditions.CheckNotNull(serializer);
this.deserializer = GrpcPreconditions.CheckNotNull(deserializer);
this.environment = GrpcPreconditions.CheckNotNull(environment);
}
/// <summary>
/// Requests cancelling the call.
/// </summary>
public void Cancel()
{
lock (myLock)
{
GrpcPreconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
{
call.Cancel();
}
}
}
/// <summary>
/// Requests cancelling the call with given status.
/// </summary>
protected void CancelWithStatus(Status status)
{
lock (myLock)
{
cancelRequested = true;
if (!disposed)
{
call.CancelWithStatus(status);
}
}
}
protected void InitializeInternal(INativeCall call)
{
lock (myLock)
{
this.call = call;
}
}
/// <summary>
/// Initiates sending a message. Only one send operation can be active at a time.
/// completionDelegate is invoked upon completion.
/// </summary>
protected void StartSendMessageInternal(TWrite msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate)
{
byte[] payload = UnsafeSerialize(msg);
lock (myLock)
{
GrpcPreconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckSendingAllowed(allowFinished: false);
call.StartSendMessage(HandleSendFinished, payload, writeFlags, !initialMetadataSent);
sendCompletionDelegate = completionDelegate;
initialMetadataSent = true;
streamingWritesCounter++;
}
}
/// <summary>
/// Initiates reading a message. Only one read operation can be active at a time.
/// completionDelegate is invoked upon completion.
/// </summary>
protected void StartReadMessageInternal(AsyncCompletionDelegate<TRead> completionDelegate)
{
lock (myLock)
{
GrpcPreconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckReadingAllowed();
call.StartReceiveMessage(HandleReadFinished);
readCompletionDelegate = completionDelegate;
}
}
/// <summary>
/// If there are no more pending actions and no new actions can be started, releases
/// the underlying native resources.
/// </summary>
protected bool ReleaseResourcesIfPossible()
{
using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.ReleaseResourcesIfPossible"))
{
if (!disposed && call != null)
{
bool noMoreSendCompletions = sendCompletionDelegate == null && (halfcloseRequested || cancelRequested || finished);
if (noMoreSendCompletions && readingDone && finished)
{
ReleaseResources();
return true;
}
}
return false;
}
}
protected abstract bool IsClient
{
get;
}
private void ReleaseResources()
{
if (call != null)
{
call.Dispose();
}
disposed = true;
OnAfterReleaseResources();
}
protected virtual void OnAfterReleaseResources()
{
}
protected void CheckSendingAllowed(bool allowFinished)
{
GrpcPreconditions.CheckState(started);
CheckNotCancelled();
GrpcPreconditions.CheckState(!disposed || allowFinished);
GrpcPreconditions.CheckState(!halfcloseRequested, "Already halfclosed.");
GrpcPreconditions.CheckState(!finished || allowFinished, "Already finished.");
GrpcPreconditions.CheckState(sendCompletionDelegate == null, "Only one write can be pending at a time");
}
protected virtual void CheckReadingAllowed()
{
GrpcPreconditions.CheckState(started);
GrpcPreconditions.CheckState(!disposed);
GrpcPreconditions.CheckState(!readingDone, "Stream has already been closed.");
GrpcPreconditions.CheckState(readCompletionDelegate == null, "Only one read can be pending at a time");
}
protected void CheckNotCancelled()
{
if (cancelRequested)
{
throw new OperationCanceledException("Remote call has been cancelled.");
}
}
protected byte[] UnsafeSerialize(TWrite msg)
{
using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.UnsafeSerialize"))
{
return serializer(msg);
}
}
protected Exception TryDeserialize(byte[] payload, out TRead msg)
{
using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.TryDeserialize"))
{
try
{
msg = deserializer(payload);
return null;
}
catch (Exception e)
{
msg = default(TRead);
return e;
}
}
}
protected void FireCompletion<T>(AsyncCompletionDelegate<T> completionDelegate, T value, Exception error)
{
try
{
completionDelegate(value, error);
}
catch (Exception e)
{
Logger.Error(e, "Exception occured while invoking completion delegate.");
}
}
/// <summary>
/// Handles send completion.
/// </summary>
protected void HandleSendFinished(bool success)
{
AsyncCompletionDelegate<object> origCompletionDelegate = null;
lock (myLock)
{
origCompletionDelegate = sendCompletionDelegate;
sendCompletionDelegate = null;
ReleaseResourcesIfPossible();
}
if (!success)
{
FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Send failed"));
}
else
{
FireCompletion(origCompletionDelegate, null, null);
}
}
/// <summary>
/// Handles halfclose (send close from client) completion.
/// </summary>
protected void HandleSendCloseFromClientFinished(bool success)
{
AsyncCompletionDelegate<object> origCompletionDelegate = null;
lock (myLock)
{
origCompletionDelegate = sendCompletionDelegate;
sendCompletionDelegate = null;
ReleaseResourcesIfPossible();
}
if (!success)
{
FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Sending close from client has failed."));
}
else
{
FireCompletion(origCompletionDelegate, null, null);
}
}
/// <summary>
/// Handles send status from server completion.
/// </summary>
protected void HandleSendStatusFromServerFinished(bool success)
{
AsyncCompletionDelegate<object> origCompletionDelegate = null;
lock (myLock)
{
origCompletionDelegate = sendCompletionDelegate;
sendCompletionDelegate = null;
ReleaseResourcesIfPossible();
}
if (!success)
{
FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Error sending status from server."));
}
else
{
FireCompletion(origCompletionDelegate, null, null);
}
}
/// <summary>
/// Handles streaming read completion.
/// </summary>
protected void HandleReadFinished(bool success, byte[] receivedMessage)
{
TRead msg = default(TRead);
var deserializeException = (success && receivedMessage != null) ? TryDeserialize(receivedMessage, out msg) : null;
AsyncCompletionDelegate<TRead> origCompletionDelegate = null;
lock (myLock)
{
origCompletionDelegate = readCompletionDelegate;
readCompletionDelegate = null;
if (receivedMessage == null)
{
// This was the last read.
readingDone = true;
}
if (deserializeException != null && IsClient)
{
readingDone = true;
CancelWithStatus(DeserializeResponseFailureStatus);
}
ReleaseResourcesIfPossible();
}
// TODO: handle the case when success==false
if (deserializeException != null && !IsClient)
{
FireCompletion(origCompletionDelegate, default(TRead), new IOException("Failed to deserialize request message.", deserializeException));
return;
}
FireCompletion(origCompletionDelegate, msg, null);
}
}
}
| |
using ChatSharp.Events;
using ChatSharp.Handlers;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Timers;
namespace ChatSharp
{
/// <summary>
/// An IRC client.
/// </summary>
public sealed partial class IrcClient
{
/// <summary>
/// A raw IRC message handler.
/// </summary>
public delegate void MessageHandler( IrcClient client, IrcMessage message );
private Dictionary<string, MessageHandler> Handlers { get; set; }
/// <summary>
/// Sets a custom handler for an IRC message. This applies to the low level IRC protocol,
/// not for private messages.
/// </summary>
public void SetHandler( string message, MessageHandler handler )
{
#if DEBUG
// This is the default behavior if 3rd parties want to handle certain messages themselves
// However, if it happens from our own code, we probably did something wrong
if ( Handlers.ContainsKey( message.ToUpper() ) )
Console.WriteLine( "Warning: {0} handler has been overwritten", message );
#endif
message = message.ToUpper();
Handlers[ message ] = handler;
}
internal static DateTime DateTimeFromIrcTime( int time )
{
return new DateTime( 1970, 1, 1 ).AddSeconds( time );
}
private const int ReadBufferLength = 1024;
private byte[] ReadBuffer { get; set; }
private int ReadBufferIndex { get; set; }
private string ServerHostname { get; set; }
private int ServerPort { get; set; }
private Timer PingTimer { get; set; }
private Socket Socket { get; set; }
private ConcurrentQueue<String> WriteQueue { get; set; }
private bool IsWriting { get; set; }
internal RequestManager RequestManager { get; set; }
internal string ServerNameFromPing { get; set; }
public Boolean Connected
{
get
{
return this.Socket.Connected;
}
}
public Boolean ConnectCompleted
{
get;
private set;
}
/// <summary>
/// The address this client is connected to, or will connect to. Setting this
/// after the client is connected will not cause a reconnect.
/// </summary>
public string ServerAddress
{
get
{
return ServerHostname + ":" + ServerPort;
}
internal set
{
string[] parts = value.Split( ':' );
if ( parts.Length > 2 || parts.Length == 0 )
throw new FormatException( "Server address is not in correct format ('hostname:port')" );
ServerHostname = parts[ 0 ];
if ( parts.Length > 1 )
ServerPort = int.Parse( parts[ 1 ] );
else
ServerPort = 6667;
}
}
/// <summary>
/// The low level TCP stream for this client.
/// </summary>
public Stream NetworkStream { get; set; }
/// <summary>
/// If true, SSL will be used to connect.
/// </summary>
public bool UseSSL { get; private set; }
/// <summary>
/// If true, invalid SSL certificates are ignored.
/// </summary>
public bool IgnoreInvalidSSL { get; set; }
/// <summary>
/// The character encoding to use for the connection. Defaults to UTF-8.
/// </summary>
/// <value>The encoding.</value>
public Encoding Encoding { get; set; }
/// <summary>
/// The user this client is logged in as.
/// </summary>
/// <value>The user.</value>
public IrcUser User { get; set; }
/// <summary>
/// The channels this user is joined to.
/// </summary>
public ChannelCollection Channels { get; private set; }
/// <summary>
/// Settings that control the behavior of ChatSharp.
/// </summary>
public ClientSettings Settings { get; set; }
/// <summary>
/// Information about the server we are connected to. Servers may not send us this information,
/// but it's required for ChatSharp to function, so by default this is a guess. Handle
/// IrcClient.ServerInfoRecieved if you'd like to know when it's populated with real information.
/// </summary>
public ServerInfo ServerInfo { get; set; }
/// <summary>
/// A string to prepend to all PRIVMSGs sent. Many IRC bots prefix their messages with \u200B, to
/// indicate to other bots that you are a bot.
/// </summary>
public string PrivmsgPrefix { get; set; }
/// <summary>
/// A list of users on this network that we are aware of.
/// </summary>
public UserPool Users { get; set; }
/// <summary>
/// Creates a new IRC client, but will not connect until ConnectAsync is called.
/// </summary>
/// <param name="serverAddress">Server address including port in the form of "hostname:port".</param>
/// <param name="user">The IRC user to connect as.</param>
/// <param name="useSSL">Connect with SSL if true.</param>
public IrcClient( string serverAddress, IrcUser user, bool useSSL = false )
{
if ( serverAddress == null ) throw new ArgumentNullException( "serverAddress" );
if ( user == null ) throw new ArgumentNullException( "user" );
User = user;
ServerAddress = serverAddress;
Encoding = Encoding.UTF8;
Channels = new ChannelCollection( this );
Settings = new ClientSettings();
Handlers = new Dictionary<string, MessageHandler>();
MessageHandlers.RegisterDefaultHandlers( this );
RequestManager = new RequestManager();
UseSSL = useSSL;
WriteQueue = new ConcurrentQueue<string>();
ServerInfo = new ServerInfo();
PrivmsgPrefix = "";
Users = new UserPool();
Users.Add( User ); // Add self to user pool
this.ConnectCompleted = false;
}
/// <summary>
/// Connects to the IRC server.
/// </summary>
public void ConnectAsync()
{
if ( Socket != null && Socket.Connected ) throw new InvalidOperationException( "Socket is already connected to server." );
Socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
ReadBuffer = new byte[ ReadBufferLength ];
ReadBufferIndex = 0;
PingTimer = new Timer( 30000 );
PingTimer.Elapsed += ( sender, e ) =>
{
if ( !string.IsNullOrEmpty( ServerNameFromPing ) )
SendRawMessage( "PING :{0}", ServerNameFromPing );
};
var checkQueue = new Timer( 1000 );
checkQueue.Elapsed += ( sender, e ) =>
{
string nextMessage;
if ( WriteQueue.Count > 0 )
{
while ( !WriteQueue.TryDequeue( out nextMessage ) ) ;
SendRawMessage( nextMessage );
}
};
checkQueue.Start();
Socket.BeginConnect( ServerHostname, ServerPort, ConnectComplete, null );
}
/// <summary>
/// Send a QUIT message and disconnect.
/// </summary>
public void Quit()
{
Quit( null );
}
/// <summary>
/// Send a QUIT message with a reason and disconnect.
/// </summary>
public void Quit( string reason )
{
if ( reason == null )
SendRawMessage( "QUIT" );
else
SendRawMessage( "QUIT :{0}", reason );
Socket.BeginDisconnect( false, ar =>
{
Socket.EndDisconnect( ar );
NetworkStream.Dispose();
NetworkStream = null;
}, null );
PingTimer.Dispose();
}
private void ConnectComplete( IAsyncResult result )
{
if ( this.Connected )
{
SocketError socketError = SocketError.Success;
try
{
Socket.EndConnect( result );
NetworkStream = new NetworkStream( Socket );
if ( UseSSL )
{
if ( IgnoreInvalidSSL )
NetworkStream = new SslStream( NetworkStream, false, ( sender, certificate, chain, policyErrors ) => true );
else
NetworkStream = new SslStream( NetworkStream );
( ( SslStream )NetworkStream ).AuthenticateAsClient( ServerHostname );
}
NetworkStream.BeginRead( ReadBuffer, ReadBufferIndex, ReadBuffer.Length, DataRecieved, null );
}
catch ( Exception ex )
{
if ( this.SocketConnectionError == null )
{
throw ex;
}
this.OnSocketConnectionError( new SocketUnhandledExceptionEventArgs( ex ) );
return;
}
// Write login info
if ( !string.IsNullOrEmpty( User.Password ) )
SendRawMessage( "PASS {0}", User.Password );
SendRawMessage( "NICK {0}", User.Nick );
// hostname, servername are ignored by most IRC servers
SendRawMessage( "USER {0} hostname servername :{1}", User.User, User.RealName );
PingTimer.Start();
}
this.ConnectCompleted = true;
}
private void DataRecieved( IAsyncResult result )
{
SocketError socketError;
if ( NetworkStream == null )
{
OnNetworkError( new SocketErrorEventArgs( SocketError.NotConnected ) );
return;
}
int length;
try
{
length = NetworkStream.EndRead( result ) + ReadBufferIndex;
}
catch ( IOException e )
{
var socketException = e.InnerException as SocketException;
if ( socketException != null )
OnNetworkError( new SocketErrorEventArgs( socketException.SocketErrorCode ) );
else
throw;
return;
}
ReadBufferIndex = 0;
while ( length > 0 )
{
int messageLength = Array.IndexOf( ReadBuffer, ( byte )'\n', 0, length );
if ( messageLength == -1 ) // Incomplete message
{
ReadBufferIndex = length;
break;
}
messageLength++;
var message = Encoding.GetString( ReadBuffer, 0, messageLength - 2 ); // -2 to remove \r\n
HandleMessage( message );
Array.Copy( ReadBuffer, messageLength, ReadBuffer, 0, length - messageLength );
length -= messageLength;
}
try
{
NetworkStream.BeginRead( ReadBuffer, ReadBufferIndex, ReadBuffer.Length - ReadBufferIndex, DataRecieved, null );
}
catch ( Exception ex )
{
if ( this.SocketConnectionError == null )
{
throw ex;
}
this.OnSocketConnectionError( new SocketUnhandledExceptionEventArgs( ex ) );
return;
}
}
private void HandleMessage( string rawMessage )
{
OnRawMessageRecieved( new RawMessageEventArgs( rawMessage, false ) );
var message = new IrcMessage( rawMessage );
if ( Handlers.ContainsKey( message.Command.ToUpper() ) )
Handlers[ message.Command.ToUpper() ]( this, message );
else
{
// TODO: Fire an event or something
}
}
public void SendActionMessage( string action, params string[] destinations )
{
this.SendMessage( string.Format( "\u0001ACTION {0} \u0001", action ), destinations );
}
/// <summary>
/// Send a raw IRC message. Behaves like /quote in most IRC clients.
/// </summary>
public void SendRawMessage( string message, params object[] format )
{
if ( NetworkStream == null )
{
OnNetworkError( new SocketErrorEventArgs( SocketError.NotConnected ) );
return;
}
message = string.Format( message, format );
var data = Encoding.GetBytes( message + "\r\n" );
try
{
if ( !IsWriting )
{
IsWriting = true;
NetworkStream.BeginWrite( data, 0, data.Length, MessageSent, message );
}
else
{
WriteQueue.Enqueue( message );
}
}
catch ( Exception ex )
{
if ( this.SocketConnectionError == null )
{
throw ex;
}
this.OnSocketConnectionError( new SocketUnhandledExceptionEventArgs( ex ) );
}
}
/// <summary>
/// Send a raw IRC message. Behaves like /quote in most IRC clients.
/// </summary>
public void SendIrcMessage( IrcMessage message )
{
SendRawMessage( message.RawMessage );
}
private void MessageSent( IAsyncResult result )
{
if ( NetworkStream == null )
{
OnNetworkError( new SocketErrorEventArgs( SocketError.NotConnected ) );
IsWriting = false;
return;
}
try
{
NetworkStream.EndWrite( result );
}
catch ( IOException e )
{
var socketException = e.InnerException as SocketException;
if ( socketException != null )
OnNetworkError( new SocketErrorEventArgs( socketException.SocketErrorCode ) );
else
throw;
return;
}
finally
{
IsWriting = false;
}
OnRawMessageSent( new RawMessageEventArgs( ( string )result.AsyncState, true ) );
string nextMessage;
if ( WriteQueue.Count > 0 )
{
while ( !WriteQueue.TryDequeue( out nextMessage ) ) ;
SendRawMessage( nextMessage );
}
}
/// <summary>
/// Raised for socket errors. ChatSharp does not automatically reconnect.
/// </summary>
public event EventHandler<SocketErrorEventArgs> NetworkError;
internal void OnNetworkError( SocketErrorEventArgs e )
{
if ( NetworkError != null ) NetworkError( this, e );
}
/// <summary>
/// Occurs when a raw message is sent.
/// </summary>
public event EventHandler<RawMessageEventArgs> RawMessageSent;
internal void OnRawMessageSent( RawMessageEventArgs e )
{
if ( RawMessageSent != null ) RawMessageSent( this, e );
}
/// <summary>
/// Occurs when a raw message recieved.
/// </summary>
public event EventHandler<RawMessageEventArgs> RawMessageRecieved;
internal void OnRawMessageRecieved( RawMessageEventArgs e )
{
if ( RawMessageRecieved != null ) RawMessageRecieved( this, e );
}
/// <summary>
/// Occurs when a notice recieved.
/// </summary>
public event EventHandler<IrcNoticeEventArgs> NoticeRecieved;
internal void OnNoticeRecieved( IrcNoticeEventArgs e )
{
if ( NoticeRecieved != null ) NoticeRecieved( this, e );
}
/// <summary>
/// Occurs when the server has sent us part of the MOTD.
/// </summary>
public event EventHandler<ServerMOTDEventArgs> MOTDPartRecieved;
internal void OnMOTDPartRecieved( ServerMOTDEventArgs e )
{
if ( MOTDPartRecieved != null ) MOTDPartRecieved( this, e );
}
/// <summary>
/// Occurs when the entire server MOTD has been recieved.
/// </summary>
public event EventHandler<ServerMOTDEventArgs> MOTDRecieved;
internal void OnMOTDRecieved( ServerMOTDEventArgs e )
{
if ( MOTDRecieved != null ) MOTDRecieved( this, e );
}
/// <summary>
/// Occurs when a private message recieved. This can be a channel OR a user message.
/// </summary>
public event EventHandler<PrivateMessageEventArgs> PrivateMessageRecieved;
internal void OnPrivateMessageRecieved( PrivateMessageEventArgs e )
{
if ( PrivateMessageRecieved != null ) PrivateMessageRecieved( this, e );
}
/// <summary>
/// Occurs when a message is recieved in an IRC channel.
/// </summary>
public event EventHandler<PrivateMessageEventArgs> ChannelMessageRecieved;
internal void OnChannelMessageRecieved( PrivateMessageEventArgs e )
{
if ( ChannelMessageRecieved != null ) ChannelMessageRecieved( this, e );
}
/// <summary>
/// Occurs when a message is recieved from a user.
/// </summary>
public event EventHandler<PrivateMessageEventArgs> UserMessageRecieved;
internal void OnUserMessageRecieved( PrivateMessageEventArgs e )
{
if ( UserMessageRecieved != null ) UserMessageRecieved( this, e );
}
/// <summary>
/// Raised if the nick you've chosen is in use. By default, ChatSharp will pick a
/// random nick to use instead. Set ErronousNickEventArgs.DoNotHandle to prevent this.
/// </summary>
public event EventHandler<ErronousNickEventArgs> NickInUse;
internal void OnNickInUse( ErronousNickEventArgs e )
{
if ( NickInUse != null ) NickInUse( this, e );
}
/// <summary>
/// Occurs when a user or channel mode is changed.
/// </summary>
public event EventHandler<ModeChangeEventArgs> ModeChanged;
internal void OnModeChanged( ModeChangeEventArgs e )
{
if ( ModeChanged != null ) ModeChanged( this, e );
}
/// <summary>
/// Occurs when a user joins a channel.
/// </summary>
public event EventHandler<ChannelUserEventArgs> UserJoinedChannel;
internal void OnUserJoinedChannel( ChannelUserEventArgs e )
{
if ( UserJoinedChannel != null ) UserJoinedChannel( this, e );
}
/// <summary>
/// Occurs when a user parts a channel.
/// </summary>
public event EventHandler<ChannelUserEventArgs> UserPartedChannel;
internal void OnUserPartedChannel( ChannelUserEventArgs e )
{
if ( UserPartedChannel != null ) UserPartedChannel( this, e );
}
/// <summary>
/// Occurs when we have received the list of users present in a channel.
/// </summary>
public event EventHandler<ChannelEventArgs> ChannelListRecieved;
internal void OnChannelListRecieved( ChannelEventArgs e )
{
if ( ChannelListRecieved != null ) ChannelListRecieved( this, e );
}
/// <summary>
/// Occurs when we have received the topic of a channel.
/// </summary>
public event EventHandler<ChannelTopicEventArgs> ChannelTopicReceived;
internal void OnChannelTopicReceived( ChannelTopicEventArgs e )
{
if ( ChannelTopicReceived != null ) ChannelTopicReceived( this, e );
}
/// <summary>
/// Occurs when the IRC connection is established and it is safe to begin interacting with the server.
/// </summary>
public event EventHandler<EventArgs> ConnectionComplete;
internal void OnConnectionComplete( EventArgs e )
{
if ( ConnectionComplete != null ) ConnectionComplete( this, e );
}
/// <summary>
/// Occurs when we receive server info (such as max nick length).
/// </summary>
public event EventHandler<SupportsEventArgs> ServerInfoRecieved;
internal void OnServerInfoRecieved( SupportsEventArgs e )
{
if ( ServerInfoRecieved != null ) ServerInfoRecieved( this, e );
}
/// <summary>
/// Occurs when a user is kicked.
/// </summary>
public event EventHandler<KickEventArgs> UserKicked;
internal void OnUserKicked( KickEventArgs e )
{
if ( UserKicked != null ) UserKicked( this, e );
}
/// <summary>
/// Occurs when a WHOIS response is received.
/// </summary>
public event EventHandler<WhoIsReceivedEventArgs> WhoIsReceived;
internal void OnWhoIsReceived( WhoIsReceivedEventArgs e )
{
if ( WhoIsReceived != null ) WhoIsReceived( this, e );
}
/// <summary>
/// Occurs when a user has changed their nick.
/// </summary>
public event EventHandler<NickChangedEventArgs> NickChanged;
internal void OnNickChanged( NickChangedEventArgs e )
{
if ( NickChanged != null ) NickChanged( this, e );
}
/// <summary>
/// Occurs when a user has quit.
/// </summary>
public event EventHandler<UserEventArgs> UserQuit;
internal void OnUserQuit( UserEventArgs e )
{
if ( UserQuit != null ) UserQuit( this, e );
}
public event EventHandler<SocketUnhandledExceptionEventArgs> SocketConnectionError;
/// <summary>
/// Occurs when error occurred
/// </summary>
/// <param name="e">The <see cref="SocketUnhandledExceptionEventArgs"/> instance containing the event data.</param>
internal void OnSocketConnectionError( SocketUnhandledExceptionEventArgs e )
{
if ( this.SocketConnectionError == null )
{
throw e.ExceptionObject;
}
this.SocketConnectionError( this, e );
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using i64 = System.Int64;
using u8 = System.Byte;
using u32 = System.UInt32;
using Pgno = System.UInt32;
namespace System.Data.SQLite
{
using sqlite3_int64 = System.Int64;
using DbPage = Sqlite3.PgHdr;
public partial class Sqlite3
{
/*
** 2009 January 28
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the implementation of the sqlite3_backup_XXX()
** API functions and the related features.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include "btreeInt.h"
/* Macro to find the minimum of two numeric values.
*/
#if !MIN
//# define MIN(x,y) ((x)<(y)?(x):(y))
#endif
/*
** Structure allocated for each backup operation.
*/
public class sqlite3_backup
{
/// <summary>
/// Destination database handle
/// </summary>
public sqlite3 pDestDb;
/// <summary>
/// The destination b-tree file.
/// </summary>
public Btree pDest;
/// <summary>
/// Original schema cookie in destination.
/// </summary>
public u32 iDestSchema;
/// <summary>
/// true one a write-transation is open on <see cref="pDestDb"/>
/// </summary>
public int bDestLocked;
/// <summary>
/// Page number of the next source page to copy.
/// </summary>
public Pgno iNext;
/// <summary>
/// Source database handle
/// </summary>
public sqlite3 pSrcDb;
/// <summary>
/// Source b-tree file.
/// </summary>
public Btree pSrc;
/// <summary>
/// Backup process error code.
/// </summary>
public int rc;
/* These two variables are set by every call to backup_step(). They are
** read by calls to backup_remaining() and backup_pagecount().
*/
/// <summary>
/// The number of pages left to copy
/// </summary>
public Pgno nRemaining;
/// <summary>
/// total number of pages to copy.
/// </summary>
public Pgno nPagecount;
/// <summary>
/// True once backup has been registered wiht pager
/// </summary>
public int isAttached;
/// <summary>
/// Next backup associated with source pager
/// </summary>
public sqlite3_backup pNext;
};
/*
** THREAD SAFETY NOTES:
**
** Once it has been created using backup_init(), a single sqlite3_backup
** structure may be accessed via two groups of thread-safe entry points:
**
** * Via the sqlite3_backup_XXX() API function backup_step() and
** backup_finish(). Both these functions obtain the source database
** handle mutex and the mutex associated with the source BtShared
** structure, in that order.
**
** * Via the BackupUpdate() and BackupRestart() functions, which are
** invoked by the pager layer to report various state changes in
** the page cache associated with the source database. The mutex
** associated with the source database BtShared structure will always
** be held when either of these functions are invoked.
**
** The other sqlite3_backup_XXX() API functions, backup_remaining() and
** backup_pagecount() are not thread-safe functions. If they are called
** while some other thread is calling backup_step() or backup_finish(),
** the values returned may be invalid. There is no way for a call to
** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
** or backup_pagecount().
**
** Depending on the SQLite configuration, the database handles and/or
** the Btree objects may have their own mutexes that require locking.
** Non-sharable Btrees (in-memory databases for example), do not have
** associated mutexes.
*/
/// <summary>
/// Return a pointer corresponding to database zDb (i.e. "main", "temp")
/// in connection handle pDb. If such a database cannot be found, return
/// a NULL pointer and write an error message to pErrorDb.
///
/// If the "temp" database is requested, it may need to be opened by this
/// function. If an error occurs while doing so, return 0 and write an
/// error message to pErrorDb.
/// </summary>
static Btree findBtree(sqlite3 pErrorDb, sqlite3 pDb, string zDb)
{
int i = sqlite3FindDbName(pDb, zDb);
if (i == 1)
{
Parse pParse;
int rc = 0;
pParse = new Parse();//sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
if (pParse == null)
{
sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
rc = SQLITE_NOMEM;
}
else
{
pParse.db = pDb;
if (sqlite3OpenTempDatabase(pParse) != 0)
{
sqlite3Error(pErrorDb, pParse.rc, "%s", pParse.zErrMsg);
rc = SQLITE_ERROR;
}
sqlite3DbFree(pErrorDb, ref pParse.zErrMsg);
//sqlite3StackFree( pErrorDb, pParse );
}
if (rc != 0)
{
return null;
}
}
if (i < 0)
{
sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
return null;
}
return pDb.aDb[i].pBt;
}
/// <summary>
/// Attempt to set the page size of the destination to match the page size
/// of the source.
/// </summary>
static int setDestPgsz(sqlite3_backup p)
{
int rc;
rc = sqlite3BtreeSetPageSize(p.pDest, sqlite3BtreeGetPageSize(p.pSrc), -1, 0);
return rc;
}
/// <summary>
/// Create an sqlite3_backup process to copy the contents of zSrcDb from
/// connection handle pSrcDb to zDestDb in pDestDb. If successful, return
/// a pointer to the new sqlite3_backup object.
///
/// If an error occurs, NULL is returned and an error code and error message
/// stored in database handle pDestDb.
/// </summary>
/// <param name='pDestDb'>
/// Database to write to
/// </param>
/// <param name='zDestDb'>
/// Name of database within <see cref="pDestDb"/>
/// </param>
/// <param name='pSrcDb'>
/// Database connection to read from
/// </param>
/// <param name='zSrcDb'>
/// Name of database within <see cref="pSrcDb"/>
/// </param>
static public sqlite3_backup sqlite3_backup_init(sqlite3 pDestDb, string zDestDb, sqlite3 pSrcDb, string zSrcDb)
{
sqlite3_backup p; /* Value to return */
/* Lock the source database handle. The destination database
** handle is not locked in this routine, but it is locked in
** sqlite3_backup_step(). The user is required to ensure that no
** other thread accesses the destination handle for the duration
** of the backup operation. Any attempt to use the destination
** database connection while a backup is in progress may cause
** a malfunction or a deadlock.
*/
sqlite3_mutex_enter(pSrcDb.mutex);
sqlite3_mutex_enter(pDestDb.mutex);
if (pSrcDb == pDestDb)
{
sqlite3Error(
pDestDb, SQLITE_ERROR, "source and destination must be distinct"
);
p = null;
}
else
{
/* Allocate space for a new sqlite3_backup object...
** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
** call to sqlite3_backup_init() and is destroyed by a call to
** sqlite3_backup_finish(). */
p = new sqlite3_backup();// (sqlite3_backup)sqlite3_malloc( sizeof( sqlite3_backup ) );
//if ( null == p )
//{
// sqlite3Error( pDestDb, SQLITE_NOMEM, 0 );
//}
}
/* If the allocation succeeded, populate the new object. */
if (p != null)
{
// memset( p, 0, sizeof( sqlite3_backup ) );
p.pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
p.pDest = findBtree(pDestDb, pDestDb, zDestDb);
p.pDestDb = pDestDb;
p.pSrcDb = pSrcDb;
p.iNext = 1;
p.isAttached = 0;
if (null == p.pSrc || null == p.pDest || setDestPgsz(p) == SQLITE_NOMEM)
{
/* One (or both) of the named databases did not exist or an OOM
** error was hit. The error has already been written into the
** pDestDb handle. All that is left to do here is free the
** sqlite3_backup structure.
*/
//sqlite3_free( ref p );
p = null;
}
}
if (p != null)
{
p.pSrc.nBackup++;
}
sqlite3_mutex_leave(pDestDb.mutex);
sqlite3_mutex_leave(pSrcDb.mutex);
return p;
}
/// <summary>
/// Argument rc is an SQLite error code. Return true if this error is
/// considered fatal if encountered during a backup operation. All errors
/// are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
/// </summary>
static bool isFatalError(int rc)
{
return (rc != SQLITE_OK && rc != SQLITE_BUSY && ALWAYS(rc != SQLITE_LOCKED));
}
/// <summary>
/// Parameter zSrcData points to a buffer containing the data for
/// page iSrcPg from the source database. Copy this data into the
/// destination database.
/// </summary>
static int backupOnePage(sqlite3_backup p, Pgno iSrcPg, byte[] zSrcData)
{
Pager pDestPager = sqlite3BtreePager(p.pDest);
int nSrcPgsz = sqlite3BtreeGetPageSize(p.pSrc);
int nDestPgsz = sqlite3BtreeGetPageSize(p.pDest);
int nCopy = MIN(nSrcPgsz, nDestPgsz);
i64 iEnd = (i64)iSrcPg * (i64)nSrcPgsz;
#if SQLITE_HAS_CODEC
int nSrcReserve = sqlite3BtreeGetReserve(p.pSrc);
int nDestReserve = sqlite3BtreeGetReserve(p.pDest);
#endif
int rc = SQLITE_OK;
i64 iOff;
Debug.Assert(p.bDestLocked != 0);
Debug.Assert(!isFatalError(p.rc));
Debug.Assert(iSrcPg != PENDING_BYTE_PAGE(p.pSrc.pBt));
Debug.Assert(zSrcData != null);
/* Catch the case where the destination is an in-memory database and the
** page sizes of the source and destination differ.
*/
if (nSrcPgsz != nDestPgsz && sqlite3PagerIsMemdb(pDestPager))
{
rc = SQLITE_READONLY;
}
#if SQLITE_HAS_CODEC
/* Backup is not possible if the page size of the destination is changing
** and a codec is in use.
*/
if ( nSrcPgsz != nDestPgsz && sqlite3PagerGetCodec( pDestPager ) != null )
{
rc = SQLITE_READONLY;
}
/* Backup is not possible if the number of bytes of reserve space differ
** between source and destination. If there is a difference, try to
** fix the destination to agree with the source. If that is not possible,
** then the backup cannot proceed.
*/
if ( nSrcReserve != nDestReserve )
{
u32 newPgsz = (u32)nSrcPgsz;
rc = sqlite3PagerSetPagesize( pDestPager, ref newPgsz, nSrcReserve );
if ( rc == SQLITE_OK && newPgsz != nSrcPgsz )
rc = SQLITE_READONLY;
}
#endif
/* This loop runs once for each destination page spanned by the source
** page. For each iteration, variable iOff is set to the byte offset
** of the destination page.
*/
for (iOff = iEnd - (i64)nSrcPgsz; rc == SQLITE_OK && iOff < iEnd; iOff += nDestPgsz)
{
DbPage pDestPg = null;
u32 iDest = (u32)(iOff / nDestPgsz) + 1;
if (iDest == PENDING_BYTE_PAGE(p.pDest.pBt))
continue;
if (SQLITE_OK == (rc = sqlite3PagerGet(pDestPager, iDest, ref pDestPg))
&& SQLITE_OK == (rc = sqlite3PagerWrite(pDestPg))
)
{
//string zIn = &zSrcData[iOff%nSrcPgsz];
byte[] zDestData = sqlite3PagerGetData(pDestPg);
//string zOut = &zDestData[iOff % nDestPgsz];
/* Copy the data from the source page into the destination page.
** Then clear the Btree layer MemPage.isInit flag. Both this module
** and the pager code use this trick (clearing the first byte
** of the page 'extra' space to invalidate the Btree layers
** cached parse of the page). MemPage.isInit is marked
** "MUST BE FIRST" for this purpose.
*/
Buffer.BlockCopy(zSrcData, (int)(iOff % nSrcPgsz), zDestData, (int)(iOff % nDestPgsz), nCopy);// memcpy( zOut, zIn, nCopy );
sqlite3PagerGetExtra(pDestPg).isInit = 0;// ( sqlite3PagerGetExtra( pDestPg ) )[0] = 0;
}
sqlite3PagerUnref(pDestPg);
}
return rc;
}
/// <summary>
/// If pFile is currently larger than iSize bytes, then truncate it to
/// exactly iSize bytes. If pFile is not larger than iSize bytes, then
/// this function is a no-op.
///
/// Return SQLITE_OK if everything is successful, or an SQLite error
/// code if an error occurs.
/// </summary>
static int backupTruncateFile(sqlite3_file pFile, int iSize)
{
long iCurrent = 0;
int rc = sqlite3OsFileSize(pFile, ref iCurrent);
if (rc == SQLITE_OK && iCurrent > iSize)
{
rc = sqlite3OsTruncate(pFile, iSize);
}
return rc;
}
/// <summary>
/// Register this backup object with the associated source pager for
/// callbacks when pages are changed or the cache invalidated.
/// </summary>
static void attachBackupObject(sqlite3_backup p)
{
sqlite3_backup pp;
Debug.Assert(sqlite3BtreeHoldsMutex(p.pSrc));
pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p.pSrc));
p.pNext = pp;
sqlite3BtreePager(p.pSrc).pBackup = p; //*pp = p;
p.isAttached = 1;
}
/// <summary>
/// Copy nPage pages from the source b-tree to the destination.
/// </summary>
static public int sqlite3_backup_step(sqlite3_backup p, int nPage)
{
int rc;
int destMode; /* Destination journal mode */
int pgszSrc = 0; /* Source page size */
int pgszDest = 0; /* Destination page size */
sqlite3_mutex_enter(p.pSrcDb.mutex);
sqlite3BtreeEnter(p.pSrc);
if (p.pDestDb != null)
{
sqlite3_mutex_enter(p.pDestDb.mutex);
}
rc = p.rc;
if (!isFatalError(rc))
{
Pager pSrcPager = sqlite3BtreePager(p.pSrc); /* Source pager */
Pager pDestPager = sqlite3BtreePager(p.pDest); /* Dest pager */
int ii; /* Iterator variable */
Pgno nSrcPage = 0; /* Size of source db in pages */
int bCloseTrans = 0; /* True if src db requires unlocking */
/* If the source pager is currently in a write-transaction, return
** SQLITE_BUSY immediately.
*/
if (p.pDestDb != null && p.pSrc.pBt.inTransaction == TRANS_WRITE)
{
rc = SQLITE_BUSY;
}
else
{
rc = SQLITE_OK;
}
/* Lock the destination database, if it is not locked already. */
if (SQLITE_OK == rc && p.bDestLocked == 0
&& SQLITE_OK == (rc = sqlite3BtreeBeginTrans(p.pDest, 2))
)
{
p.bDestLocked = 1;
sqlite3BtreeGetMeta(p.pDest, BTREE_SCHEMA_VERSION, ref p.iDestSchema);
}
/* If there is no open read-transaction on the source database, open
** one now. If a transaction is opened here, then it will be closed
** before this function exits.
*/
if (rc == SQLITE_OK && !sqlite3BtreeIsInReadTrans(p.pSrc))
{
rc = sqlite3BtreeBeginTrans(p.pSrc, 0);
bCloseTrans = 1;
}
/* Do not allow backup if the destination database is in WAL mode
** and the page sizes are different between source and destination */
pgszSrc = sqlite3BtreeGetPageSize(p.pSrc);
pgszDest = sqlite3BtreeGetPageSize(p.pDest);
destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p.pDest));
if (SQLITE_OK == rc && destMode == PAGER_JOURNALMODE_WAL && pgszSrc != pgszDest)
{
rc = SQLITE_READONLY;
}
/* Now that there is a read-lock on the source database, query the
** source pager for the number of pages in the database.
*/
nSrcPage = sqlite3BtreeLastPage(p.pSrc);
Debug.Assert(nSrcPage >= 0);
for (ii = 0; (nPage < 0 || ii < nPage) && p.iNext <= nSrcPage && 0 == rc; ii++)
{
Pgno iSrcPg = p.iNext; /* Source page number */
if (iSrcPg != PENDING_BYTE_PAGE(p.pSrc.pBt))
{
DbPage pSrcPg = null; /* Source page object */
rc = sqlite3PagerGet(pSrcPager, (u32)iSrcPg, ref pSrcPg);
if (rc == SQLITE_OK)
{
rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
sqlite3PagerUnref(pSrcPg);
}
}
p.iNext++;
}
if (rc == SQLITE_OK)
{
p.nPagecount = nSrcPage;
p.nRemaining = (nSrcPage + 1 - p.iNext);
if (p.iNext > nSrcPage)
{
rc = SQLITE_DONE;
}
else if (0 == p.isAttached)
{
attachBackupObject(p);
}
}
/* Update the schema version field in the destination database. This
** is to make sure that the schema-version really does change in
** the case where the source and destination databases have the
** same schema version.
*/
if (rc == SQLITE_DONE
&& (rc = sqlite3BtreeUpdateMeta(p.pDest, 1, p.iDestSchema + 1)) == SQLITE_OK
)
{
Pgno nDestTruncate;
if (p.pDestDb != null)
{
sqlite3ResetInternalSchema(p.pDestDb, -1);
}
/* Set nDestTruncate to the final number of pages in the destination
** database. The complication here is that the destination page
** size may be different to the source page size.
**
** If the source page size is smaller than the destination page size,
** round up. In this case the call to sqlite3OsTruncate() below will
** fix the size of the file. However it is important to call
** sqlite3PagerTruncateImage() here so that any pages in the
** destination file that lie beyond the nDestTruncate page mark are
** journalled by PagerCommitPhaseOne() before they are destroyed
** by the file truncation.
*/
Debug.Assert(pgszSrc == sqlite3BtreeGetPageSize(p.pSrc));
Debug.Assert(pgszDest == sqlite3BtreeGetPageSize(p.pDest));
if (pgszSrc < pgszDest)
{
int ratio = pgszDest / pgszSrc;
nDestTruncate = (Pgno)((nSrcPage + ratio - 1) / ratio);
if (nDestTruncate == (int)PENDING_BYTE_PAGE(p.pDest.pBt))
{
nDestTruncate--;
}
}
else
{
nDestTruncate = (Pgno)(nSrcPage * (pgszSrc / pgszDest));
}
sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
if (pgszSrc < pgszDest)
{
/* If the source page-size is smaller than the destination page-size,
** two extra things may need to happen:
**
** * The destination may need to be truncated, and
**
** * Data stored on the pages immediately following the
** pending-byte page in the source database may need to be
** copied into the destination database.
*/
int iSize = (int)(pgszSrc * nSrcPage);
sqlite3_file pFile = sqlite3PagerFile(pDestPager);
i64 iOff;
i64 iEnd;
Debug.Assert(pFile != null);
Debug.Assert((i64)nDestTruncate * (i64)pgszDest >= iSize || (
nDestTruncate == (int)(PENDING_BYTE_PAGE(p.pDest.pBt) - 1)
&& iSize >= PENDING_BYTE && iSize <= PENDING_BYTE + pgszDest
));
/* This call ensures that all data required to recreate the original
** database has been stored in the journal for pDestPager and the
** journal synced to disk. So at this point we may safely modify
** the database file in any way, knowing that if a power failure
** occurs, the original database will be reconstructed from the
** journal file. */
rc = sqlite3PagerCommitPhaseOne(pDestPager, null, true);
/* Write the extra pages and truncate the database file as required. */
iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
for (
iOff = PENDING_BYTE + pgszSrc;
rc == SQLITE_OK && iOff < iEnd;
iOff += pgszSrc
)
{
PgHdr pSrcPg = null;
u32 iSrcPg = (u32)((iOff / pgszSrc) + 1);
rc = sqlite3PagerGet(pSrcPager, iSrcPg, ref pSrcPg);
if (rc == SQLITE_OK)
{
byte[] zData = sqlite3PagerGetData(pSrcPg);
rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
}
sqlite3PagerUnref(pSrcPg);
}
if (rc == SQLITE_OK)
{
rc = backupTruncateFile(pFile, (int)iSize);
}
/* Sync the database file to disk. */
if (rc == SQLITE_OK)
{
rc = sqlite3PagerSync(pDestPager);
}
}
else
{
rc = sqlite3PagerCommitPhaseOne(pDestPager, null, false);
}
/* Finish committing the transaction to the destination database. */
if (SQLITE_OK == rc
&& SQLITE_OK == (rc = sqlite3BtreeCommitPhaseTwo(p.pDest, 0))
)
{
rc = SQLITE_DONE;
}
}
/* If bCloseTrans is true, then this function opened a read transaction
** on the source database. Close the read transaction here. There is
** no need to check the return values of the btree methods here, as
** "committing" a read-only transaction cannot fail.
*/
if (bCloseTrans != 0)
{
#if !NDEBUG || SQLITE_COVERAGE_TEST
//TESTONLY( int rc2 );
//TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p.pSrc, 0);
//TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p.pSrc);
int rc2;
rc2 = sqlite3BtreeCommitPhaseOne( p.pSrc, "" );
rc2 |= sqlite3BtreeCommitPhaseTwo( p.pSrc, 0 );
Debug.Assert( rc2 == SQLITE_OK );
#else
sqlite3BtreeCommitPhaseOne(p.pSrc, null);
sqlite3BtreeCommitPhaseTwo(p.pSrc, 0);
#endif
}
if (rc == SQLITE_IOERR_NOMEM)
{
rc = SQLITE_NOMEM;
}
p.rc = rc;
}
if (p.pDestDb != null)
{
sqlite3_mutex_leave(p.pDestDb.mutex);
}
sqlite3BtreeLeave(p.pSrc);
sqlite3_mutex_leave(p.pSrcDb.mutex);
return rc;
}
/// <summary>
/// Release all resources associated with an sqlite3_backup* handle.
/// </summary>
static public int sqlite3_backup_finish(sqlite3_backup p)
{
sqlite3_backup pp; /* Ptr to head of pagers backup list */
sqlite3_mutex mutex; /* Mutex to protect source database */
int rc; /* Value to return */
/* Enter the mutexes */
if (p == null)
return SQLITE_OK;
sqlite3_mutex_enter(p.pSrcDb.mutex);
sqlite3BtreeEnter(p.pSrc);
mutex = p.pSrcDb.mutex;
if (p.pDestDb != null)
{
sqlite3_mutex_enter(p.pDestDb.mutex);
}
/* Detach this backup from the source pager. */
if (p.pDestDb != null)
{
p.pSrc.nBackup--;
}
if (p.isAttached != 0)
{
pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p.pSrc));
while (pp != p)
{
pp = (pp).pNext;
}
sqlite3BtreePager(p.pSrc).pBackup = p.pNext;
}
/* If a transaction is still open on the Btree, roll it back. */
sqlite3BtreeRollback(p.pDest);
/* Set the error code of the destination database handle. */
rc = (p.rc == SQLITE_DONE) ? SQLITE_OK : p.rc;
sqlite3Error(p.pDestDb, rc, 0);
/* Exit the mutexes and free the backup context structure. */
if (p.pDestDb != null)
{
sqlite3_mutex_leave(p.pDestDb.mutex);
}
sqlite3BtreeLeave(p.pSrc);
if (p.pDestDb != null)
{
/* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
** call to sqlite3_backup_init() and is destroyed by a call to
** sqlite3_backup_finish(). */
//sqlite3_free( ref p );
}
sqlite3_mutex_leave(mutex);
return rc;
}
/// <summary>
/// Return the number of pages still to be backed up as of the most recent
/// call to sqlite3_backup_step().
/// </summary>
static int sqlite3_backup_remaining(sqlite3_backup p)
{
return (int)p.nRemaining;
}
/// <summary>
/// Return the total number of pages in the source database as of the most
/// recent call to sqlite3_backup_step().
/// </summary>
static int sqlite3_backup_pagecount(sqlite3_backup p)
{
return (int)p.nPagecount;
}
/// <summary>
/// This function is called after the contents of page iPage of the
/// source database have been modified. If page iPage has already been
/// copied into the destination database, then the data written to the
/// destination is now invalidated. The destination copy of iPage needs
/// to be updated with the new data before the backup operation is
/// complete.
///
/// It is assumed that the mutex associated with the BtShared object
/// corresponding to the source database is held when this function is
/// called.
/// </summary>
static void sqlite3BackupUpdate(sqlite3_backup pBackup, Pgno iPage, byte[] aData)
{
sqlite3_backup p; /* Iterator variable */
for (p = pBackup; p != null; p = p.pNext)
{
Debug.Assert(sqlite3_mutex_held(p.pSrc.pBt.mutex));
if (!isFatalError(p.rc) && iPage < p.iNext)
{
/* The backup process p has already copied page iPage. But now it
** has been modified by a transaction on the source pager. Copy
** the new data into the backup.
*/
int rc;
Debug.Assert(p.pDestDb != null);
sqlite3_mutex_enter(p.pDestDb.mutex);
rc = backupOnePage(p, iPage, aData);
sqlite3_mutex_leave(p.pDestDb.mutex);
Debug.Assert(rc != SQLITE_BUSY && rc != SQLITE_LOCKED);
if (rc != SQLITE_OK)
{
p.rc = rc;
}
}
}
}
/// <summary>
/// Restart the backup process. This is called when the pager layer
/// detects that the database has been modified by an external database
/// connection. In this case there is no way of knowing which of the
/// pages that have been copied into the destination database are still
/// valid and which are not, so the entire process needs to be restarted.
///
/// It is assumed that the mutex associated with the BtShared object
/// corresponding to the source database is held when this function is
/// called.
/// </summary>
static void sqlite3BackupRestart(sqlite3_backup pBackup)
{
sqlite3_backup p; /* Iterator variable */
for (p = pBackup; p != null; p = p.pNext)
{
Debug.Assert(sqlite3_mutex_held(p.pSrc.pBt.mutex));
p.iNext = 1;
}
}
#if !SQLITE_OMIT_VACUUM
/// <summary>
/// Copy the complete content of pBtFrom into pBtTo. A transaction
/// must be active for both files.
///
/// The size of file pTo may be reduced by this operation. If anything
/// goes wrong, the transaction on pTo is rolled back. If successful, the
/// transaction is committed before returning.
/// </summary>
static int sqlite3BtreeCopyFile(Btree pTo, Btree pFrom)
{
int rc;
sqlite3_backup b;
sqlite3BtreeEnter(pTo);
sqlite3BtreeEnter(pFrom);
/* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
** to 0. This is used by the implementations of sqlite3_backup_step()
** and sqlite3_backup_finish() to detect that they are being called
** from this function, not directly by the user.
*/
b = new sqlite3_backup();// memset( &b, 0, sizeof( b ) );
b.pSrcDb = pFrom.db;
b.pSrc = pFrom;
b.pDest = pTo;
b.iNext = 1;
/* 0x7FFFFFFF is the hard limit for the number of pages in a database
** file. By passing this as the number of pages to copy to
** sqlite3_backup_step(), we can guarantee that the copy finishes
** within a single call (unless an error occurs). The Debug.Assert() statement
** checks this assumption - (p.rc) should be set to either SQLITE_DONE
** or an error code.
*/
sqlite3_backup_step(b, 0x7FFFFFFF);
Debug.Assert(b.rc != SQLITE_OK);
rc = sqlite3_backup_finish(b);
if (rc == SQLITE_OK)
{
pTo.pBt.pageSizeFixed = false;
}
sqlite3BtreeLeave(pFrom);
sqlite3BtreeLeave(pTo);
return rc;
}
#endif //* SQLITE_OMIT_VACUUM */
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.Fees;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
using QuantConnect.Securities.Positions;
namespace QuantConnect.Brokerages.Backtesting
{
/// <summary>
/// Represents a brokerage to be used during backtesting. This is intended to be only be used with the BacktestingTransactionHandler
/// </summary>
public class BacktestingBrokerage : Brokerage
{
// flag used to indicate whether or not we need to scan for
// fills, this is purely a performance concern is ConcurrentDictionary.IsEmpty
// is not exactly the fastest operation and Scan gets called at least twice per
// time loop
private bool _needsScan;
private readonly ConcurrentDictionary<int, Order> _pending;
private readonly object _needsScanLock = new object();
private readonly HashSet<Symbol> _pendingOptionAssignments = new HashSet<Symbol>();
/// <summary>
/// This is the algorithm under test
/// </summary>
protected readonly IAlgorithm Algorithm;
/// <summary>
/// Creates a new BacktestingBrokerage for the specified algorithm
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
public BacktestingBrokerage(IAlgorithm algorithm)
: base("Backtesting Brokerage")
{
Algorithm = algorithm;
_pending = new ConcurrentDictionary<int, Order>();
}
/// <summary>
/// Creates a new BacktestingBrokerage for the specified algorithm
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="name">The name of the brokerage</param>
protected BacktestingBrokerage(IAlgorithm algorithm, string name)
: base(name)
{
Algorithm = algorithm;
_pending = new ConcurrentDictionary<int, Order>();
}
/// <summary>
/// Creates a new BacktestingBrokerage for the specified algorithm. Adds market simulation to BacktestingBrokerage;
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="marketSimulation">The backtesting market simulation instance</param>
public BacktestingBrokerage(IAlgorithm algorithm, IBacktestingMarketSimulation marketSimulation)
: base("Backtesting Brokerage")
{
Algorithm = algorithm;
MarketSimulation = marketSimulation;
_pending = new ConcurrentDictionary<int, Order>();
}
/// <summary>
/// Gets the connection status
/// </summary>
/// <remarks>
/// The BacktestingBrokerage is always connected
/// </remarks>
public override bool IsConnected => true;
/// <summary>
/// Gets all open orders on the account
/// </summary>
/// <returns>The open orders returned from IB</returns>
public override List<Order> GetOpenOrders()
{
return Algorithm.Transactions.GetOpenOrders().ToList();
}
/// <summary>
/// Gets all holdings for the account
/// </summary>
/// <returns>The current holdings from the account</returns>
public override List<Holding> GetAccountHoldings()
{
// grab everything from the portfolio with a non-zero absolute quantity
return (from kvp in Algorithm.Portfolio.Securities.OrderBy(x => x.Value.Symbol)
where kvp.Value.Holdings.AbsoluteQuantity > 0
select new Holding(kvp.Value)).ToList();
}
/// <summary>
/// Gets the current cash balance for each currency held in the brokerage account
/// </summary>
/// <returns>The current cash balance for each currency available for trading</returns>
public override List<CashAmount> GetCashBalance()
{
return Algorithm.Portfolio.CashBook.Select(x => new CashAmount(x.Value.Amount, x.Value.Symbol)).ToList();
}
/// <summary>
/// Places a new order and assigns a new broker ID to the order
/// </summary>
/// <param name="order">The order to be placed</param>
/// <returns>True if the request for a new order has been placed, false otherwise</returns>
public override bool PlaceOrder(Order order)
{
if (Algorithm.LiveMode)
{
Log.Trace("BacktestingBrokerage.PlaceOrder(): Type: " + order.Type + " Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity);
}
if (order.Status == OrderStatus.New)
{
lock (_needsScanLock)
{
_needsScan = true;
SetPendingOrder(order);
}
var orderId = order.Id.ToStringInvariant();
if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(orderId);
// fire off the event that says this order has been submitted
var submitted = new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero)
{ Status = OrderStatus.Submitted };
OnOrderEvent(submitted);
return true;
}
return false;
}
/// <summary>
/// Updates the order with the same ID
/// </summary>
/// <param name="order">The new order information</param>
/// <returns>True if the request was made for the order to be updated, false otherwise</returns>
public override bool UpdateOrder(Order order)
{
if (Algorithm.LiveMode)
{
Log.Trace("BacktestingBrokerage.UpdateOrder(): Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity + " Status: " + order.Status);
}
lock (_needsScanLock)
{
Order pending;
if (!_pending.TryGetValue(order.Id, out pending))
{
// can't update something that isn't there
return false;
}
_needsScan = true;
SetPendingOrder(order);
}
var orderId = order.Id.ToStringInvariant();
if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(orderId);
// fire off the event that says this order has been updated
var updated = new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero)
{
Status = OrderStatus.UpdateSubmitted
};
OnOrderEvent(updated);
return true;
}
/// <summary>
/// Cancels the order with the specified ID
/// </summary>
/// <param name="order">The order to cancel</param>
/// <returns>True if the request was made for the order to be canceled, false otherwise</returns>
public override bool CancelOrder(Order order)
{
if (Algorithm.LiveMode)
{
Log.Trace("BacktestingBrokerage.CancelOrder(): Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity);
}
lock (_needsScanLock)
{
Order pending;
if (!_pending.TryRemove(order.Id, out pending))
{
// can't cancel something that isn't there
return false;
}
}
var orderId = order.Id.ToStringInvariant();
if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(order.Id.ToStringInvariant());
// fire off the event that says this order has been canceled
var canceled = new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero)
{ Status = OrderStatus.Canceled };
OnOrderEvent(canceled);
return true;
}
/// <summary>
/// Market Simulation - simulates various market conditions in backtest
/// </summary>
public IBacktestingMarketSimulation MarketSimulation { get; set; }
/// <summary>
/// Scans all the outstanding orders and applies the algorithm model fills to generate the order events
/// </summary>
public virtual void Scan()
{
lock (_needsScanLock)
{
// there's usually nothing in here
if (!_needsScan)
{
return;
}
var stillNeedsScan = false;
// process each pending order to produce fills/fire events
foreach (var kvp in _pending.OrderBy(x => x.Key))
{
var order = kvp.Value;
if (order == null)
{
Log.Error("BacktestingBrokerage.Scan(): Null pending order found: " + kvp.Key);
_pending.TryRemove(kvp.Key, out order);
continue;
}
if (order.Status.IsClosed())
{
// this should never actually happen as we always remove closed orders as they happen
_pending.TryRemove(order.Id, out order);
continue;
}
// all order fills are processed on the next bar (except for market orders)
if (order.Time == Algorithm.UtcTime && order.Type != OrderType.Market && order.Type != OrderType.OptionExercise)
{
stillNeedsScan = true;
continue;
}
var fills = new OrderEvent[0];
Security security;
if (!Algorithm.Securities.TryGetValue(order.Symbol, out security))
{
Log.Error("BacktestingBrokerage.Scan(): Unable to process order: " + order.Id + ". The security no longer exists.");
// invalidate the order in the algorithm before removing
OnOrderEvent(new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero)
{Status = OrderStatus.Invalid});
_pending.TryRemove(order.Id, out order);
continue;
}
if (order.Type == OrderType.MarketOnOpen)
{
// This is a performance improvement:
// Since MOO should never fill on the same bar or on stale data (see FillModel)
// the order can remain unfilled for multiple 'scans', so we want to avoid
// margin and portfolio calculations since they are expensive
var currentBar = security.GetLastData();
var localOrderTime = order.Time.ConvertFromUtc(security.Exchange.TimeZone);
if (currentBar == null || localOrderTime >= currentBar.EndTime)
{
stillNeedsScan = true;
continue;
}
}
// check if the time in force handler allows fills
if (order.TimeInForce.IsOrderExpired(security, order))
{
OnOrderEvent(new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero)
{
Status = OrderStatus.Canceled,
Message = "The order has expired."
});
_pending.TryRemove(order.Id, out order);
continue;
}
// check if we would actually be able to fill this
if (!Algorithm.BrokerageModel.CanExecuteOrder(security, order))
{
continue;
}
// verify sure we have enough cash to perform the fill
HasSufficientBuyingPowerForOrderResult hasSufficientBuyingPowerResult;
try
{
var group = Algorithm.Portfolio.Positions.CreatePositionGroup(order);
hasSufficientBuyingPowerResult = group.BuyingPowerModel.HasSufficientBuyingPowerForOrder(
new HasSufficientPositionGroupBuyingPowerForOrderParameters(Algorithm.Portfolio, group, order)
);
}
catch (Exception err)
{
// if we threw an error just mark it as invalid and remove the order from our pending list
OnOrderEvent(new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero,
err.Message)
{ Status = OrderStatus.Invalid });
Order pending;
_pending.TryRemove(order.Id, out pending);
Log.Error(err);
Algorithm.Error($"Order Error: id: {order.Id}, Error executing margin models: {err.Message}");
continue;
}
//Before we check this queued order make sure we have buying power:
if (hasSufficientBuyingPowerResult.IsSufficient)
{
//Model:
var model = security.FillModel;
//Based on the order type: refresh its model to get fill price and quantity
try
{
if (order.Type == OrderType.OptionExercise)
{
var option = (Option)security;
fills = option.OptionExerciseModel.OptionExercise(option, order as OptionExerciseOrder).ToArray();
}
else
{
var context = new FillModelParameters(
security,
order,
Algorithm.SubscriptionManager.SubscriptionDataConfigService,
Algorithm.Settings.StalePriceTimeSpan);
fills = new[] { model.Fill(context).OrderEvent };
}
// invoke fee models for completely filled order events
foreach (var fill in fills)
{
if (fill.Status == OrderStatus.Filled)
{
// this check is provided for backwards compatibility of older user-defined fill models
// that may be performing fee computation inside the fill model w/out invoking the fee model
// TODO : This check can be removed in April, 2019 -- a 6-month window to upgrade (also, suspect small % of users, if any are impacted)
if (fill.OrderFee.Value.Amount == 0m)
{
fill.OrderFee = security.FeeModel.GetOrderFee(
new OrderFeeParameters(security,
order));
}
}
}
}
catch (Exception err)
{
Log.Error(err);
Algorithm.Error($"Order Error: id: {order.Id}, Transaction model failed to fill for order type: {order.Type} with error: {err.Message}");
}
}
else
{
// invalidate the order in the algorithm before removing
var message = $"Insufficient buying power to complete order (Value:{order.GetValue(security).SmartRounding()}), Reason: {hasSufficientBuyingPowerResult.Reason}.";
OnOrderEvent(new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero,
message)
{ Status = OrderStatus.Invalid });
Order pending;
_pending.TryRemove(order.Id, out pending);
Algorithm.Error($"Order Error: id: {order.Id}, {message}");
continue;
}
foreach (var fill in fills)
{
// check if the fill should be emitted
if (!order.TimeInForce.IsFillValid(security, order, fill))
{
break;
}
// change in status or a new fill
if (order.Status != fill.Status || fill.FillQuantity != 0)
{
// we update the order status so we do not re process it if we re enter
// because of the call to OnOrderEvent.
// Note: this is done by the transaction handler but we have a clone of the order
order.Status = fill.Status;
//If the fill models come back suggesting filled, process the affects on portfolio
OnOrderEvent(fill);
}
if (fill.IsAssignment)
{
fill.Message = order.Tag;
OnOptionPositionAssigned(fill);
}
}
if (fills.All(x => x.Status.IsClosed()))
{
_pending.TryRemove(order.Id, out order);
}
else
{
stillNeedsScan = true;
}
}
// if we didn't fill then we need to continue to scan or
// if there are still pending orders
_needsScan = stillNeedsScan || !_pending.IsEmpty;
}
}
/// <summary>
/// Runs market simulation
/// </summary>
public void SimulateMarket()
{
// if simulator is installed, we run it
MarketSimulation?.SimulateMarketConditions(this, Algorithm);
}
/// <summary>
/// This method is called by market simulator in order to launch an assignment event
/// </summary>
/// <param name="option">Option security to assign</param>
/// <param name="quantity">Quantity to assign</param>
public virtual void ActivateOptionAssignment(Option option, int quantity)
{
// do not process the same assignment more than once
if (_pendingOptionAssignments.Contains(option.Symbol)) return;
_pendingOptionAssignments.Add(option.Symbol);
// assignments always cause a positive change to option contract holdings
var request = new SubmitOrderRequest(OrderType.OptionExercise, option.Type, option.Symbol, Math.Abs(quantity), 0m, 0m, 0m, Algorithm.UtcTime, "Simulated option assignment before expiration");
var ticket = Algorithm.Transactions.ProcessRequest(request);
Log.Trace($"BacktestingBrokerage.ActivateOptionAssignment(): OrderId: {ticket.OrderId}");
}
/// <summary>
/// Event invocator for the OrderFilled event
/// </summary>
/// <param name="e">The OrderEvent</param>
protected override void OnOrderEvent(OrderEvent e)
{
if (e.Status.IsClosed() && _pendingOptionAssignments.Contains(e.Symbol))
{
_pendingOptionAssignments.Remove(e.Symbol);
}
base.OnOrderEvent(e);
}
/// <summary>
/// The BacktestingBrokerage is always connected. This is a no-op.
/// </summary>
public override void Connect()
{
//NOP
}
/// <summary>
/// The BacktestingBrokerage is always connected. This is a no-op.
/// </summary>
public override void Disconnect()
{
//NOP
}
/// <summary>
/// Sets the pending order as a clone to prevent object reference nastiness
/// </summary>
/// <param name="order">The order to be added to the pending orders dictionary</param>
/// <returns></returns>
private void SetPendingOrder(Order order)
{
_pending[order.Id] = order;
}
}
}
| |
namespace StripeTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Moq.Protected;
using Newtonsoft.Json;
using Stripe;
using Xunit;
public class AutoPagingTest : BaseStripeTest
{
public AutoPagingTest(MockHttpClientFixture mockHttpClientFixture)
: base(mockHttpClientFixture)
{
}
[Fact]
public void ListAutoPaging()
{
// Set up stubbed requests
var response1 = new HttpResponseMessage(HttpStatusCode.OK);
response1.Content = new StringContent(GetResourceAsString("pageable_models.0.json"));
var response2 = new HttpResponseMessage(HttpStatusCode.OK);
response2.Content = new StringContent(GetResourceAsString("pageable_models.1.json"));
var response3 = new HttpResponseMessage(HttpStatusCode.OK);
response3.Content = new StringContent(GetResourceAsString("pageable_models.2.json"));
this.MockHttpClientFixture.MockHandler.Protected()
.SetupSequence<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels"),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(response1))
.Returns(Task.FromResult(response2))
.Returns(Task.FromResult(response3))
.Throws(new StripeTestException("Unexpected invocation!"));
// Call auto-paging method
var service = new PageableService(this.StripeClient);
var options = new ListOptions
{
Limit = 2,
};
var models = service.ListAutoPaging(options).ToList();
// Check results
Assert.Equal(5, models.Count);
Assert.Equal("pm_123", models[0].Id);
Assert.Equal("pm_124", models[1].Id);
Assert.Equal("pm_125", models[2].Id);
Assert.Equal("pm_126", models[3].Id);
Assert.Equal("pm_127", models[4].Id);
// Check invocations
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&starting_after=pm_124"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&starting_after=pm_126"),
ItExpr.IsAny<CancellationToken>());
}
[Fact]
public void ListAutoPaging_NoParams()
{
// Set up stubbed requests
var response1 = new HttpResponseMessage(HttpStatusCode.OK);
response1.Content = new StringContent(GetResourceAsString("pageable_models.0.json"));
var response2 = new HttpResponseMessage(HttpStatusCode.OK);
response2.Content = new StringContent(GetResourceAsString("pageable_models.1.json"));
var response3 = new HttpResponseMessage(HttpStatusCode.OK);
response3.Content = new StringContent(GetResourceAsString("pageable_models.2.json"));
this.MockHttpClientFixture.MockHandler.Protected()
.SetupSequence<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels"),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(response1))
.Returns(Task.FromResult(response2))
.Returns(Task.FromResult(response3))
.Throws(new StripeTestException("Unexpected invocation!"));
// Call auto-paging method
var service = new PageableService(this.StripeClient);
var models = service.ListAutoPaging().ToList();
// Check results
Assert.Equal(5, models.Count);
Assert.Equal("pm_123", models[0].Id);
Assert.Equal("pm_124", models[1].Id);
Assert.Equal("pm_125", models[2].Id);
Assert.Equal("pm_126", models[3].Id);
Assert.Equal("pm_127", models[4].Id);
// Check invocations
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == string.Empty),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?starting_after=pm_124"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?starting_after=pm_126"),
ItExpr.IsAny<CancellationToken>());
}
[Fact]
public void ListAutoPaging_StartingAfter()
{
// Set up stubbed requests
var response1 = new HttpResponseMessage(HttpStatusCode.OK);
response1.Content = new StringContent(GetResourceAsString("pageable_models.1.json"));
var response2 = new HttpResponseMessage(HttpStatusCode.OK);
response2.Content = new StringContent(GetResourceAsString("pageable_models.2.json"));
this.MockHttpClientFixture.MockHandler.Protected()
.SetupSequence<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels"),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(response1))
.Returns(Task.FromResult(response2))
.Throws(new StripeTestException("Unexpected invocation!"));
// Call auto-paging method
var service = new PageableService(this.StripeClient);
var options = new ListOptions
{
Limit = 2,
StartingAfter = "pm_124",
};
var models = service.ListAutoPaging(options).ToList();
// Check results
Assert.Equal(3, models.Count);
Assert.Equal("pm_125", models[0].Id);
Assert.Equal("pm_126", models[1].Id);
Assert.Equal("pm_127", models[2].Id);
// Check invocations
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&starting_after=pm_124"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&starting_after=pm_126"),
ItExpr.IsAny<CancellationToken>());
}
[Fact]
public void ListAutoPaging_EndingBefore()
{
// Set up stubbed requests
var response1 = new HttpResponseMessage(HttpStatusCode.OK);
response1.Content = new StringContent(GetResourceAsString("pageable_models.1.json"));
var response2 = new HttpResponseMessage(HttpStatusCode.OK);
response2.Content = new StringContent(GetResourceAsString("pageable_models.0.json"));
var response3 = new HttpResponseMessage(HttpStatusCode.OK);
response3.Content = new StringContent(GetResourceAsString("pageable_models.0b.json"));
this.MockHttpClientFixture.MockHandler.Protected()
.SetupSequence<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels"),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(response1))
.Returns(Task.FromResult(response2))
.Returns(Task.FromResult(response3))
.Throws(new StripeTestException("Unexpected invocation!"));
// Call auto-paging method
var service = new PageableService(this.StripeClient);
var options = new ListOptions
{
Limit = 2,
EndingBefore = "pm_127",
};
var models = service.ListAutoPaging(options).ToList();
// Check results
Assert.Equal(5, models.Count);
Assert.Equal("pm_126", models[0].Id);
Assert.Equal("pm_125", models[1].Id);
Assert.Equal("pm_124", models[2].Id);
Assert.Equal("pm_123", models[3].Id);
Assert.Equal("pm_122", models[4].Id);
// Check invocations
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&ending_before=pm_127"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&ending_before=pm_125"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&ending_before=pm_123"),
ItExpr.IsAny<CancellationToken>());
}
[Fact]
public async Task ListAutoPagingAsync()
{
// Set up stubbed requests
var response1 = new HttpResponseMessage(HttpStatusCode.OK);
response1.Content = new StringContent(GetResourceAsString("pageable_models.0.json"));
var response2 = new HttpResponseMessage(HttpStatusCode.OK);
response2.Content = new StringContent(GetResourceAsString("pageable_models.1.json"));
var response3 = new HttpResponseMessage(HttpStatusCode.OK);
response3.Content = new StringContent(GetResourceAsString("pageable_models.2.json"));
this.MockHttpClientFixture.MockHandler.Protected()
.SetupSequence<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels"),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(response1))
.Returns(Task.FromResult(response2))
.Returns(Task.FromResult(response3))
.Throws(new StripeTestException("Unexpected invocation!"));
// Call auto-paging method
var service = new PageableService(this.StripeClient);
var options = new ListOptions
{
Limit = 2,
};
var models = await service.ListAutoPagingAsync(options).ToListAsync();
// Check results
Assert.Equal(5, models.Count);
Assert.Equal("pm_123", models[0].Id);
Assert.Equal("pm_124", models[1].Id);
Assert.Equal("pm_125", models[2].Id);
Assert.Equal("pm_126", models[3].Id);
Assert.Equal("pm_127", models[4].Id);
// Check invocations
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&starting_after=pm_124"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&starting_after=pm_126"),
ItExpr.IsAny<CancellationToken>());
}
[Fact]
public async Task ListAutoPagingAsync_NoParams()
{
// Set up stubbed requests
var response1 = new HttpResponseMessage(HttpStatusCode.OK);
response1.Content = new StringContent(GetResourceAsString("pageable_models.0.json"));
var response2 = new HttpResponseMessage(HttpStatusCode.OK);
response2.Content = new StringContent(GetResourceAsString("pageable_models.1.json"));
var response3 = new HttpResponseMessage(HttpStatusCode.OK);
response3.Content = new StringContent(GetResourceAsString("pageable_models.2.json"));
this.MockHttpClientFixture.MockHandler.Protected()
.SetupSequence<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels"),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(response1))
.Returns(Task.FromResult(response2))
.Returns(Task.FromResult(response3))
.Throws(new StripeTestException("Unexpected invocation!"));
// Call auto-paging method
var service = new PageableService(this.StripeClient);
var models = await service.ListAutoPagingAsync().ToListAsync();
// Check results
Assert.Equal(5, models.Count);
Assert.Equal("pm_123", models[0].Id);
Assert.Equal("pm_124", models[1].Id);
Assert.Equal("pm_125", models[2].Id);
Assert.Equal("pm_126", models[3].Id);
Assert.Equal("pm_127", models[4].Id);
// Check invocations
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == string.Empty),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?starting_after=pm_124"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?starting_after=pm_126"),
ItExpr.IsAny<CancellationToken>());
}
[Fact]
public async Task ListAutoPagingAsync_StartingAfter()
{
// Set up stubbed requests
var response1 = new HttpResponseMessage(HttpStatusCode.OK);
response1.Content = new StringContent(GetResourceAsString("pageable_models.1.json"));
var response2 = new HttpResponseMessage(HttpStatusCode.OK);
response2.Content = new StringContent(GetResourceAsString("pageable_models.2.json"));
this.MockHttpClientFixture.MockHandler.Protected()
.SetupSequence<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels"),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(response1))
.Returns(Task.FromResult(response2))
.Throws(new StripeTestException("Unexpected invocation!"));
// Call auto-paging method
var service = new PageableService(this.StripeClient);
var options = new ListOptions
{
Limit = 2,
StartingAfter = "pm_124",
};
var models = await service.ListAutoPagingAsync(options).ToListAsync();
// Check results
Assert.Equal(3, models.Count);
Assert.Equal("pm_125", models[0].Id);
Assert.Equal("pm_126", models[1].Id);
Assert.Equal("pm_127", models[2].Id);
// Check invocations
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&starting_after=pm_124"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&starting_after=pm_126"),
ItExpr.IsAny<CancellationToken>());
}
[Fact]
public async Task ListAutoPagingAsync_EndingBefore()
{
// Set up stubbed requests
var response1 = new HttpResponseMessage(HttpStatusCode.OK);
response1.Content = new StringContent(GetResourceAsString("pageable_models.1.json"));
var response2 = new HttpResponseMessage(HttpStatusCode.OK);
response2.Content = new StringContent(GetResourceAsString("pageable_models.0.json"));
var response3 = new HttpResponseMessage(HttpStatusCode.OK);
response3.Content = new StringContent(GetResourceAsString("pageable_models.0b.json"));
this.MockHttpClientFixture.MockHandler.Protected()
.SetupSequence<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels"),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(response1))
.Returns(Task.FromResult(response2))
.Returns(Task.FromResult(response3))
.Throws(new StripeTestException("Unexpected invocation!"));
// Call auto-paging method
var service = new PageableService(this.StripeClient);
var options = new ListOptions
{
Limit = 2,
EndingBefore = "pm_127",
};
var models = await service.ListAutoPagingAsync(options).ToListAsync();
// Check results
Assert.Equal(5, models.Count);
Assert.Equal("pm_126", models[0].Id);
Assert.Equal("pm_125", models[1].Id);
Assert.Equal("pm_124", models[2].Id);
Assert.Equal("pm_123", models[3].Id);
Assert.Equal("pm_122", models[4].Id);
// Check invocations
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&ending_before=pm_127"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&ending_before=pm_125"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&ending_before=pm_123"),
ItExpr.IsAny<CancellationToken>());
}
[Fact]
public async Task ListAutoPagingAsync_WithCancellation()
{
// Set up stubbed requests
var response1 = new HttpResponseMessage(HttpStatusCode.OK);
response1.Content = new StringContent(GetResourceAsString("pageable_models.0.json"));
var response2 = new HttpResponseMessage(HttpStatusCode.OK);
response2.Content = new StringContent(GetResourceAsString("pageable_models.1.json"));
this.MockHttpClientFixture.MockHandler.Protected()
.SetupSequence<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels"),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(response1))
.Returns(Task.FromResult(response2))
.Throws(new StripeTestException("Unexpected invocation!"));
// Call auto-paging method
var service = new PageableService(this.StripeClient);
var options = new ListOptions
{
Limit = 2,
};
var models = new List<PageableModel>();
var source = new CancellationTokenSource();
try
{
await foreach (var model in service.ListAutoPagingAsync(options).WithCancellation(source.Token))
{
models.Add(model);
// Cancel in the middle of the second page
if (model.Id == "pm_125")
{
source.Cancel();
}
}
Assert.True(false, "Exception OperationCanceledException to be thrown");
}
catch (OperationCanceledException)
{
}
finally
{
source.Dispose();
}
// Check results
Assert.Equal(3, models.Count);
Assert.Equal("pm_123", models[0].Id);
Assert.Equal("pm_124", models[1].Id);
Assert.Equal("pm_125", models[2].Id);
// Check invocations
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2"),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == HttpMethod.Get &&
m.RequestUri.AbsolutePath == "/v1/pageablemodels" &&
m.RequestUri.Query == "?limit=2&starting_after=pm_124"),
ItExpr.IsAny<CancellationToken>());
}
public class PageableModel : StripeEntity<PageableModel>, IHasId
{
[JsonProperty("id")]
public string Id { get; set; }
}
public class PageableService : Service<PageableModel>
{
public PageableService(IStripeClient client)
: base(client)
{
}
public override string BasePath => "/v1/pageablemodels";
public IEnumerable<PageableModel> ListAutoPaging(ListOptions options = null, RequestOptions requestOptions = null)
{
return this.ListEntitiesAutoPaging(options, requestOptions);
}
public IAsyncEnumerable<PageableModel> ListAutoPagingAsync(ListOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
{
return this.ListEntitiesAutoPagingAsync(options, requestOptions, cancellationToken);
}
}
}
}
| |
// *******************************************************************************************************
// Product: DotSpatial.Symbology.DesktopRasterExt.cs
// Description: Methods for draw rasters.
// *******************************************************************************************************
// Contributor(s): Open source contributors may list themselves and their modifications here.
// Contribution of code constitutes transferral of copyright from authors to DotSpatial copyright holders.
// *******************************************************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using DotSpatial.Data;
using DotSpatial.NTSExtension;
namespace DotSpatial.Symbology
{
/// <summary>
/// DesktopRasterExt contains extension methods for rasters.
/// </summary>
public static class DesktopRasterExt
{
#region CreateHillShade
/// <summary>
/// Create Hillshade of values ranging from 0 to 1, or -1 for no-data regions.
/// This should be a little faster since we are accessing the Data field directly instead of working
/// through a value parameter.
/// </summary>
/// <param name="raster">The raster to create the hillshade from.</param>
/// <param name="shadedRelief">An implementation of IShadedRelief describing how the hillshade should be created.</param>
/// <param name="progressHandler">An implementation of IProgressHandler for progress messages</param>
public static float[][] CreateHillShade(this IRaster raster, IShadedRelief shadedRelief, IProgressHandler progressHandler = null)
{
if (progressHandler == null) progressHandler = raster.ProgressHandler;
var pm = new ProgressMeter(progressHandler, SymbologyMessageStrings.DesktopRasterExt_CreatingShadedRelief, raster.NumRows);
Func<int, int, double> getValue;
if (raster.DataType == typeof(int))
{
var r = raster.ToRaster<int>();
getValue = (row, col) => r.Data[row][col];
}
else if (raster.DataType == typeof(float))
{
var r = raster.ToRaster<float>();
getValue = (row, col) => r.Data[row][col];
}
else if (raster.DataType == typeof(short))
{
var r = raster.ToRaster<short>();
getValue = (row, col) => r.Data[row][col];
}
else if (raster.DataType == typeof(byte))
{
var r = raster.ToRaster<byte>();
getValue = (row, col) => r.Data[row][col];
}
else if (raster.DataType == typeof(double))
{
var r = raster.ToRaster<double>();
getValue = (row, col) => r.Data[row][col];
}
else
{
getValue = (row, col) => raster.Value[row, col];
}
return CreateHillShadeT(raster, getValue, shadedRelief, pm);
}
/// <summary>
/// Create Hillshade of values ranging from 0 to 1, or -1 for no-data regions.
/// This should be a little faster since we are accessing the Data field directly instead of working
/// through a value parameter.
/// </summary>
/// <param name="raster">The raster to create the hillshade from.</param>
/// <param name="shadedRelief">An implementation of IShadedRelief describing how the hillshade should be created.</param>
/// <param name="progressMeter">An implementation of IProgressHandler for progress messages</param>
public static float[][] CreateHillShadeT<T>(this Raster<T> raster, IShadedRelief shadedRelief, ProgressMeter progressMeter) where T : IEquatable<T>, IComparable<T>
{
return CreateHillShadeT(raster, (row, col) => raster.Data[row][col], shadedRelief, progressMeter);
}
private static float[][] CreateHillShadeT<T>(this IRaster raster, Func<int, int, T> getValue, IShadedRelief shadedRelief, ProgressMeter progressMeter) where T : IEquatable<T>, IComparable<T>
{
if (!raster.IsInRam) return null;
int numCols = raster.NumColumns;
int numRows = raster.NumRows;
var noData = Convert.ToSingle(raster.NoDataValue);
float extrusion = shadedRelief.Extrusion;
float elevationFactor = shadedRelief.ElevationFactor;
float lightIntensity = shadedRelief.LightIntensity;
float ambientIntensity = shadedRelief.AmbientIntensity;
FloatVector3 lightDirection = shadedRelief.GetLightDirection();
float[] aff = new float[6]; // affine coefficients converted to float format
for (int i = 0; i < 6; i++)
{
aff[i] = Convert.ToSingle(raster.Bounds.AffineCoefficients[i]);
}
float[][] hillshade = new float[numRows][];
if (progressMeter != null) progressMeter.BaseMessage = "Creating Shaded Relief";
for (int row = 0; row < numRows; row++)
{
hillshade[row] = new float[numCols];
for (int col = 0; col < numCols; col++)
{
// 3D position vectors of three points to create a triangle.
FloatVector3 v1 = new FloatVector3(0f, 0f, 0f);
FloatVector3 v2 = new FloatVector3(0f, 0f, 0f);
FloatVector3 v3 = new FloatVector3(0f, 0f, 0f);
float val = Convert.ToSingle(getValue(row, col));
// Cannot compute polygon ... make the best guess)
if (col >= numCols - 1 || row <= 0)
{
if (col >= numCols - 1 && row <= 0)
{
v1.Z = val;
v2.Z = val;
v3.Z = val;
}
else if (col >= numCols - 1)
{
v1.Z = Convert.ToSingle(getValue(row, col - 1)); // 3 - 2
v2.Z = Convert.ToSingle(getValue(row - 1, col)); // | /
v3.Z = Convert.ToSingle(getValue(row - 1, col - 1)); // 1 *
}
else if (row <= 0)
{
v1.Z = Convert.ToSingle(getValue(row + 1, col)); // 3* 2
v2.Z = Convert.ToSingle(getValue(row, col + 1)); // | /
v3.Z = val; // 1
}
}
else
{
v1.Z = val; // 3 - 2
v2.Z = Convert.ToSingle(getValue(row - 1, col + 1)); // | /
v3.Z = Convert.ToSingle(getValue(row - 1, col)); // 1*
}
// Test for no-data values and don't calculate hillshade in that case
if (v1.Z == noData || v2.Z == noData || v3.Z == noData)
{
hillshade[row][col] = -1; // should never be negative otherwise.
continue;
}
// Apply the Conversion Factor to put elevation into the same range as lat/lon
v1.Z = v1.Z * elevationFactor * extrusion;
v2.Z = v2.Z * elevationFactor * extrusion;
v3.Z = v3.Z * elevationFactor * extrusion;
// Complete the vectors using the latitude/longitude coordinates
v1.X = aff[0] + aff[1] * col + aff[2] * row;
v1.Y = aff[3] + aff[4] * col + aff[5] * row;
v2.X = aff[0] + aff[1] * (col + 1) + aff[2] * (row + 1);
v2.Y = aff[3] + aff[4] * (col + 1) + aff[5] * (row + 1);
v3.X = aff[0] + aff[1] * col + aff[2] * (row + 1);
v3.Y = aff[3] + aff[4] * col + aff[5] * (row + 1);
// We need two direction vectors in order to obtain a cross product
FloatVector3 dir2 = FloatVector3.Subtract(v2, v1); // points from 1 to 2
FloatVector3 dir3 = FloatVector3.Subtract(v3, v1); // points from 1 to 3
FloatVector3 cross = FloatVector3.CrossProduct(dir3, dir2); // right hand rule - cross direction should point into page... reflecting more if light direction is in the same direction
// Normalizing this vector ensures that this vector is a pure direction and won't affect the intensity
cross.Normalize();
// Hillshade now has an "intensity" modifier that should be applied to the R, G and B values of the color found at each pixel.
hillshade[row][col] = FloatVector3.Dot(cross, lightDirection) * lightIntensity + ambientIntensity;
}
if (progressMeter != null) progressMeter.Next();
}
// Setting this indicates that a hillshade has been created more recently than characteristics have been changed.
shadedRelief.HasChanged = false;
return hillshade;
}
#endregion
#region DrawToBitmap
/// <summary>
/// Creates a bitmap from this raster using the specified rasterSymbolizer.
/// </summary>
/// <param name="raster">The raster to draw to a bitmap.</param>
/// <param name="rasterSymbolizer">The raster symbolizer to use for assigning colors.</param>
/// <param name="bitmap">This must be an Format32bbpArgb bitmap that has already been saved to a file so that it exists.</param>
/// <param name="progressHandler">The progress handler to use.</param>
/// <exception cref="ArgumentNullException">rasterSymbolizer cannot be null</exception>
public static void DrawToBitmap(this IRaster raster, IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler = null)
{
if (raster == null) throw new ArgumentNullException("raster");
if (rasterSymbolizer == null) throw new ArgumentNullException("rasterSymbolizer");
if (bitmap == null) throw new ArgumentNullException("bitmap");
if (rasterSymbolizer.Scheme.Categories == null || rasterSymbolizer.Scheme.Categories.Count == 0) return;
BitmapData bmpData;
var rect = new Rectangle(0, 0, raster.NumColumns, raster.NumRows);
try
{
bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
}
catch (Exception)
{
// if they have not saved the bitmap yet, it can cause an exception
var ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Bmp);
ms.Position = 0;
bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
}
var numRows = raster.NumRows;
var numColumns = raster.NumColumns;
// Prepare progress meter
if (progressHandler == null) progressHandler = raster.ProgressHandler;
var pm = new ProgressMeter(progressHandler, "Drawing to Bitmap", numRows);
if (numRows * numColumns < 100000) pm.StepPercent = 50;
if (numRows * numColumns < 500000) pm.StepPercent = 10;
if (numRows * numColumns < 1000000) pm.StepPercent = 5;
DrawToBitmap(raster, rasterSymbolizer, bmpData.Scan0, bmpData.Stride, pm);
bitmap.UnlockBits(bmpData);
rasterSymbolizer.ColorSchemeHasUpdated = true;
}
/// <summary>
/// Creates a bitmap from this raster using the specified rasterSymbolizer.
/// </summary>
/// <param name="raster">The raster to draw to a bitmap</param>
/// <param name="rasterSymbolizer">The raster symbolizer to use for assigning colors</param>
/// <param name="rgbData">Byte values representing the ARGB image bytes</param>
/// <param name="stride">The stride</param>
/// <param name="pm">The progress meter to use.</param>
/// <exception cref="ArgumentNullException">rasterSymbolizer cannot be null</exception>
public static void DrawToBitmapT<T>(Raster<T> raster, IRasterSymbolizer rasterSymbolizer, byte[] rgbData, int stride, ProgressMeter pm)
where T : struct, IEquatable<T>, IComparable<T>
{
DrawToBitmapT(raster, GetNoData(raster), (row, col) => raster.Data[row][col],
i => rgbData[i], (i, b) => rgbData[i] = b, rasterSymbolizer, stride, pm);
if (rasterSymbolizer.IsSmoothed)
{
var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
mySmoother.Smooth();
}
}
/// <summary>
/// Creates a bitmap from this raster using the specified rasterSymbolizer.
/// </summary>
/// <param name="raster">The raster to draw to a bitmap.</param>
/// <param name="rasterSymbolizer">The raster symbolizer to use for assigning colors.</param>
/// <param name="rgbData">Byte values representing the ARGB image bytes.</param>
/// <param name="stride">The stride</param>
/// <param name="pm">The progress meter to use.</param>
public static void DrawToBitmap(this IRaster raster, IRasterSymbolizer rasterSymbolizer, byte[] rgbData, int stride, ProgressMeter pm)
{
if (raster.DataType == typeof(int))
{
DrawToBitmapT(raster.ToRaster<int>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(float))
{
DrawToBitmapT(raster.ToRaster<float>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(short))
{
DrawToBitmapT(raster.ToRaster<short>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(byte))
{
DrawToBitmapT(raster.ToRaster<byte>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(double))
{
DrawToBitmapT(raster.ToRaster<double>(), rasterSymbolizer, rgbData, stride, pm);
}
else
{
DrawToBitmapT(raster, raster.NoDataValue, (row, col) => raster.Value[row, col],
i => rgbData[i], (i, b) => rgbData[i] = b, rasterSymbolizer, stride, pm);
if (rasterSymbolizer.IsSmoothed)
{
var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
mySmoother.Smooth();
}
}
}
private static void DrawToBitmapT<T>(Raster<T> raster, IRasterSymbolizer rasterSymbolizer, IntPtr rgbData, int stride, ProgressMeter pm)
where T : struct, IEquatable<T>, IComparable<T>
{
DrawToBitmapT(raster, GetNoData(raster), (row, col) => raster.Data[row][col],
i => Marshal.ReadByte(rgbData, i), (i, b) => Marshal.WriteByte(rgbData, i, b), rasterSymbolizer, stride, pm);
if (rasterSymbolizer.IsSmoothed)
{
var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
mySmoother.Smooth();
}
}
private static void DrawToBitmap(IRaster raster, IRasterSymbolizer rasterSymbolizer, IntPtr rgbData, int stride, ProgressMeter pm)
{
if (raster.DataType == typeof(int))
{
DrawToBitmapT(raster.ToRaster<int>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(float))
{
DrawToBitmapT(raster.ToRaster<float>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(short))
{
DrawToBitmapT(raster.ToRaster<short>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(byte))
{
DrawToBitmapT(raster.ToRaster<byte>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(double))
{
DrawToBitmapT(raster.ToRaster<double>(), rasterSymbolizer, rgbData, stride, pm);
}
else
{
DrawToBitmapT(raster, raster.NoDataValue, (row, col) => raster.Value[row, col],
i => Marshal.ReadByte(rgbData, i), (i, b) => Marshal.WriteByte(rgbData, i, b), rasterSymbolizer, stride, pm);
if (rasterSymbolizer.IsSmoothed)
{
var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
mySmoother.Smooth();
}
}
}
private static void DrawToBitmapT<T>(IRaster raster, T noData, Func<int, int, T> getValue, Func<int, byte> getByte,
Action<int, byte> setByte, IRasterSymbolizer rasterSymbolizer, int stride, ProgressMeter pm)
where T : struct, IEquatable<T>, IComparable<T>
{
if (raster == null) throw new ArgumentNullException("raster");
if (rasterSymbolizer == null) throw new ArgumentNullException("rasterSymbolizer");
if (rasterSymbolizer.Scheme.Categories == null || rasterSymbolizer.Scheme.Categories.Count == 0) return;
float[][] hillshade = null;
if (rasterSymbolizer.ShadedRelief.IsUsed)
{
pm.BaseMessage = "Calculating Shaded Relief";
hillshade = rasterSymbolizer.HillShade ?? raster.CreateHillShadeT(getValue, rasterSymbolizer.ShadedRelief, pm);
}
pm.BaseMessage = "Calculating Colors";
var sets = GetColorSets<T>(rasterSymbolizer.Scheme.Categories);
var noDataColor = Argb.FromColor(rasterSymbolizer.NoDataColor);
for (int row = 0; row < raster.NumRows; row++)
{
for (int col = 0; col < raster.NumColumns; col++)
{
var value = getValue(row, col);
Argb argb;
if (value.Equals(noData))
{
argb = noDataColor;
}
else
{
// Usually values are not random, so check neighboring previous cells for same color
int? srcOffset = null;
if (col > 0)
{
if (value.Equals(getValue(row, col - 1)))
{
srcOffset = Offset(row, col - 1, stride);
}
}
if (srcOffset == null && row > 0)
{
if (value.Equals(getValue(row - 1, col)))
{
srcOffset = Offset(row - 1, col, stride);
}
}
if (srcOffset != null)
{
argb = new Argb(getByte((int)srcOffset + 3),
getByte((int)srcOffset + 2),
getByte((int)srcOffset + 1),
getByte((int)srcOffset));
}
else
{
argb = GetColor(sets, value);
}
}
if (hillshade != null)
{
if (hillshade[row][col] == -1 || float.IsNaN(hillshade[row][col]))
{
argb = new Argb(argb.A, noDataColor.R, noDataColor.G, noDataColor.B);
}
else
{
var red = (int)(argb.R * hillshade[row][col]);
var green = (int)(argb.G * hillshade[row][col]);
var blue = (int)(argb.B * hillshade[row][col]);
argb = new Argb(argb.A, red, green, blue);
}
}
var offset = Offset(row, col, stride);
setByte(offset, argb.B);
setByte(offset + 1, argb.G);
setByte(offset + 2, argb.R);
setByte(offset + 3, argb.A);
}
pm.Next();
}
}
#endregion
#region PaintColorSchemeToBitmap
/// <summary>
/// Creates a bitmap using only the colorscheme, even if a hillshade was specified.
/// </summary>
/// <param name="raster">The Raster containing values that need to be drawn to the bitmap as a color scheme.</param>
/// <param name="rasterSymbolizer">The raster symbolizer to use.</param>
/// <param name="bitmap">The bitmap to edit. Ensure that this has been created and saved at least once.</param>
/// <param name="progressHandler">An IProgressHandler implementation to receive progress updates.</param>
/// <exception cref="ArgumentNullException">rasterSymbolizer cannot be null.</exception>
public static void PaintColorSchemeToBitmap(this IRaster raster, IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler)
{
if (raster.DataType == typeof(int))
{
PaintColorSchemeToBitmapT(raster.ToRaster<int>(), rasterSymbolizer, bitmap, progressHandler);
}
else if (raster.DataType == typeof(float))
{
PaintColorSchemeToBitmapT(raster.ToRaster<float>(), rasterSymbolizer, bitmap, progressHandler);
}
else if (raster.DataType == typeof(short))
{
PaintColorSchemeToBitmapT(raster.ToRaster<short>(), rasterSymbolizer, bitmap, progressHandler);
}
else if (raster.DataType == typeof(byte))
{
PaintColorSchemeToBitmapT(raster.ToRaster<byte>(), rasterSymbolizer, bitmap, progressHandler);
}
else if (raster.DataType == typeof(double))
{
PaintColorSchemeToBitmapT(raster.ToRaster<double>(), rasterSymbolizer, bitmap, progressHandler);
}
else
{
PaintColorSchemeToBitmapT(raster, raster.NoDataValue, (row, col) => raster.Value[row, col], rasterSymbolizer, bitmap, progressHandler);
}
}
/// <summary>
/// Creates a bitmap using only the colorscheme, even if a hillshade was specified.
/// </summary>
/// <param name="raster">The Raster containing values that need to be drawn to the bitmap as a color scheme.</param>
/// <param name="rasterSymbolizer">The raster symbolizer to use.</param>
/// <param name="bitmap">The bitmap to edit. Ensure that this has been created and saved at least once.</param>
/// <param name="progressHandler">An IProgressHandler implementation to receive progress updates.</param>
/// <exception cref="ArgumentNullException"><paramref name="rasterSymbolizer"/> cannot be null, <see cref="raster"/> cannot be null, <see cref="bitmap"/> cannot be null</exception>
public static void PaintColorSchemeToBitmapT<T>(this Raster<T> raster, IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler)
where T : struct, IEquatable<T>, IComparable<T>
{
PaintColorSchemeToBitmapT(raster, GetNoData(raster), (row, col) => raster.Data[row][col], rasterSymbolizer, bitmap, progressHandler);
}
private static void PaintColorSchemeToBitmapT<T>(this IRaster raster, T noData, Func<int, int, T> getValue,
IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler)
where T : struct, IEquatable<T>, IComparable<T>
{
if (raster == null) throw new ArgumentNullException("raster");
if (rasterSymbolizer == null) throw new ArgumentNullException("rasterSymbolizer");
if (bitmap == null) throw new ArgumentNullException("bitmap");
if (rasterSymbolizer.Scheme.Categories == null || rasterSymbolizer.Scheme.Categories.Count == 0) return;
BitmapData bmpData;
var numRows = raster.NumRows;
var numColumns = raster.NumColumns;
var rect = new Rectangle(0, 0, numColumns, numRows);
try
{
bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
}
catch
{
var ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.MemoryBmp);
ms.Position = 0;
bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
}
// Prepare progress meter
var pm = new ProgressMeter(progressHandler, SymbologyMessageStrings.DesktopRasterExt_PaintingColorScheme, numRows);
if (numRows * numColumns < 100000) pm.StepPercent = 50;
if (numRows * numColumns < 500000) pm.StepPercent = 10;
if (numRows * numColumns < 1000000) pm.StepPercent = 5;
var sets = GetColorSets<T>(rasterSymbolizer.Scheme.Categories);
var noDataColor = Argb.FromColor(rasterSymbolizer.NoDataColor);
var alpha = Argb.ByteRange(Convert.ToInt32(rasterSymbolizer.Opacity * 255));
var ptr = bmpData.Scan0;
for (var row = 0; row < numRows; row++)
{
for (var col = 0; col < numColumns; col++)
{
var val = getValue(row, col);
Argb argb;
if (val.Equals(noData))
{
argb = noDataColor;
}
else
{
// Usually values are not random, so check neighboring previous cells for same color
int? srcOffset = null;
if (col > 0)
{
if (val.Equals(getValue(row, col - 1)))
{
srcOffset = Offset(row, col - 1, bmpData.Stride);
}
}
if (srcOffset == null && row > 0)
{
if (val.Equals(getValue(row - 1, col)))
{
srcOffset = Offset(row - 1, col, bmpData.Stride);
}
}
if (srcOffset != null)
{
argb = new Argb(
Marshal.ReadByte(ptr, (int)srcOffset + 3),
Marshal.ReadByte(ptr, (int)srcOffset + 2),
Marshal.ReadByte(ptr, (int)srcOffset + 1),
Marshal.ReadByte(ptr, (int)srcOffset));
}
else
{
var color = GetColor(sets, val);
argb = new Argb(alpha, color.R, color.G, color.B);
}
}
var offset = Offset(row, col, bmpData.Stride);
Marshal.WriteByte(ptr, offset, argb.B);
Marshal.WriteByte(ptr, offset + 1, argb.G);
Marshal.WriteByte(ptr, offset + 2, argb.R);
Marshal.WriteByte(ptr, offset + 3, argb.A);
}
pm.CurrentValue = row;
}
pm.Reset();
if (rasterSymbolizer.IsSmoothed)
{
var mySmoother = new Smoother(bmpData.Stride, bmpData.Width, bmpData.Height, bmpData.Scan0, progressHandler);
mySmoother.Smooth();
}
bitmap.UnlockBits(bmpData);
rasterSymbolizer.ColorSchemeHasUpdated = true;
}
#endregion
private static List<ColorSet<T>> GetColorSets<T>(IEnumerable<IColorCategory> categories) where T : struct, IComparable<T>
{
var result = new List<ColorSet<T>>();
foreach (var c in categories)
{
var cs = new ColorSet<T>();
Color high = c.HighColor;
Color low = c.LowColor;
cs.Color = Argb.FromColor(low);
if (high != low)
{
cs.GradientModel = c.GradientModel;
cs.Gradient = true;
cs.MinA = low.A;
cs.MinR = low.R;
cs.MinG = low.G;
cs.MinB = low.B;
cs.RangeA = high.A - cs.MinA;
cs.RangeR = high.R - cs.MinR;
cs.RangeG = high.G - cs.MinG;
cs.RangeB = high.B - cs.MinB;
}
cs.Max = Global.MaximumValue<T>();
var testMax = Convert.ToDouble(cs.Max);
cs.Min = Global.MinimumValue<T>();
var testMin = Convert.ToDouble(cs.Min);
if (c.Range.Maximum != null && c.Range.Maximum < testMax)
{
if (c.Range.Maximum < testMin)
cs.Max = cs.Min;
else
cs.Max = (T)Convert.ChangeType(c.Range.Maximum.Value, typeof(T));
}
if (c.Range.Minimum != null && c.Range.Minimum > testMin)
{
if (c.Range.Minimum > testMax)
cs.Min = Global.MaximumValue<T>();
else
cs.Min = (T)Convert.ChangeType(c.Range.Minimum.Value, typeof(T));
}
cs.MinInclusive = c.Range.MinIsInclusive;
cs.MaxInclusive = c.Range.MaxIsInclusive;
result.Add(cs);
}
// The normal order uses "overwrite" behavior, so that each color is drawn
// if it qualifies until all the ranges are tested, overwriting previous.
// This can be mimicked by going through the sets in reverse and choosing
// the first that qualifies. For lots of color ranges, opting out of
// a large portion of the range testing should be faster.
result.Reverse();
return result;
}
private static Argb GetColor<T>(IEnumerable<ColorSet<T>> sets, T value) where T : struct, IComparable<T>
{
foreach (var set in sets)
{
if (set.Contains(value))
{
if (!set.Gradient) return set.Color;
if (set.Min == null || set.Max == null) return set.Color;
double lowVal = Convert.ToDouble(set.Min.Value);
double range = Math.Abs(Convert.ToDouble(set.Max.Value) - lowVal);
double p = 0; // the portion of the range, where 0 is LowValue & 1 is HighValue
double ht;
double dVal = Convert.ToDouble(value);
switch (set.GradientModel)
{
case GradientModel.Linear:
p = (dVal - lowVal) / range;
break;
case GradientModel.Exponential:
ht = dVal;
if (ht < 1) ht = 1.0;
if (range > 1)
p = (Math.Pow(ht - lowVal, 2) / Math.Pow(range, 2));
else
return set.Color;
break;
case GradientModel.Logarithmic:
ht = dVal;
if (ht < 1) ht = 1.0;
if (range > 1.0 && ht - lowVal > 1.0)
p = Math.Log(ht - lowVal) / Math.Log(range);
else
return set.Color;
break;
}
return new Argb(
set.MinA + (int)(set.RangeA * p),
set.MinR + (int)(set.RangeR * p),
set.MinG + (int)(set.RangeG * p),
set.MinB + (int)(set.RangeB * p));
}
}
return Argb.FromColor(Color.Transparent);
}
private static T GetNoData<T>(Raster<T> raster) where T : IEquatable<T>, IComparable<T>
{
// Get nodata value.
var noData = default(T);
try
{
noData = (T)Convert.ChangeType(raster.NoDataValue, typeof(T));
}
catch (OverflowException)
{
// For whatever reason, GDAL occasionally is reporting noDataValues
// That will not fit in the specified band type. Is this due to a
// malformed GeoTiff file?
// http://dotspatial.codeplex.com/workitem/343
Trace.WriteLine("OverflowException while getting NoDataValue");
}
return noData;
}
private static int Offset(int row, int col, int stride)
{
return row * stride + col * 4;
}
/// <summary>
/// Obtains an set of unique values. If there are more than maxCount values, the process stops and overMaxCount is set to true.
/// </summary>
/// <param name="raster">the raster to obtain the unique values from.</param>
/// <param name="maxCount">An integer specifying the maximum number of values to add to the list of unique values</param>
/// <param name="overMaxCount">A boolean that will be true if the process was halted prematurely.</param>
/// <returns>A set of doubles representing the independant values.</returns>
public static ISet<double> GetUniqueValues(this IRaster raster, int maxCount, out bool overMaxCount)
{
overMaxCount = false;
var result = new HashSet<double>();
var totalPossibleCount = int.MaxValue;
// Optimization for integer types
if (raster.DataType == typeof(byte) ||
raster.DataType == typeof(int) ||
raster.DataType == typeof(sbyte) ||
raster.DataType == typeof(uint) ||
raster.DataType == typeof(short) ||
raster.DataType == typeof(ushort))
{
totalPossibleCount = (int)(raster.Maximum - raster.Minimum + 1);
}
// NumRows and NumColumns - virtual properties, so copy them local variables for faster access
var numRows = raster.NumRows;
var numCols = raster.NumColumns;
var valueGrid = raster.Value;
for (var row = 0; row < numRows; row++)
for (var col = 0; col < numCols; col++)
{
double val = valueGrid[row, col];
if (result.Add(val))
{
if (result.Count > maxCount)
{
overMaxCount = true;
goto fin;
}
if (result.Count == totalPossibleCount)
goto fin;
}
}
fin:
return result;
}
/// <summary>
/// This will sample randomly from the raster, preventing duplicates.
/// If the sampleSize is larger than this raster, this returns all of the values from the raster.
/// If a "Sample" has been prefetched and stored in the Sample array, then this will return that.
/// </summary>
/// <param name="raster">The raster to obtain the values from.</param>
/// <param name="sampleSize">Number of values to get.</param>
/// <returns>List of random double values contained in the raster.</returns>
public static List<double> GetRandomValues(this IRaster raster, int sampleSize)
{
if (raster.Sample != null) return raster.Sample.ToList();
int numRows = raster.NumRows;
int numCols = raster.NumColumns;
List<double> result = new List<double>();
double noData = raster.NoDataValue;
if (numRows * numCols < sampleSize)
{
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < numCols; col++)
{
double val = raster.Value[row, col];
if (val != noData) result.Add(raster.Value[row, col]);
}
}
return result;
}
Random rnd = new Random(DateTime.Now.Millisecond);
if (numRows * (long)numCols < (long)sampleSize * 5 && numRows * (long)numCols < int.MaxValue)
{
// When the raster is only just barely larger than the sample size,
// we want to prevent lots of repeat guesses that fail (hit the same previously sampled values).
// We create a copy of all the values and sample from this reservoir while removing sampled values.
List<double> resi = new List<double>();
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < numCols; col++)
{
double val = raster.Value[row, col];
if (val != noData) resi.Add(val);
}
}
//int count = numRows * numCols; //this could failed if there's lot of noDataValues
long longcount = raster.NumValueCells;
int count = numRows * numCols;
if (count < int.MaxValue)
count = (int)longcount;
for (int i = 0; i < sampleSize; i++)
{
if (resi.Count == 0) break;
int indx = rnd.Next(count);
result.Add(resi[indx]);
resi.RemoveAt(indx);
count--;
}
raster.Sample = result;
return result;
}
// Use a HashSet here, because it has O(1) lookup for preventing duplicates
HashSet<long> exclusiveResults = new HashSet<long>();
int remaining = sampleSize;
while (remaining > 0)
{
int row = rnd.Next(numRows);
int col = rnd.Next(numCols);
long index = row * numCols + col;
if (exclusiveResults.Contains(index)) continue;
exclusiveResults.Add(index);
remaining--;
}
// Sorting is O(n ln(n)), but sorting once is better than using a SortedSet for previous lookups.
List<long> sorted = exclusiveResults.ToList();
sorted.Sort();
// Sorted values are much faster to read than reading values in at random, since the file actually
// is reading in a whole line at a time. If we can get more than one value from a line, then that
// is better than getting one value, discarding the cache and then comming back later for the value
// next to it.
result = raster.GetValues(sorted);
raster.Sample = result;
return result;
}
#region HelperClass: ColorSet
private class ColorSet<T>
where T : struct, IComparable<T>
{
public Argb Color; // for non bivalue case.
public bool Gradient;
public GradientModel GradientModel;
public T? Max;
public bool MaxInclusive;
public T? Min;
public int MinA;
public int MinB;
public int MinG;
public bool MinInclusive;
public int MinR;
public int RangeA;
public int RangeB;
public int RangeG;
public int RangeR;
public bool Contains(T value)
{
// Checking for nulls
if (Max == null && Min == null) return true;
if (Min == null)
return MaxInclusive ? value.CompareTo(Max.Value) <= 0 : value.CompareTo(Max.Value) < 0;
if (Max == null)
return MinInclusive ? value.CompareTo(Min.Value) >= 0 : value.CompareTo(Min.Value) > 0;
// Normal checking
double cMax = value.CompareTo(Max.Value);
if (cMax > 0 || (!MaxInclusive && cMax == 0)) return false; //value bigger than max or max excluded
double cMin = value.CompareTo(Min.Value);
if (cMin < 0 || (cMin == 0 && !MinInclusive)) return false; //value smaller than min or min excluded
return true;
}
}
#endregion
}
}
| |
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 CustomerManagerWeb
{
/// <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 add-in.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <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;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
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
}
| |
/*
Bullet for XNA Copyright (c) 2003-2007 Vsevolod Klementjev http://www.codeplex.com/xnadevru
Bullet original C++ version Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace XnaDevRu.BulletX
{
/// <summary>
/// MinkowskiPenetrationDepthSolver implements bruteforce penetration depth estimation.
/// Implementation is based on sampling the depth using support mapping, and using GJK step to get the witness points.
/// </summary>
public class MinkowskiPenetrationDepthSolver : IConvexPenetrationDepthSolver
{
private const int UnitSpherePointsCount = 42;
private static Vector3[] penetrationDirections =
{
new Vector3(0.000000f , -0.000000f,-1.000000f),
new Vector3(0.723608f , -0.525725f,-0.447219f),
new Vector3(-0.276388f , -0.850649f,-0.447219f),
new Vector3(-0.894426f , -0.000000f,-0.447216f),
new Vector3(-0.276388f , 0.850649f,-0.447220f),
new Vector3(0.723608f , 0.525725f,-0.447219f),
new Vector3(0.276388f , -0.850649f,0.447220f),
new Vector3(-0.723608f , -0.525725f,0.447219f),
new Vector3(-0.723608f , 0.525725f,0.447219f),
new Vector3(0.276388f , 0.850649f,0.447219f),
new Vector3(0.894426f , 0.000000f,0.447216f),
new Vector3(-0.000000f , 0.000000f,1.000000f),
new Vector3(0.425323f , -0.309011f,-0.850654f),
new Vector3(-0.162456f , -0.499995f,-0.850654f),
new Vector3(0.262869f , -0.809012f,-0.525738f),
new Vector3(0.425323f , 0.309011f,-0.850654f),
new Vector3(0.850648f , -0.000000f,-0.525736f),
new Vector3(-0.525730f , -0.000000f,-0.850652f),
new Vector3(-0.688190f , -0.499997f,-0.525736f),
new Vector3(-0.162456f , 0.499995f,-0.850654f),
new Vector3(-0.688190f , 0.499997f,-0.525736f),
new Vector3(0.262869f , 0.809012f,-0.525738f),
new Vector3(0.951058f , 0.309013f,0.000000f),
new Vector3(0.951058f , -0.309013f,0.000000f),
new Vector3(0.587786f , -0.809017f,0.000000f),
new Vector3(0.000000f , -1.000000f,0.000000f),
new Vector3(-0.587786f , -0.809017f,0.000000f),
new Vector3(-0.951058f , -0.309013f,-0.000000f),
new Vector3(-0.951058f , 0.309013f,-0.000000f),
new Vector3(-0.587786f , 0.809017f,-0.000000f),
new Vector3(-0.000000f , 1.000000f,-0.000000f),
new Vector3(0.587786f , 0.809017f,-0.000000f),
new Vector3(0.688190f , -0.499997f,0.525736f),
new Vector3(-0.262869f , -0.809012f,0.525738f),
new Vector3(-0.850648f , 0.000000f,0.525736f),
new Vector3(-0.262869f , 0.809012f,0.525738f),
new Vector3(0.688190f , 0.499997f,0.525736f),
new Vector3(0.525730f , 0.000000f,0.850652f),
new Vector3(0.162456f , -0.499995f,0.850654f),
new Vector3(-0.425323f , -0.309011f,0.850654f),
new Vector3(-0.425323f , 0.309011f,0.850654f),
new Vector3(0.162456f , 0.499995f,0.850654f)
};
private class IntermediateResult : DiscreteCollisionDetectorInterface.Result
{
private Vector3 _normalOnBInWorld;
private Vector3 _pointInWorld;
private float _depth;
private bool _hasResult;
public IntermediateResult()
{
_hasResult = false;
}
public bool HasResult { get { return _hasResult; } }
public float Depth { get { return _depth; } }
public Vector3 PointInWorld { get { return _pointInWorld; } }
public override void SetShapeIdentifiers(int partId0, int index0, int partId1, int index1)
{
}
public override void AddContactPoint(Vector3 normalOnBInWorld, Vector3 pointInWorld, float depth)
{
_normalOnBInWorld = normalOnBInWorld;
_pointInWorld = pointInWorld;
_depth = depth;
_hasResult = true;
}
}
#region IConvexPenetrationDepthSolver Members
public bool CalculatePenetrationDepth(ISimplexSolver simplexSolver,
ConvexShape convexA, ConvexShape convexB,
Matrix transformA, Matrix transformB,
Vector3 v, out Vector3 pa, out Vector3 pb, IDebugDraw debugDraw)
{
pa = new Vector3();
pb = new Vector3();
//just take fixed number of orientation, and sample the penetration depth in that direction
float minProj = 1e30f;
Vector3 minNorm = new Vector3();
Vector3 minA = new Vector3(), minB = new Vector3();
Vector3 seperatingAxisInA, seperatingAxisInB;
Vector3 pInA, qInB, pWorld, qWorld, w;
Vector3[] supportVerticesABatch = new Vector3[UnitSpherePointsCount + ConvexShape.MaxPreferredPenetrationDirections * 2];
Vector3[] supportVerticesBBatch = new Vector3[UnitSpherePointsCount + ConvexShape.MaxPreferredPenetrationDirections * 2];
Vector3[] seperatingAxisInABatch = new Vector3[UnitSpherePointsCount + ConvexShape.MaxPreferredPenetrationDirections * 2];
Vector3[] seperatingAxisInBBatch = new Vector3[UnitSpherePointsCount + ConvexShape.MaxPreferredPenetrationDirections * 2];
int numSampleDirections = UnitSpherePointsCount;
for (int i = 0; i < numSampleDirections; i++)
{
Vector3 norm = penetrationDirections[i];
seperatingAxisInABatch[i] = Vector3.TransformNormal((-norm), transformA);
seperatingAxisInBBatch[i] = Vector3.TransformNormal(norm, transformB);
}
{
int numPDA = convexA.PreferredPenetrationDirectionsCount;
if (numPDA != 0)
{
for (int i = 0; i < numPDA; i++)
{
Vector3 norm;
convexA.GetPreferredPenetrationDirection(i, out norm);
norm = Vector3.TransformNormal(norm, transformA);
penetrationDirections[numSampleDirections] = norm;
seperatingAxisInABatch[numSampleDirections] = Vector3.TransformNormal((-norm), transformA);
seperatingAxisInBBatch[numSampleDirections] = Vector3.TransformNormal(norm, transformB);
numSampleDirections++;
}
}
}
{
int numPDB = convexB.PreferredPenetrationDirectionsCount;
if (numPDB != 0)
{
for (int i = 0; i < numPDB; i++)
{
Vector3 norm;
convexB.GetPreferredPenetrationDirection(i, out norm);
norm = Vector3.TransformNormal(norm, transformB);
penetrationDirections[numSampleDirections] = norm;
seperatingAxisInABatch[numSampleDirections] = Vector3.TransformNormal((-norm), transformA);
seperatingAxisInBBatch[numSampleDirections] = Vector3.TransformNormal(norm, transformB);
numSampleDirections++;
}
}
}
convexA.BatchedUnitVectorGetSupportingVertexWithoutMargin(seperatingAxisInABatch, supportVerticesABatch); //, numSampleDirections);
convexB.BatchedUnitVectorGetSupportingVertexWithoutMargin(seperatingAxisInBBatch, supportVerticesBBatch); //, numSampleDirections);
for (int i = 0; i < numSampleDirections; i++)
{
Vector3 norm = penetrationDirections[i];
seperatingAxisInA = seperatingAxisInABatch[i];
seperatingAxisInB = seperatingAxisInBBatch[i];
pInA = supportVerticesABatch[i];
qInB = supportVerticesBBatch[i];
pWorld = MathHelper.MatrixToVector(transformA, pInA);
qWorld = MathHelper.MatrixToVector(transformB, qInB);
w = qWorld - pWorld;
float delta = Vector3.Dot(norm, w);
//find smallest delta
if (delta < minProj)
{
minProj = delta;
minNorm = norm;
minA = pWorld;
minB = qWorld;
}
}
//add the margins
minA += minNorm * convexA.Margin;
minB -= minNorm * convexB.Margin;
//no penetration
if (minProj < 0)
return false;
minProj += (convexA.Margin + convexB.Margin);
GjkPairDetector gjkdet = new GjkPairDetector(convexA, convexB, simplexSolver, null);
float offsetDist = minProj;
Vector3 offset = minNorm * offsetDist;
GjkPairDetector.ClosestPointInput input = new DiscreteCollisionDetectorInterface.ClosestPointInput();
Vector3 newOrg = transformA.Translation + offset;
Matrix displacedTrans = transformA;
displacedTrans.Translation = newOrg;
input.TransformA = displacedTrans;
input.TransformB = transformB;
input.MaximumDistanceSquared = 1e30f;//minProj;
IntermediateResult res = new IntermediateResult();
gjkdet.GetClosestPoints(input, res, debugDraw);
float correctedMinNorm = minProj - res.Depth;
//the penetration depth is over-estimated, relax it
float penetration_relaxation = 1;
minNorm *= penetration_relaxation;
if (res.HasResult)
{
pa = res.PointInWorld - minNorm * correctedMinNorm;
pb = res.PointInWorld;
}
return res.HasResult;
}
#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.
/******************************************************************************
* 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 ZeroHighBitsUInt32()
{
var test = new ScalarBinaryOpTest__ZeroHighBitsUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.ReadUnaligned
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.ReadUnaligned
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.ReadUnaligned
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ScalarBinaryOpTest__ZeroHighBitsUInt32
{
private struct TestStruct
{
public UInt32 _fld1;
public UInt32 _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
testStruct._fld1 = 0xFFFFFFFF;
testStruct._fld2 = 16;
return testStruct;
}
public void RunStructFldScenario(ScalarBinaryOpTest__ZeroHighBitsUInt32 testClass)
{
var result = Bmi2.ZeroHighBits(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static UInt32 _data1;
private static UInt32 _data2;
private static UInt32 _clsVar1;
private static UInt32 _clsVar2;
private UInt32 _fld1;
private UInt32 _fld2;
static ScalarBinaryOpTest__ZeroHighBitsUInt32()
{
_clsVar1 = 0xFFFFFFFF;
_clsVar2 = 16;
}
public ScalarBinaryOpTest__ZeroHighBitsUInt32()
{
Succeeded = true;
_fld1 = 0xFFFFFFFF;
_fld2 = 16;
_data1 = 0xFFFFFFFF;
_data2 = 16;
}
public bool IsSupported => Bmi2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Bmi2.ZeroHighBits(
Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data2))
);
ValidateResult(_data1, _data2, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Bmi2).GetMethod(nameof(Bmi2.ZeroHighBits), new Type[] { typeof(UInt32), typeof(UInt32) })
.Invoke(null, new object[] {
Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data2))
});
ValidateResult(_data1, _data2, (UInt32)result);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Bmi2.ZeroHighBits(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var data1 = Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data1));
var data2 = Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data2));
var result = Bmi2.ZeroHighBits(data1, data2);
ValidateResult(data1, data2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ScalarBinaryOpTest__ZeroHighBitsUInt32();
var result = Bmi2.ZeroHighBits(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Bmi2.ZeroHighBits(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Bmi2.ZeroHighBits(test._fld1, 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 RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(UInt32 left, UInt32 right, UInt32 result, [CallerMemberName] string method = "")
{
var isUnexpectedResult = false;
uint expectedResult = 0xFFFF; isUnexpectedResult = (expectedResult != result);
if (isUnexpectedResult)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Bmi2)}.{nameof(Bmi2.ZeroHighBits)}<UInt32>(UInt32, UInt32): ZeroHighBits failed:");
TestLibrary.TestFramework.LogInformation($" left: {left}");
TestLibrary.TestFramework.LogInformation($" right: {right}");
TestLibrary.TestFramework.LogInformation($" result: {result}");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* 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.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.OptionalModules.Scripting.Minimodule.WorldX;
namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
{
public class World : System.MarshalByRefObject, IWorld, IWorldAudio
{
private readonly Scene m_internalScene;
private readonly ISecurityCredential m_security;
private readonly Heightmap m_heights;
private readonly ObjectAccessor m_objs;
public World(Scene internalScene, ISecurityCredential securityCredential)
{
m_security = securityCredential;
m_internalScene = internalScene;
m_heights = new Heightmap(m_internalScene);
m_objs = new ObjectAccessor(m_internalScene, securityCredential);
}
#region Events
#region OnNewUser
private event OnNewUserDelegate _OnNewUser;
private bool _OnNewUserActive;
public event OnNewUserDelegate OnNewUser
{
add
{
if (!_OnNewUserActive)
{
_OnNewUserActive = true;
m_internalScene.EventManager.OnNewPresence += EventManager_OnNewPresence;
}
_OnNewUser += value;
}
remove
{
_OnNewUser -= value;
if (_OnNewUser == null)
{
_OnNewUserActive = false;
m_internalScene.EventManager.OnNewPresence -= EventManager_OnNewPresence;
}
}
}
void EventManager_OnNewPresence(ScenePresence presence)
{
if (_OnNewUser != null)
{
NewUserEventArgs e = new NewUserEventArgs();
e.Avatar = new SPAvatar(m_internalScene, presence.UUID, m_security);
_OnNewUser(this, e);
}
}
#endregion
#region OnChat
private event OnChatDelegate _OnChat;
private bool _OnChatActive;
public IWorldAudio Audio
{
get { return this; }
}
public event OnChatDelegate OnChat
{
add
{
if (!_OnChatActive)
{
_OnChatActive = true;
m_internalScene.EventManager.OnChatFromClient += EventManager_OnChatFromClient;
m_internalScene.EventManager.OnChatFromWorld += EventManager_OnChatFromWorld;
}
_OnChat += value;
}
remove
{
_OnChat -= value;
if (_OnChat == null)
{
_OnChatActive = false;
m_internalScene.EventManager.OnChatFromClient -= EventManager_OnChatFromClient;
m_internalScene.EventManager.OnChatFromWorld -= EventManager_OnChatFromWorld;
}
}
}
void EventManager_OnChatFromWorld(object sender, OSChatMessage chat)
{
if (_OnChat != null)
{
HandleChatPacket(chat);
return;
}
}
private void HandleChatPacket(OSChatMessage chat)
{
if (string.IsNullOrEmpty(chat.Message))
return;
// Object?
if (chat.Sender == null && chat.SenderObject != null)
{
ChatEventArgs e = new ChatEventArgs();
e.Sender = new SOPObject(m_internalScene, ((SceneObjectPart) chat.SenderObject).LocalId, m_security);
e.Text = chat.Message;
e.Channel = chat.Channel;
_OnChat(this, e);
return;
}
// Avatar?
if (chat.Sender != null && chat.SenderObject == null)
{
ChatEventArgs e = new ChatEventArgs();
e.Sender = new SPAvatar(m_internalScene, chat.SenderUUID, m_security);
e.Text = chat.Message;
e.Channel = chat.Channel;
_OnChat(this, e);
return;
}
// Skip if other
}
void EventManager_OnChatFromClient(object sender, OSChatMessage chat)
{
if (_OnChat != null)
{
HandleChatPacket(chat);
return;
}
}
#endregion
#endregion
public IObjectAccessor Objects
{
get { return m_objs; }
}
public IParcel[] Parcels
{
get
{
List<ILandObject> m_los = m_internalScene.LandChannel.AllParcels();
List<IParcel> m_parcels = new List<IParcel>(m_los.Count);
foreach (ILandObject landObject in m_los)
{
m_parcels.Add(new LOParcel(m_internalScene, landObject.LandData.LocalID));
}
return m_parcels.ToArray();
}
}
public IAvatar[] Avatars
{
get
{
EntityBase[] ents = m_internalScene.Entities.GetAllByType<ScenePresence>();
IAvatar[] rets = new IAvatar[ents.Length];
for (int i = 0; i < ents.Length; i++)
{
EntityBase ent = ents[i];
rets[i] = new SPAvatar(m_internalScene, ent.UUID, m_security);
}
return rets;
}
}
public IHeightmap Terrain
{
get { return m_heights; }
}
#region Implementation of IWorldAudio
public void PlaySound(UUID audio, Vector3 position, double volume)
{
ISoundModule soundModule = m_internalScene.RequestModuleInterface<ISoundModule>();
if (soundModule != null)
{
soundModule.TriggerSound(audio, UUID.Zero, UUID.Zero, UUID.Zero, volume, position,
m_internalScene.RegionInfo.RegionHandle);
}
}
public void PlaySound(UUID audio, Vector3 position)
{
ISoundModule soundModule = m_internalScene.RequestModuleInterface<ISoundModule>();
if (soundModule != null)
{
soundModule.TriggerSound(audio, UUID.Zero, UUID.Zero, UUID.Zero, 1.0, position,
m_internalScene.RegionInfo.RegionHandle);
}
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="EmbeddedUIProxy.cs" company="Microsoft Corporation">
// Copyright (c) 1999, Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Part of the Deployment Tools Foundation project.
// </summary>
//---------------------------------------------------------------------
namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
/// <summary>
/// Managed-code portion of the embedded UI proxy.
/// </summary>
internal static class EmbeddedUIProxy
{
private static IEmbeddedUI uiInstance;
private static string uiClass;
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private static bool DebugBreakEnabled(string method)
{
return CustomActionProxy.DebugBreakEnabled(new string[] { method, EmbeddedUIProxy.uiClass + "." + method } );
}
/// <summary>
/// Initializes managed embedded UI by loading the UI class and invoking its Initialize method.
/// </summary>
/// <param name="sessionHandle">Integer handle to the installer session.</param>
/// <param name="uiClass">Name of the class that implements the embedded UI. This must
/// be of the form: "AssemblyName!Namespace.Class"</param>
/// <param name="internalUILevel">On entry, contains the current UI level for the installation. After this
/// method returns, the installer resets the UI level to the returned value of this parameter.</param>
/// <returns>0 if the embedded UI was successfully loaded and initialized,
/// ERROR_INSTALL_USEREXIT if the user canceled the installation during initialization,
/// or ERROR_INSTALL_FAILURE if the embedded UI could not be initialized.</returns>
/// <remarks>
/// Due to interop limitations, the successful resulting UILevel is actually returned
/// as the high-word of the return value instead of via a ref parameter.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static int Initialize(int sessionHandle, string uiClass, int internalUILevel)
{
Session session = null;
try
{
session = new Session((IntPtr) sessionHandle, false);
if (string.IsNullOrWhiteSpace(uiClass))
{
throw new ArgumentNullException("uiClass");
}
EmbeddedUIProxy.uiInstance = EmbeddedUIProxy.InstantiateUI(session, uiClass);
}
catch (Exception ex)
{
if (session != null)
{
try
{
session.Log("Exception while loading embedded UI:");
session.Log(ex.ToString());
}
catch (Exception)
{
}
}
}
if (EmbeddedUIProxy.uiInstance == null)
{
return (int) ActionResult.Failure;
}
try
{
string resourcePath = Path.GetDirectoryName(EmbeddedUIProxy.uiInstance.GetType().Assembly.Location);
InstallUIOptions uiOptions = (InstallUIOptions) internalUILevel;
if (EmbeddedUIProxy.DebugBreakEnabled("Initialize"))
{
System.Diagnostics.Debugger.Launch();
}
if (EmbeddedUIProxy.uiInstance.Initialize(session, resourcePath, ref uiOptions))
{
// The embedded UI initialized and the installation should continue
// with internal UI reset according to options.
return ((int) uiOptions) << 16;
}
else
{
// The embedded UI did not initialize but the installation should still continue
// with internal UI reset according to options.
return (int) uiOptions;
}
}
catch (InstallCanceledException)
{
// The installation was canceled by the user.
return (int) ActionResult.UserExit;
}
catch (Exception ex)
{
// An unhandled exception causes the installation to fail immediately.
session.Log("Exception thrown by embedded UI initialization:");
session.Log(ex.ToString());
return (int) ActionResult.Failure;
}
}
/// <summary>
/// Passes a progress message to the UI class.
/// </summary>
/// <param name="messageType">Installer message type and message box options.</param>
/// <param name="recordHandle">Handle to a record containing message data.</param>
/// <returns>Return value returned by the UI class.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static int ProcessMessage(int messageType, int recordHandle)
{
if (EmbeddedUIProxy.uiInstance != null)
{
try
{
int msgType = messageType & 0x7F000000;
int buttons = messageType & 0x0000000F;
int icon = messageType & 0x000000F0;
int defButton = messageType & 0x00000F00;
Record msgRec = (recordHandle != 0 ? Record.FromHandle((IntPtr) recordHandle, false) : null);
using (msgRec)
{
if (EmbeddedUIProxy.DebugBreakEnabled("ProcessMessage"))
{
System.Diagnostics.Debugger.Launch();
}
return (int) EmbeddedUIProxy.uiInstance.ProcessMessage(
(InstallMessage) msgType,
msgRec,
(MessageButtons) buttons,
(MessageIcon) icon,
(MessageDefaultButton) defButton);
}
}
catch (Exception)
{
// Ignore it... just hope future messages will not throw exceptions.
}
}
return 0;
}
/// <summary>
/// Passes a shutdown message to the UI class.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static void Shutdown()
{
if (EmbeddedUIProxy.uiInstance != null)
{
try
{
if (EmbeddedUIProxy.DebugBreakEnabled("Shutdown"))
{
System.Diagnostics.Debugger.Launch();
}
EmbeddedUIProxy.uiInstance.Shutdown();
}
catch (Exception)
{
// Nothing to do at this point... the installation is done anyway.
}
EmbeddedUIProxy.uiInstance = null;
}
}
/// <summary>
/// Instantiates a UI class from a given assembly and class name.
/// </summary>
/// <param name="session">Installer session, for logging.</param>
/// <param name="uiClass">Name of the class that implements the embedded UI. This must
/// be of the form: "AssemblyName!Namespace.Class"</param>
/// <returns>Interface on the UI class for handling UI messages.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static IEmbeddedUI InstantiateUI(Session session, string uiClass)
{
int assemblySplit = uiClass.IndexOf('!');
if (assemblySplit < 0)
{
session.Log("Error: invalid embedded UI assembly and class:" + uiClass);
return null;
}
string assemblyName = uiClass.Substring(0, assemblySplit);
EmbeddedUIProxy.uiClass = uiClass.Substring(assemblySplit + 1);
Assembly uiAssembly;
try
{
uiAssembly = AppDomain.CurrentDomain.Load(assemblyName);
// This calls out to CustomActionProxy.DebugBreakEnabled() directly instead
// of calling EmbeddedUIProxy.DebugBreakEnabled() because we don't compose a
// class.method name for this breakpoint.
if (CustomActionProxy.DebugBreakEnabled(new string[] { "EmbeddedUI" }))
{
System.Diagnostics.Debugger.Launch();
}
return (IEmbeddedUI) uiAssembly.CreateInstance(EmbeddedUIProxy.uiClass);
}
catch (Exception ex)
{
session.Log("Error: could not load embedded UI class " + EmbeddedUIProxy.uiClass + " from assembly: " + assemblyName);
session.Log(ex.ToString());
return null;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestDurationTestService : ServiceClient<AutoRestDurationTestService>, IAutoRestDurationTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IDurationOperations.
/// </summary>
public virtual IDurationOperations Duration { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestService(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestDurationTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestDurationTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Duration = new DurationOperations(this);
this.BaseUri = new Uri("https://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
// The NUnit version of this file introduces conditional compilation for
// building under .NET Standard
//
// 11/5/2015 -
// Change namespace to avoid conflict with user code use of mono.options
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
// Missing XML Docs
#pragma warning disable 1591
#if NETSTANDARD1_3 || NETSTANDARD1_6
using NUnit.Compatibility;
#else
using System.Security.Permissions;
using System.Runtime.Serialization;
#endif
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
#if NUNIT_CONSOLE || NUNITLITE || NUNIT_ENGINE
namespace NUnit.Options
#elif NDESK_OPTIONS
namespace NDesk.Options
#else
namespace Mono.Options
#endif
{
public class OptionValueCollection : IList, IList<string> {
List<string> values = new List<string> ();
OptionContext c;
internal OptionValueCollection (OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
#endregion
#region ICollection<T>
public void Add (string item) {values.Add (item);}
public void Clear () {values.Clear ();}
public bool Contains (string item) {return values.Contains (item);}
public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
public bool Remove (string item) {return values.Remove (item);}
public int Count {get {return values.Count;}}
public bool IsReadOnly {get {return false;}}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IList
int IList.Add (object value) {return (values as IList).Add (value);}
bool IList.Contains (object value) {return (values as IList).Contains (value);}
int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
void IList.Remove (object value) {(values as IList).Remove (value);}
void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
bool IList.IsFixedSize {get {return false;}}
object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
#endregion
#region IList<T>
public int IndexOf (string item) {return values.IndexOf (item);}
public void Insert (int index, string item) {values.Insert (index, item);}
public void RemoveAt (int index) {values.RemoveAt (index);}
private void AssertValid (int index)
{
if (c.Option == null)
throw new InvalidOperationException ("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException ("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException (string.Format (
c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this [int index] {
get {
AssertValid (index);
return index >= values.Count ? null : values [index];
}
set {
values [index] = value;
}
}
#endregion
public List<string> ToList ()
{
return new List<string> (values);
}
public string[] ToArray ()
{
return values.ToArray ();
}
public override string ToString ()
{
return string.Join (", ", values.ToArray ());
}
}
public class OptionContext {
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext (OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection (this);
}
public Option Option {
get {return option;}
set {option = value;}
}
public string OptionName {
get {return name;}
set {name = value;}
}
public int OptionIndex {
get {return index;}
set {index = value;}
}
public OptionSet OptionSet {
get {return set;}
}
public OptionValueCollection OptionValues {
get {return c;}
}
}
public enum OptionValueType {
None,
Optional,
Required,
}
public abstract class Option {
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option (string prototype, string description)
: this (prototype, description, 1)
{
}
protected Option (string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException ("prototype");
if (prototype.Length == 0)
throw new ArgumentException ("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException ("maxValueCount");
this.prototype = prototype;
this.names = prototype.Split ('|');
this.description = description;
this.count = maxValueCount;
this.type = ParsePrototype ();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException (
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException (
string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf (names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException (
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype {get {return prototype;}}
public string Description {get {return description;}}
public OptionValueType OptionValueType {get {return type;}}
public int MaxValueCount {get {return count;}}
public string[] GetNames ()
{
return (string[]) names.Clone ();
}
public string[] GetValueSeparators ()
{
if (separators == null)
return new string [0];
return (string[]) separators.Clone ();
}
protected static T Parse<T> (string value, OptionContext c)
{
Type tt = typeof (T);
#if NETSTANDARD1_3 || NETSTANDARD1_6
bool nullable = tt.GetTypeInfo().IsValueType && tt.GetTypeInfo().IsGenericType &&
!tt.GetTypeInfo().IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition () == typeof (Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
#else
bool nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition () == typeof (Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
#endif
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
TypeConverter conv = TypeDescriptor.GetConverter (targetType);
#endif
T t = default (T);
try {
if (value != null)
#if NETSTANDARD1_3 || NETSTANDARD1_6
t = (T)Convert.ChangeType(value, tt, CultureInfo.InvariantCulture);
#else
t = (T) conv.ConvertFromString (value);
#endif
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names {get {return names;}}
internal string[] ValueSeparators {get {return separators;}}
static readonly char[] NameTerminator = new char[]{'=', ':'};
private OptionValueType ParsePrototype ()
{
char type = '\0';
List<string> seps = new List<string> ();
for (int i = 0; i < names.Length; ++i) {
string name = names [i];
if (name.Length == 0)
throw new ArgumentException ("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny (NameTerminator);
if (end == -1)
continue;
names [i] = name.Substring (0, end);
if (type == '\0' || type == name [end])
type = name [end];
else
throw new ArgumentException (
string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
"prototype");
AddSeparators (name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException (
string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1) {
if (seps.Count == 0)
this.separators = new string[]{":", "="};
else if (seps.Count == 1 && seps [0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray ();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators (string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end+1; i < name.Length; ++i) {
switch (name [i]) {
case '{':
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i+1;
break;
case '}':
if (start == -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add (name.Substring (start, i-start));
start = -1;
break;
default:
if (start == -1)
seps.Add (name [i].ToString ());
break;
}
}
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke (OptionContext c)
{
OnParseComplete (c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear ();
}
protected abstract void OnParseComplete (OptionContext c);
public override string ToString ()
{
return Prototype;
}
}
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
[Serializable]
#endif
public class OptionException : Exception
{
private string option;
public OptionException ()
{
}
public OptionException (string message, string optionName)
: base (message)
{
this.option = optionName;
}
public OptionException (string message, string optionName, Exception innerException)
: base (message, innerException)
{
this.option = optionName;
}
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
protected OptionException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
this.option = info.GetString ("OptionName");
}
#endif
public string OptionName {
get {return this.option;}
}
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
base.GetObjectData (info, context);
info.AddValue ("OptionName", option);
}
#endif
}
public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
string localizer(string msg)
{
return msg;
}
public string MessageLocalizer(string msg)
{
return msg;
}
protected override string GetKeyForItem (Option item)
{
if (item == null)
throw new ArgumentNullException ("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names [0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException ("Option has no names!");
}
[Obsolete ("Use KeyedCollection.this[string]")]
protected Option GetOptionForName (string option)
{
if (option == null)
throw new ArgumentNullException ("option");
try {
return base [option];
}
catch (KeyNotFoundException) {
return null;
}
}
protected override void InsertItem (int index, Option item)
{
base.InsertItem (index, item);
AddImpl (item);
}
protected override void RemoveItem (int index)
{
base.RemoveItem (index);
Option p = Items [index];
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i) {
Dictionary.Remove (p.Names [i]);
}
}
protected override void SetItem (int index, Option item)
{
base.SetItem (index, item);
RemoveItem (index);
AddImpl (item);
}
private void AddImpl (Option option)
{
if (option == null)
throw new ArgumentNullException ("option");
List<string> added = new List<string> (option.Names.Length);
try {
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i) {
Dictionary.Add (option.Names [i], option);
added.Add (option.Names [i]);
}
}
catch (Exception) {
foreach (string name in added)
Dictionary.Remove (name);
throw;
}
}
public new OptionSet Add (Option option)
{
base.Add (option);
return this;
}
sealed class ActionOption : Option {
Action<OptionValueCollection> action;
public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
: base (prototype, description, count)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (c.OptionValues);
}
}
public OptionSet Add (string prototype, Action<string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 1,
delegate (OptionValueCollection v) { action (v [0]); });
base.Add (p);
return this;
}
public OptionSet Add (string prototype, OptionAction<string, string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 2,
delegate (OptionValueCollection v) {action (v [0], v [1]);});
base.Add (p);
return this;
}
sealed class ActionOption<T> : Option {
Action<T> action;
public ActionOption (string prototype, string description, Action<T> action)
: base (prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (Parse<T> (c.OptionValues [0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option {
OptionAction<TKey, TValue> action;
public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
: base (prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<TKey> (c.OptionValues [0], c),
Parse<TValue> (c.OptionValues [1], c));
}
}
public OptionSet Add<T> (string prototype, Action<T> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<T> (string prototype, string description, Action<T> action)
{
return Add (new ActionOption<T> (prototype, description, action));
}
public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add (new ActionOption<TKey, TValue> (prototype, description, action));
}
protected virtual OptionContext CreateOptionContext ()
{
return new OptionContext (this);
}
#if LINQ
public List<string> Parse (IEnumerable<string> arguments)
{
bool process = true;
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
var def = GetOptionForName ("<>");
var unprocessed =
from argument in arguments
where ++c.OptionIndex >= 0 && (process || def != null)
? process
? argument == "--"
? (process = false)
: !Parse (argument, c)
? def != null
? Unprocessed (null, def, c, argument)
: true
: false
: def != null
? Unprocessed (null, def, c, argument)
: true
: true
select argument;
List<string> r = unprocessed.ToList ();
if (c.Option != null)
c.Option.Invoke (c);
return r;
}
#else
public List<string> Parse (IEnumerable<string> arguments)
{
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string> ();
Option def = Contains ("<>") ? this ["<>"] : null;
foreach (string argument in arguments) {
++c.OptionIndex;
if (argument == "--") {
process = false;
continue;
}
if (!process) {
Unprocessed (unprocessed, def, c, argument);
continue;
}
if (!Parse (argument, c))
Unprocessed (unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke (c);
return unprocessed;
}
#endif
private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null) {
extra.Add (argument);
return false;
}
c.OptionValues.Add (argument);
c.Option = def;
c.Option.Invoke (c);
return false;
}
private readonly Regex ValueOption = new Regex (
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException ("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match (argument);
if (!m.Success) {
return false;
}
flag = m.Groups ["flag"].Value;
name = m.Groups ["name"].Value;
if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
sep = m.Groups ["sep"].Value;
value = m.Groups ["value"].Value;
}
return true;
}
protected virtual bool Parse (string argument, OptionContext c)
{
if (c.Option != null) {
ParseValue (argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts (argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains (n)) {
p = this [n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType) {
case OptionValueType.None:
c.OptionValues.Add (n);
c.Option.Invoke (c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue (v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool (argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue (f, string.Concat (n + s + v), c))
return true;
return false;
}
private void ParseValue (string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split (c.Option.ValueSeparators, StringSplitOptions.None)
: new string[]{option}) {
c.OptionValues.Add (o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke (c);
else if (c.OptionValues.Count > c.Option.MaxValueCount) {
throw new OptionException (localizer (string.Format (
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool (string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
Contains ((rn = n.Substring (0, n.Length-1)))) {
p = this [rn];
string v = n [n.Length-1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add (v);
p.Invoke (c);
return true;
}
return false;
}
private bool ParseBundledValue (string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i) {
Option p;
string opt = f + n [i].ToString ();
string rn = n [i].ToString ();
if (!Contains (rn)) {
if (i == 0)
return false;
throw new OptionException (string.Format (localizer (
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this [rn];
switch (p.OptionValueType) {
case OptionValueType.None:
Invoke (c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required: {
string v = n.Substring (i+1);
c.Option = p;
c.OptionName = opt;
ParseValue (v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke (OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add (value);
option.Invoke (c);
}
private const int OptionWidth = 29;
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
bool indent = false;
string prefix = new string (' ', OptionWidth+2);
foreach (string line in GetLines (localizer (GetDescription (p.Description)))) {
if (indent)
o.Write (prefix);
o.WriteLine (line);
indent = true;
}
}
}
bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex (names, 0);
if (i == names.Length)
return false;
if (names [i].Length == 1) {
Write (o, ref written, " -");
Write (o, ref written, names [0]);
}
else {
Write (o, ref written, " --");
Write (o, ref written, names [0]);
}
for ( i = GetNextOptionIndex (names, i+1);
i < names.Length; i = GetNextOptionIndex (names, i+1)) {
Write (o, ref written, ", ");
Write (o, ref written, names [i].Length == 1 ? "-" : "--");
Write (o, ref written, names [i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required) {
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("["));
}
Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators [0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c) {
Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("]"));
}
}
return true;
}
static int GetNextOptionIndex (string[] names, int i)
{
while (i < names.Length && names [i] == "<>") {
++i;
}
return i;
}
static void Write (TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write (s);
}
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription (string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder (description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i) {
switch (description [i]) {
case '{':
if (i == start) {
sb.Append ('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0) {
if ((i+1) == description.Length || description [i+1] != '}')
throw new InvalidOperationException ("Invalid option description: " + description);
++i;
sb.Append ("}");
}
else {
sb.Append (description.Substring (start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append (description [i]);
break;
}
}
return sb.ToString ();
}
private static IEnumerable<string> GetLines (string description)
{
if (string.IsNullOrEmpty (description)) {
yield return string.Empty;
yield break;
}
int length = 80 - OptionWidth - 1;
int start = 0, end;
do {
end = GetLineEnd (start, length, description);
char c = description [end-1];
if (char.IsWhiteSpace (c))
--end;
bool writeContinuation = end != description.Length && !IsEolChar (c);
string line = description.Substring (start, end - start) +
(writeContinuation ? "-" : "");
yield return line;
start = end;
if (char.IsWhiteSpace (c))
++start;
length = 80 - OptionWidth - 2 - 1;
} while (end < description.Length);
}
private static bool IsEolChar (char c)
{
return !char.IsLetterOrDigit (c);
}
private static int GetLineEnd (int start, int length, string description)
{
int end = System.Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start+1; i < end; ++i) {
if (description [i] == '\n')
return i+1;
if (IsEolChar (description [i]))
sep = i+1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
using EIDSS.Reports.BaseControls.Report;
using EIDSS.Reports.Document.Human.CaseInvestigation;
namespace EIDSS.Reports.Document.Veterinary.LivestockInvestigation
{
partial class LivestockInvestigationReport
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LivestockInvestigationReport));
this.DetailReportInfo = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailInfo = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable4 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow19 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell56 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow22 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell58 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell61 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellBarcode = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.sp_rep_VET_LivestockCaseTableAdapter1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockInvestigationDataSetTableAdapters.sp_rep_VET_LivestockCaseTableAdapter();
this.livestockInvestigationDataSet1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockInvestigationDataSet();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReportHerd = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailHerd = new DevExpress.XtraReports.UI.DetailBand();
this.xrSubreport1 = new DevExpress.XtraReports.UI.XRSubreport();
this.herdReport1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdReport();
this.DetailReportClinical = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailClinical = new DevExpress.XtraReports.UI.DetailBand();
this.ClinicalInvestigationSubreport = new DevExpress.XtraReports.UI.XRSubreport();
this.ReportHeaderClinical = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel2 = new DevExpress.XtraReports.UI.XRLabel();
this.DetailReportEpi = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailEpi = new DevExpress.XtraReports.UI.DetailBand();
this.EpiSubreport = new DevExpress.XtraReports.UI.XRSubreport();
this.reportHeaderBand1 = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel3 = new DevExpress.XtraReports.UI.XRLabel();
this.DetailReportVaccinations = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailVaccinations = new DevExpress.XtraReports.UI.DetailBand();
this.xrSubreport4 = new DevExpress.XtraReports.UI.XRSubreport();
this.vaccinationReport1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.VaccinationReport();
this.DetailReportRapidTest = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailRapidTest = new DevExpress.XtraReports.UI.DetailBand();
this.xrSubreport5 = new DevExpress.XtraReports.UI.XRSubreport();
this.rapidTestReport1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.RapidTestReport();
this.DetailReportDiagnosis = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailDiagnosis = new DevExpress.XtraReports.UI.DetailBand();
this.xrSubreport6 = new DevExpress.XtraReports.UI.XRSubreport();
this.diagnosisReport1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.DiagnosisReport();
this.DetailReportOutbreak = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailOutbreak = new DevExpress.XtraReports.UI.DetailBand();
this.xrLabel4 = new DevExpress.XtraReports.UI.XRLabel();
this.ControlMeasuresSubreport = new DevExpress.XtraReports.UI.XRSubreport();
this.DetailReportSample = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailSample = new DevExpress.XtraReports.UI.DetailBand();
this.xrSubreport8 = new DevExpress.XtraReports.UI.XRSubreport();
this.sampleReport1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockAnimalCSReport();
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.livestockInvestigationDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.herdReport1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.vaccinationReport1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rapidTestReport1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.diagnosisReport1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.sampleReport1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
this.PageFooter.StylePriority.UseBorders = false;
//
// xrPageInfo1
//
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
//
// tableBaseHeader
//
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// DetailReportInfo
//
this.DetailReportInfo.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailInfo});
this.DetailReportInfo.DataAdapter = this.sp_rep_VET_LivestockCaseTableAdapter1;
this.DetailReportInfo.DataMember = "spRepVetLivestockCase";
this.DetailReportInfo.DataSource = this.livestockInvestigationDataSet1;
resources.ApplyResources(this.DetailReportInfo, "DetailReportInfo");
this.DetailReportInfo.Level = 0;
this.DetailReportInfo.Name = "DetailReportInfo";
//
// DetailInfo
//
this.DetailInfo.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable4,
this.xrTable2,
this.xrTable1});
resources.ApplyResources(this.DetailInfo, "DetailInfo");
this.DetailInfo.Name = "DetailInfo";
this.DetailInfo.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.DetailInfo.StylePriority.UsePadding = false;
this.DetailInfo.StylePriority.UseTextAlignment = false;
//
// xrTable4
//
resources.ApplyResources(this.xrTable4, "xrTable4");
this.xrTable4.Name = "xrTable4";
this.xrTable4.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow20});
this.xrTable4.StylePriority.UseBorders = false;
this.xrTable4.StylePriority.UseTextAlignment = false;
//
// xrTableRow20
//
this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell14,
this.xrTableCell20});
this.xrTableRow20.Name = "xrTableRow20";
this.xrTableRow20.StylePriority.UseBorders = false;
this.xrTableRow20.StylePriority.UseFont = false;
this.xrTableRow20.Weight = 1D;
//
// xrTableCell14
//
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Weight = 0.752258064516129D;
//
// xrTableCell20
//
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.OwnershipType")});
this.xrTableCell20.Multiline = true;
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseBorders = false;
this.xrTableCell20.Weight = 2.2477419354838712D;
//
// xrTable2
//
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow3,
this.xrTableRow19,
this.xrTableRow18,
this.xrTableRow17,
this.xrTableRow16,
this.xrTableRow15,
this.xrTableRow14,
this.xrTableRow13,
this.xrTableRow12,
this.xrTableRow11,
this.xrTableRow10,
this.xrTableRow5,
this.xrTableRow22});
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2,
this.xrTableCell9,
this.xrTableCell3,
this.xrTableCell8});
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.Weight = 0.65999999999999992D;
//
// xrTableCell2
//
this.xrTableCell2.Name = "xrTableCell2";
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Weight = 0.752258064516129D;
//
// xrTableCell9
//
this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.ReportedName")});
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.Weight = 0.75161290322580654D;
//
// xrTableCell3
//
this.xrTableCell3.Name = "xrTableCell3";
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Weight = 0.75161290322580643D;
//
// xrTableCell8
//
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.InvestigationName")});
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.Weight = 0.74451612903225806D;
//
// xrTableRow19
//
this.xrTableRow19.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell55,
this.xrTableCell56,
this.xrTableCell57,
this.xrTableCell59});
this.xrTableRow19.Name = "xrTableRow19";
this.xrTableRow19.Weight = 0.65999999999999992D;
//
// xrTableCell55
//
this.xrTableCell55.Name = "xrTableCell55";
resources.ApplyResources(this.xrTableCell55, "xrTableCell55");
this.xrTableCell55.Weight = 0.752258064516129D;
//
// xrTableCell56
//
this.xrTableCell56.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.ReportedDate", "{0:dd/MM/yyyy}")});
this.xrTableCell56.Name = "xrTableCell56";
this.xrTableCell56.Weight = 0.75161290322580654D;
//
// xrTableCell57
//
this.xrTableCell57.Name = "xrTableCell57";
resources.ApplyResources(this.xrTableCell57, "xrTableCell57");
this.xrTableCell57.Weight = 0.75161290322580643D;
//
// xrTableCell59
//
this.xrTableCell59.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.AssignedDate", "{0:dd/MM/yyyy}")});
this.xrTableCell59.Name = "xrTableCell59";
this.xrTableCell59.Weight = 0.74451612903225806D;
//
// xrTableRow18
//
this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell51,
this.xrTableCell52,
this.xrTableCell53,
this.xrTableCell54});
this.xrTableRow18.Name = "xrTableRow18";
this.xrTableRow18.Weight = 0.65999999999999992D;
//
// xrTableCell51
//
this.xrTableCell51.Name = "xrTableCell51";
resources.ApplyResources(this.xrTableCell51, "xrTableCell51");
this.xrTableCell51.Weight = 0.752258064516129D;
//
// xrTableCell52
//
this.xrTableCell52.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.EnteredName")});
this.xrTableCell52.Name = "xrTableCell52";
this.xrTableCell52.Weight = 0.75161290322580654D;
//
// xrTableCell53
//
this.xrTableCell53.Name = "xrTableCell53";
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
this.xrTableCell53.Weight = 0.75161290322580643D;
//
// xrTableCell54
//
this.xrTableCell54.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.DateOfInvestigation", "{0:dd/MM/yyyy}")});
this.xrTableCell54.Name = "xrTableCell54";
this.xrTableCell54.Weight = 0.74451612903225806D;
//
// xrTableRow17
//
this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell47,
this.xrTableCell48,
this.xrTableCell49,
this.xrTableCell50});
this.xrTableRow17.Name = "xrTableRow17";
this.xrTableRow17.Weight = 0.65999999999999992D;
//
// xrTableCell47
//
this.xrTableCell47.Name = "xrTableCell47";
resources.ApplyResources(this.xrTableCell47, "xrTableCell47");
this.xrTableCell47.Weight = 0.752258064516129D;
//
// xrTableCell48
//
this.xrTableCell48.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.DataEntryDate", "{0:dd/MM/yyyy}")});
this.xrTableCell48.Name = "xrTableCell48";
this.xrTableCell48.Weight = 0.75161290322580654D;
//
// xrTableCell49
//
this.xrTableCell49.Name = "xrTableCell49";
this.xrTableCell49.Weight = 0.75161290322580643D;
//
// xrTableCell50
//
this.xrTableCell50.Name = "xrTableCell50";
this.xrTableCell50.Weight = 0.74451612903225806D;
//
// xrTableRow16
//
this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell45});
this.xrTableRow16.Name = "xrTableRow16";
this.xrTableRow16.Weight = 0.65999999999999992D;
//
// xrTableCell45
//
resources.ApplyResources(this.xrTableCell45, "xrTableCell45");
this.xrTableCell45.Name = "xrTableCell45";
this.xrTableCell45.StylePriority.UseFont = false;
this.xrTableCell45.Weight = 3.0000000000000004D;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell38,
this.xrTableCell39,
this.xrTableCell40,
this.xrTableCell41});
this.xrTableRow15.Name = "xrTableRow15";
this.xrTableRow15.Weight = 0.65999999999999992D;
//
// xrTableCell38
//
resources.ApplyResources(this.xrTableCell38, "xrTableCell38");
this.xrTableCell38.Name = "xrTableCell38";
this.xrTableCell38.StylePriority.UseFont = false;
this.xrTableCell38.Weight = 0.752258064516129D;
//
// xrTableCell39
//
this.xrTableCell39.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmName")});
this.xrTableCell39.Name = "xrTableCell39";
this.xrTableCell39.Weight = 0.75161290322580654D;
//
// xrTableCell40
//
this.xrTableCell40.Name = "xrTableCell40";
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
this.xrTableCell40.Weight = 0.75161290322580643D;
//
// xrTableCell41
//
this.xrTableCell41.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmRegion")});
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.Weight = 0.74451612903225806D;
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell34,
this.xrTableCell35,
this.xrTableCell36,
this.xrTableCell37});
this.xrTableRow14.Name = "xrTableRow14";
this.xrTableRow14.Weight = 0.65999999999999992D;
//
// xrTableCell34
//
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseFont = false;
this.xrTableCell34.Weight = 0.752258064516129D;
//
// xrTableCell35
//
this.xrTableCell35.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmCode")});
this.xrTableCell35.Name = "xrTableCell35";
this.xrTableCell35.Weight = 0.75161290322580654D;
//
// xrTableCell36
//
this.xrTableCell36.Name = "xrTableCell36";
resources.ApplyResources(this.xrTableCell36, "xrTableCell36");
this.xrTableCell36.Weight = 0.75161290322580643D;
//
// xrTableCell37
//
this.xrTableCell37.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmRayon")});
this.xrTableCell37.Name = "xrTableCell37";
this.xrTableCell37.Weight = 0.74451612903225806D;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell30,
this.xrTableCell31,
this.xrTableCell32,
this.xrTableCell33});
this.xrTableRow13.Name = "xrTableRow13";
this.xrTableRow13.Weight = 0.65999999999999992D;
//
// xrTableCell30
//
this.xrTableCell30.Name = "xrTableCell30";
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Weight = 0.752258064516129D;
//
// xrTableCell31
//
this.xrTableCell31.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmerName")});
this.xrTableCell31.Name = "xrTableCell31";
this.xrTableCell31.Weight = 0.75161290322580654D;
//
// xrTableCell32
//
this.xrTableCell32.Name = "xrTableCell32";
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
this.xrTableCell32.Weight = 0.75161290322580643D;
//
// xrTableCell33
//
this.xrTableCell33.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.Settlement")});
this.xrTableCell33.Name = "xrTableCell33";
this.xrTableCell33.Weight = 0.74451612903225806D;
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell26,
this.xrTableCell27,
this.xrTableCell28,
this.xrTableCell29});
this.xrTableRow12.Name = "xrTableRow12";
this.xrTableRow12.Weight = 0.65999999999999992D;
//
// xrTableCell26
//
this.xrTableCell26.Name = "xrTableCell26";
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Weight = 0.752258064516129D;
//
// xrTableCell27
//
this.xrTableCell27.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmPhone")});
this.xrTableCell27.Name = "xrTableCell27";
this.xrTableCell27.Weight = 0.75161290322580654D;
//
// xrTableCell28
//
this.xrTableCell28.Name = "xrTableCell28";
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
this.xrTableCell28.Weight = 0.75161290322580643D;
//
// xrTableCell29
//
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.Weight = 0.74451612903225806D;
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell22,
this.xrTableCell23,
this.xrTableCell25});
this.xrTableRow11.Name = "xrTableRow11";
this.xrTableRow11.Weight = 0.65999999999999992D;
//
// xrTableCell22
//
this.xrTableCell22.Name = "xrTableCell22";
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Weight = 0.752258064516129D;
//
// xrTableCell23
//
this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmFax")});
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.Weight = 0.75161290322580654D;
//
// xrTableCell25
//
this.xrTableCell25.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmAddress")});
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.Weight = 1.4961290322580645D;
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell18,
this.xrTableCell19,
this.xrTableCell21});
this.xrTableRow10.Name = "xrTableRow10";
this.xrTableRow10.Weight = 0.65999999999999992D;
//
// xrTableCell18
//
this.xrTableCell18.Name = "xrTableCell18";
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Weight = 0.752258064516129D;
//
// xrTableCell19
//
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmEMail")});
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.Weight = 0.75161290322580654D;
//
// xrTableCell21
//
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.Weight = 1.4961290322580645D;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell16});
this.xrTableRow5.Name = "xrTableRow5";
this.xrTableRow5.Weight = 0.65999999999999992D;
//
// xrTableCell16
//
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.StylePriority.UseFont = false;
this.xrTableCell16.Weight = 3.0000000000000004D;
//
// xrTableRow22
//
this.xrTableRow22.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell60,
this.xrTableCell58,
this.xrTableCell61,
this.xrTableCell44});
this.xrTableRow22.Name = "xrTableRow22";
this.xrTableRow22.Weight = 0.65999999999999992D;
//
// xrTableCell60
//
this.xrTableCell60.Name = "xrTableCell60";
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
this.xrTableCell60.Weight = 0.75000000000000011D;
//
// xrTableCell58
//
this.xrTableCell58.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmLatitude")});
this.xrTableCell58.Name = "xrTableCell58";
this.xrTableCell58.Weight = 0.75000000000000011D;
//
// xrTableCell61
//
this.xrTableCell61.Name = "xrTableCell61";
resources.ApplyResources(this.xrTableCell61, "xrTableCell61");
this.xrTableCell61.Weight = 0.75000000000000011D;
//
// xrTableCell44
//
this.xrTableCell44.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmLongitude")});
this.xrTableCell44.Name = "xrTableCell44";
this.xrTableCell44.Weight = 0.75000000000000011D;
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow2});
this.xrTable1.StylePriority.UseFont = false;
this.xrTable1.StylePriority.UsePadding = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1,
this.cellBarcode,
this.xrTableCell4});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 0.84D;
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Multiline = true;
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseFont = false;
this.xrTableCell1.Weight = 0.85747610536804086D;
//
// cellBarcode
//
this.cellBarcode.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.CaseIdentifier", "*{0}*")});
resources.ApplyResources(this.cellBarcode, "cellBarcode");
this.cellBarcode.Name = "cellBarcode";
this.cellBarcode.StylePriority.UseFont = false;
this.cellBarcode.StylePriority.UseTextAlignment = false;
this.cellBarcode.Weight = 1.1956392421223068D;
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.Padding = new DevExpress.XtraPrinting.PaddingInfo(20, 2, 2, 2, 100F);
this.xrTableCell4.StylePriority.UseFont = false;
this.xrTableCell4.StylePriority.UsePadding = false;
this.xrTableCell4.Weight = 1.3704102316602316D;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6,
this.xrTableCell7});
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.Weight = 0.65999999999999992D;
//
// xrTableCell5
//
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.Weight = 0.85747610536804086D;
//
// xrTableCell6
//
this.xrTableCell6.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.CaseIdentifier")});
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseBorders = false;
this.xrTableCell6.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Weight = 1.1956392421223068D;
//
// xrTableCell7
//
this.xrTableCell7.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FieldAccessionID")});
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.Padding = new DevExpress.XtraPrinting.PaddingInfo(20, 2, 2, 2, 100F);
this.xrTableCell7.StylePriority.UsePadding = false;
this.xrTableCell7.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Weight = 1.3704102316602316D;
//
// sp_rep_VET_LivestockCaseTableAdapter1
//
this.sp_rep_VET_LivestockCaseTableAdapter1.ClearBeforeFill = true;
//
// livestockInvestigationDataSet1
//
this.livestockInvestigationDataSet1.DataSetName = "LivestockInvestigationDataSet";
this.livestockInvestigationDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// xrTableCell10
//
this.xrTableCell10.Name = "xrTableCell10";
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Weight = 0.752258064516129D;
//
// xrTableCell11
//
this.xrTableCell11.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmLatitude", "{0:#.00}")});
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.Weight = 0.75161290322580654D;
//
// xrTableCell12
//
this.xrTableCell12.Name = "xrTableCell12";
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Weight = 0.75161290322580643D;
//
// xrTableCell13
//
this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmLongitude", "{0:#.00}")});
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.Weight = 0.74451612903225806D;
//
// DetailReportHerd
//
this.DetailReportHerd.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailHerd});
this.DetailReportHerd.Level = 1;
this.DetailReportHerd.Name = "DetailReportHerd";
//
// DetailHerd
//
this.DetailHerd.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreport1});
resources.ApplyResources(this.DetailHerd, "DetailHerd");
this.DetailHerd.Name = "DetailHerd";
this.DetailHerd.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrSubreport1
//
resources.ApplyResources(this.xrSubreport1, "xrSubreport1");
this.xrSubreport1.Name = "xrSubreport1";
this.xrSubreport1.ReportSource = this.herdReport1;
//
// DetailReportClinical
//
this.DetailReportClinical.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailClinical,
this.ReportHeaderClinical});
this.DetailReportClinical.Level = 2;
this.DetailReportClinical.Name = "DetailReportClinical";
//
// DetailClinical
//
this.DetailClinical.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.ClinicalInvestigationSubreport});
resources.ApplyResources(this.DetailClinical, "DetailClinical");
this.DetailClinical.Name = "DetailClinical";
//
// ClinicalInvestigationSubreport
//
resources.ApplyResources(this.ClinicalInvestigationSubreport, "ClinicalInvestigationSubreport");
this.ClinicalInvestigationSubreport.Name = "ClinicalInvestigationSubreport";
//
// ReportHeaderClinical
//
this.ReportHeaderClinical.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel2});
resources.ApplyResources(this.ReportHeaderClinical, "ReportHeaderClinical");
this.ReportHeaderClinical.Name = "ReportHeaderClinical";
this.ReportHeaderClinical.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrLabel2
//
this.xrLabel2.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel2, "xrLabel2");
this.xrLabel2.Name = "xrLabel2";
this.xrLabel2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel2.StylePriority.UseBorders = false;
this.xrLabel2.StylePriority.UseFont = false;
this.xrLabel2.StylePriority.UseTextAlignment = false;
//
// DetailReportEpi
//
this.DetailReportEpi.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailEpi,
this.reportHeaderBand1});
this.DetailReportEpi.Level = 3;
this.DetailReportEpi.Name = "DetailReportEpi";
//
// DetailEpi
//
this.DetailEpi.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.EpiSubreport});
resources.ApplyResources(this.DetailEpi, "DetailEpi");
this.DetailEpi.Name = "DetailEpi";
//
// EpiSubreport
//
resources.ApplyResources(this.EpiSubreport, "EpiSubreport");
this.EpiSubreport.Name = "EpiSubreport";
//
// reportHeaderBand1
//
this.reportHeaderBand1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel3});
resources.ApplyResources(this.reportHeaderBand1, "reportHeaderBand1");
this.reportHeaderBand1.Name = "reportHeaderBand1";
this.reportHeaderBand1.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrLabel3
//
this.xrLabel3.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel3, "xrLabel3");
this.xrLabel3.Name = "xrLabel3";
this.xrLabel3.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel3.StylePriority.UseBorders = false;
this.xrLabel3.StylePriority.UseFont = false;
this.xrLabel3.StylePriority.UseTextAlignment = false;
//
// DetailReportVaccinations
//
this.DetailReportVaccinations.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailVaccinations});
this.DetailReportVaccinations.Level = 4;
this.DetailReportVaccinations.Name = "DetailReportVaccinations";
//
// DetailVaccinations
//
this.DetailVaccinations.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreport4});
resources.ApplyResources(this.DetailVaccinations, "DetailVaccinations");
this.DetailVaccinations.Name = "DetailVaccinations";
this.DetailVaccinations.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrSubreport4
//
resources.ApplyResources(this.xrSubreport4, "xrSubreport4");
this.xrSubreport4.Name = "xrSubreport4";
this.xrSubreport4.ReportSource = this.vaccinationReport1;
//
// DetailReportRapidTest
//
this.DetailReportRapidTest.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailRapidTest});
this.DetailReportRapidTest.Level = 5;
this.DetailReportRapidTest.Name = "DetailReportRapidTest";
//
// DetailRapidTest
//
this.DetailRapidTest.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreport5});
resources.ApplyResources(this.DetailRapidTest, "DetailRapidTest");
this.DetailRapidTest.Name = "DetailRapidTest";
this.DetailRapidTest.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrSubreport5
//
resources.ApplyResources(this.xrSubreport5, "xrSubreport5");
this.xrSubreport5.Name = "xrSubreport5";
this.xrSubreport5.ReportSource = this.rapidTestReport1;
//
// DetailReportDiagnosis
//
this.DetailReportDiagnosis.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailDiagnosis});
this.DetailReportDiagnosis.Level = 6;
this.DetailReportDiagnosis.Name = "DetailReportDiagnosis";
//
// DetailDiagnosis
//
this.DetailDiagnosis.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreport6});
resources.ApplyResources(this.DetailDiagnosis, "DetailDiagnosis");
this.DetailDiagnosis.Name = "DetailDiagnosis";
this.DetailDiagnosis.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrSubreport6
//
resources.ApplyResources(this.xrSubreport6, "xrSubreport6");
this.xrSubreport6.Name = "xrSubreport6";
this.xrSubreport6.ReportSource = this.diagnosisReport1;
//
// DetailReportOutbreak
//
this.DetailReportOutbreak.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailOutbreak});
this.DetailReportOutbreak.Level = 7;
this.DetailReportOutbreak.Name = "DetailReportOutbreak";
//
// DetailOutbreak
//
this.DetailOutbreak.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel4,
this.ControlMeasuresSubreport});
resources.ApplyResources(this.DetailOutbreak, "DetailOutbreak");
this.DetailOutbreak.Name = "DetailOutbreak";
this.DetailOutbreak.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrLabel4
//
this.xrLabel4.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel4, "xrLabel4");
this.xrLabel4.Name = "xrLabel4";
this.xrLabel4.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel4.StylePriority.UseBorders = false;
this.xrLabel4.StylePriority.UseFont = false;
this.xrLabel4.StylePriority.UseTextAlignment = false;
//
// ControlMeasuresSubreport
//
resources.ApplyResources(this.ControlMeasuresSubreport, "ControlMeasuresSubreport");
this.ControlMeasuresSubreport.Name = "ControlMeasuresSubreport";
//
// DetailReportSample
//
this.DetailReportSample.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailSample});
this.DetailReportSample.Level = 8;
this.DetailReportSample.Name = "DetailReportSample";
//
// DetailSample
//
this.DetailSample.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreport8});
resources.ApplyResources(this.DetailSample, "DetailSample");
this.DetailSample.Name = "DetailSample";
this.DetailSample.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrSubreport8
//
resources.ApplyResources(this.xrSubreport8, "xrSubreport8");
this.xrSubreport8.Name = "xrSubreport8";
this.xrSubreport8.ReportSource = this.sampleReport1;
//
// LivestockInvestigationReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReportInfo,
this.DetailReportHerd,
this.DetailReportClinical,
this.DetailReportEpi,
this.DetailReportVaccinations,
this.DetailReportRapidTest,
this.DetailReportDiagnosis,
this.DetailReportOutbreak,
this.DetailReportSample});
this.Version = "11.1";
this.Controls.SetChildIndex(this.DetailReportSample, 0);
this.Controls.SetChildIndex(this.DetailReportOutbreak, 0);
this.Controls.SetChildIndex(this.DetailReportDiagnosis, 0);
this.Controls.SetChildIndex(this.DetailReportRapidTest, 0);
this.Controls.SetChildIndex(this.DetailReportVaccinations, 0);
this.Controls.SetChildIndex(this.DetailReportEpi, 0);
this.Controls.SetChildIndex(this.DetailReportClinical, 0);
this.Controls.SetChildIndex(this.DetailReportHerd, 0);
this.Controls.SetChildIndex(this.DetailReportInfo, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.livestockInvestigationDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.herdReport1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.vaccinationReport1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rapidTestReport1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.diagnosisReport1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.sampleReport1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailReportBand DetailReportInfo;
private DevExpress.XtraReports.UI.DetailBand DetailInfo;
private EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockInvestigationDataSetTableAdapters.sp_rep_VET_LivestockCaseTableAdapter sp_rep_VET_LivestockCaseTableAdapter1;
private LivestockInvestigationDataSet livestockInvestigationDataSet1;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell cellBarcode;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell55;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell56;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell57;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell59;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell51;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell52;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell54;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell47;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell50;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell45;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell38;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell39;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell40;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell35;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell36;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell37;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTable xrTable4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportHerd;
private DevExpress.XtraReports.UI.DetailBand DetailHerd;
private DevExpress.XtraReports.UI.XRSubreport xrSubreport1;
private HerdReport herdReport1;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportClinical;
private DevExpress.XtraReports.UI.DetailBand DetailClinical;
private DevExpress.XtraReports.UI.XRSubreport ClinicalInvestigationSubreport;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportEpi;
private DevExpress.XtraReports.UI.DetailBand DetailEpi;
private DevExpress.XtraReports.UI.XRSubreport EpiSubreport;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportVaccinations;
private DevExpress.XtraReports.UI.DetailBand DetailVaccinations;
private DevExpress.XtraReports.UI.XRSubreport xrSubreport4;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportRapidTest;
private DevExpress.XtraReports.UI.DetailBand DetailRapidTest;
private DevExpress.XtraReports.UI.XRSubreport xrSubreport5;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportDiagnosis;
private DevExpress.XtraReports.UI.DetailBand DetailDiagnosis;
private DevExpress.XtraReports.UI.XRSubreport xrSubreport6;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportOutbreak;
private DevExpress.XtraReports.UI.DetailBand DetailOutbreak;
private DevExpress.XtraReports.UI.XRSubreport ControlMeasuresSubreport;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportSample;
private DevExpress.XtraReports.UI.DetailBand DetailSample;
private DevExpress.XtraReports.UI.XRSubreport xrSubreport8;
private VaccinationReport vaccinationReport1;
private RapidTestReport rapidTestReport1;
private DiagnosisReport diagnosisReport1;
private LivestockAnimalCSReport sampleReport1;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeaderClinical;
private DevExpress.XtraReports.UI.XRLabel xrLabel2;
private DevExpress.XtraReports.UI.ReportHeaderBand reportHeaderBand1;
private DevExpress.XtraReports.UI.XRLabel xrLabel3;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell60;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell58;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell61;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell44;
private DevExpress.XtraReports.UI.XRLabel xrLabel4;
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Text;
using System.Xml;
public static class PsdLayerPrefs
{
public static bool verbose = true;
private static string filePath;
private static XmlDocument xml = new XmlDocument();
private static XmlNode root;
static PsdLayerPrefs()
{
var pathes = Directory.GetFiles(Directory.GetCurrentDirectory(), "PsdLayerPrefs.cs", SearchOption.AllDirectories);
PsdLayerPrefs.filePath = Path.GetDirectoryName(pathes[0]) + "/PsdLayerPrefs.xml";
if (File.Exists(PsdLayerPrefs.filePath))
{
PsdLayerPrefs.xml.Load(PsdLayerPrefs.filePath);
}
else
{
var node = PsdLayerPrefs.xml.CreateNode(XmlNodeType.Element, "Keys", null);
PsdLayerPrefs.xml.AppendChild(node);
PsdLayerPrefs.xml.Save(PsdLayerPrefs.filePath);
}
PsdLayerPrefs.root = PsdLayerPrefs.xml.DocumentElement;
}
public static void Load()
{
PsdLayerPrefs.xml.Load(PsdLayerPrefs.filePath);
}
public static void Save()
{
PsdLayerPrefs.xml.Save(PsdLayerPrefs.filePath);
}
public static bool HasKey(string key)
{
try
{
var node = PsdLayerPrefs.root.SelectSingleNode("//Key[@Name='" + key + "']");
return node != null;
}
catch (Exception e)
{
if (PsdLayerPrefs.verbose)
Debug.LogError(e.Message);
return false;
}
}
public static bool DeleteKey(string key)
{
try
{
var node = PsdLayerPrefs.root.SelectSingleNode("//Key[@Name='" + key + "']");
PsdLayerPrefs.root.RemoveChild(node);
return node != null;
}
catch (Exception e)
{
if (PsdLayerPrefs.verbose)
Debug.LogError(e.Message);
return false;
}
}
#region Default SetTypes
public static bool SetInt(string key, int v)
{
return PsdLayerPrefs.SetString(key, v.ToString());
}
public static bool SetFloat(string key, float v)
{
return PsdLayerPrefs.SetString(key, v.ToString());
}
public static bool SetString(string key, string v)
{
try
{
var child = PsdLayerPrefs.xml.CreateNode(XmlNodeType.Element, "Key", null);
var name = PsdLayerPrefs.xml.CreateAttribute("Name");
var val = PsdLayerPrefs.xml.CreateAttribute("Value");
name.Value = key;
val.Value = v;
child.Attributes.Append(name);
child.Attributes.Append(val);
var node = PsdLayerPrefs.root.SelectSingleNode("//Key[@Name='" + key + "']");
if (node != null)
node = PsdLayerPrefs.root.ReplaceChild(child, node);
else
node = PsdLayerPrefs.root.AppendChild(child);
PsdLayerPrefs.Save();
}
catch (Exception e)
{
if (PsdLayerPrefs.verbose)
Debug.LogError(e.Message);
return false;
}
return true;
}
#endregion
#region Default GetTypes
public static int GetInt(string key)
{
return PsdLayerPrefs.GetInt(key, 0);
}
public static float GetFloat(string key)
{
return PsdLayerPrefs.GetFloat(key, 0);
}
public static string GetString(string key)
{
return PsdLayerPrefs.GetString(key, "");
}
public static int GetInt(string key, int defaultValue)
{
var ret = PsdLayerPrefs.GetString(key);
return !string.IsNullOrEmpty(ret) ? int.Parse(ret) : defaultValue;
}
public static float GetFloat(string key, float defaultValue)
{
var ret = PsdLayerPrefs.GetString(key);
return !string.IsNullOrEmpty(ret) ? float.Parse(ret) : defaultValue;
}
public static string GetString(string key, string defaultValue)
{
try
{
var node = PsdLayerPrefs.root.SelectSingleNode("//Key[@Name='" + key + "']");
return node != null ? node.Attributes["Value"].Value : defaultValue;
}
catch (Exception e)
{
if (PsdLayerPrefs.verbose)
Debug.LogError(e.Message);
return defaultValue;
}
}
#endregion
#region String Array
public static bool SetStringArray(string key, char separator, params string[] strings)
{
try
{
if (strings.Length == 0)
PsdLayerPrefs.SetString(key, "");
else
PsdLayerPrefs.SetString(key, string.Join(separator.ToString(), strings));
}
catch (Exception e)
{
if (PsdLayerPrefs.verbose)
Debug.LogError(e.Message);
return false;
}
return true;
}
public static bool SetStringArray(string key, params string[] strings)
{
if (!PsdLayerPrefs.SetStringArray(key, "\n"[0], strings))
return false;
return true;
}
public static string[] GetStringArray(string key, char separator)
{
if (PsdLayerPrefs.HasKey(key))
return PsdLayerPrefs.GetString(key).Split(separator);
return new string[0];
}
public static string[] GetStringArray(string key)
{
if (PsdLayerPrefs.HasKey(key))
return PsdLayerPrefs.GetString(key).Split("\n"[0]);
return new string[0];
}
public static string[] GetStringArray(string key, char separator, string defaultValue, int defaultSize)
{
if (PsdLayerPrefs.HasKey(key))
return PsdLayerPrefs.GetString(key).Split(separator);
var strings = new string[defaultSize];
for (int i = 0; i < defaultSize; i++)
strings[i] = defaultValue;
return strings;
}
public static string[] GetStringArray(string key, string defaultValue, int defaultSize)
{
return PsdLayerPrefs.GetStringArray(key, "\n"[0], defaultValue, defaultSize);
}
#endregion
};
| |
#region License
//
// Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Exceptions;
using FluentMigrator.Runner.Infrastructure;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Tests.Integration.Migrations;
using FluentMigrator.Tests.Integration.Migrations.Constrained.Constraints;
using FluentMigrator.Tests.Integration.Migrations.Constrained.ConstraintsMultiple;
using FluentMigrator.Tests.Integration.Migrations.Constrained.ConstraintsSuccess;
using FluentMigrator.Tests.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit
{
[TestFixture]
public class MigrationRunnerTests
{
private Mock<IStopWatch> _stopWatch;
private Mock<IMigrationProcessor> _processorMock;
private Mock<IMigrationInformationLoader> _migrationLoaderMock;
private Mock<IProfileLoader> _profileLoaderMock;
private Mock<IAssemblySource> _assemblySourceMock;
private Mock<IMigrationScopeManager> _migrationScopeHandlerMock;
private ICollection<string> _logMessages;
private SortedList<long, IMigrationInfo> _migrationList;
private TestVersionLoader _fakeVersionLoader;
private int _applicationContext;
private IServiceCollection _serviceCollection;
[SetUp]
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetUp()
{
var asm = Assembly.GetExecutingAssembly();
_applicationContext = new Random().Next();
_migrationList = new SortedList<long, IMigrationInfo>();
_processorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose);
_migrationLoaderMock = new Mock<IMigrationInformationLoader>(MockBehavior.Loose);
_profileLoaderMock = new Mock<IProfileLoader>(MockBehavior.Loose);
_migrationScopeHandlerMock = new Mock<IMigrationScopeManager>(MockBehavior.Loose);
_migrationScopeHandlerMock.Setup(x => x.CreateOrWrapMigrationScope(It.IsAny<bool>())).Returns(new NoOpMigrationScope());
_stopWatch = new Mock<IStopWatch>();
_stopWatch.Setup(x => x.Time(It.IsAny<Action>())).Returns(new TimeSpan(1)).Callback((Action a) => a.Invoke());
_assemblySourceMock = new Mock<IAssemblySource>();
_assemblySourceMock.SetupGet(x => x.Assemblies).Returns(new[] { asm });
_migrationLoaderMock.Setup(x => x.LoadMigrations()).Returns(()=> _migrationList);
_logMessages = new List<string>();
var connectionString = IntegrationTestOptions.SqlServer2008.ConnectionString;
_serviceCollection = ServiceCollectionExtensions.CreateServices()
.WithProcessor(_processorMock)
.AddSingleton<ILoggerProvider>(new TextLineLoggerProvider(_logMessages, new FluentMigratorLoggerOptions() { ShowElapsedTime = true }))
.AddSingleton(_stopWatch.Object)
.AddSingleton(_assemblySourceMock.Object)
.AddSingleton(_migrationLoaderMock.Object)
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader(connectionString))
.AddScoped(_ => _profileLoaderMock.Object)
#pragma warning disable 612
.Configure<RunnerOptions>(opt => opt.ApplicationContext = _applicationContext)
#pragma warning restore 612
.Configure<ProcessorOptions>(
opt => opt.ConnectionString = connectionString)
.Configure<AssemblySourceOptions>(opt => opt.AssemblyNames = new []{ asm.FullName })
.Configure<TypeFilterOptions>(
opt => opt.Namespace = "FluentMigrator.Tests.Integration.Migrations")
.ConfigureRunner(builder => builder.WithRunnerConventions(new CustomMigrationConventions()));
}
private MigrationRunner CreateRunner(Action<IServiceCollection> initAction = null)
{
initAction?.Invoke(_serviceCollection);
var serviceProvider = _serviceCollection
.BuildServiceProvider();
var runner = (MigrationRunner) serviceProvider.GetRequiredService<IMigrationRunner>();
_fakeVersionLoader = new TestVersionLoader(runner, runner.VersionLoader.VersionTableMetaData);
runner.VersionLoader = _fakeVersionLoader;
var readTableDataResult = new DataSet();
readTableDataResult.Tables.Add(new DataTable());
_processorMock.Setup(x => x.ReadTableData(It.IsAny<string>(), It.IsAny<string>()))
.Returns(readTableDataResult);
_processorMock.Setup(x => x.SchemaExists(It.Is<string>(s => s == runner.VersionLoader.VersionTableMetaData.SchemaName)))
.Returns(true);
_processorMock.Setup(x => x.TableExists(It.Is<string>(s => s == runner.VersionLoader.VersionTableMetaData.SchemaName),
It.Is<string>(t => t == runner.VersionLoader.VersionTableMetaData.TableName)))
.Returns(true);
return runner;
}
private void LoadVersionData(params long[] fakeVersions)
{
_fakeVersionLoader.Versions.Clear();
_migrationList.Clear();
foreach (var version in fakeVersions)
{
_fakeVersionLoader.Versions.Add(version);
_migrationList.Add(version,new MigrationInfo(version, TransactionBehavior.Default, new TestMigration()));
}
_fakeVersionLoader.LoadVersionInfo();
}
[Test]
public void ProfilesAreAppliedWhenMigrateUpIsCalledWithNoVersion()
{
var runner = CreateRunner();
runner.MigrateUp();
_profileLoaderMock.Verify(x => x.ApplyProfiles(runner), Times.Once());
}
[Test]
public void ProfilesAreAppliedWhenMigrateUpIsCalledWithVersionParameter()
{
var runner = CreateRunner();
runner.MigrateUp(2009010101);
_profileLoaderMock.Verify(x => x.ApplyProfiles(runner), Times.Once());
}
[Test]
public void ProfilesAreAppliedWhenMigrateDownIsCalled()
{
var runner = CreateRunner();
runner.MigrateDown(2009010101);
_profileLoaderMock.Verify(x => x.ApplyProfiles(runner), Times.Once());
}
/// <summary>Unit test which ensures that the application context is correctly propagated down to each migration class.</summary>
[Test(Description = "Ensure that the application context is correctly propagated down to each migration class.")]
public void CanPassApplicationContext()
{
var runner = CreateRunner();
IMigration migration = new TestEmptyMigration();
runner.Up(migration);
Assert.AreEqual(_applicationContext, migration.ApplicationContext, "The migration does not have the expected application context.");
}
[Test]
public void CanPassConnectionString()
{
var runner = CreateRunner();
IMigration migration = new TestEmptyMigration();
runner.Up(migration);
Assert.AreEqual(IntegrationTestOptions.SqlServer2008.ConnectionString, migration.ConnectionString, "The migration does not have the expected connection string.");
}
[Test]
public void CanAnnounceUp()
{
var runner = CreateRunner();
runner.Up(new TestMigration());
_logMessages.ShouldContain(l => LineContainsAll(l, "Test", "migrating"));
}
[Test]
public void CanAnnounceUpFinish()
{
var runner = CreateRunner();
runner.Up(new TestMigration());
_logMessages.ShouldContain(l => LineContainsAll(l, "Test", "migrated"));
}
[Test]
public void CanAnnounceDown()
{
var runner = CreateRunner();
runner.Down(new TestMigration());
_logMessages.ShouldContain(l => LineContainsAll(l, "Test", "reverting"));
}
[Test]
public void CanAnnounceDownFinish()
{
var runner = CreateRunner();
runner.Down(new TestMigration());
_logMessages.ShouldContain(l => LineContainsAll(l, "Test", "reverted"));
}
[Test]
public void CanAnnounceUpElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
var runner = CreateRunner();
runner.Up(new TestMigration());
_logMessages.ShouldContain(l => l.Equals($"=> {ts.TotalSeconds}s"));
}
[Test]
public void CanAnnounceDownElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
var runner = CreateRunner();
runner.Down(new TestMigration());
_logMessages.ShouldContain(l => l.Equals($"=> {ts.TotalSeconds}s"));
}
[Test]
public void CanReportExceptions()
{
var runner = CreateRunner();
_processorMock.Setup(x => x.Process(It.IsAny<CreateTableExpression>())).Throws(new Exception("Oops"));
var exception = Assert.Throws<Exception>(() => runner.Up(new TestMigration()));
Assert.That(exception.Message, Does.Contain("Oops"));
}
[Test]
public void CanSayExpression()
{
_stopWatch.Setup(x => x.ElapsedTime()).Returns(new TimeSpan(0, 0, 0, 1, 3));
var runner = CreateRunner();
runner.Up(new TestMigration());
_logMessages.ShouldContain(l => LineContainsAll(l, "CreateTable"));
}
[Test]
public void CanTimeExpression()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
var runner = CreateRunner();
runner.Up(new TestMigration());
_logMessages.ShouldContain(l => l.Equals($"=> {ts.TotalSeconds}s"));
}
[Test]
public void HasMigrationsToApplyUpWhenThereAreMigrations()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
_fakeVersionLoader.Versions.Remove(fakeMigrationVersion2);
_fakeVersionLoader.LoadVersionInfo();
runner.HasMigrationsToApplyUp().ShouldBeTrue();
}
[Test]
public void HasMigrationsToApplyUpWhenThereAreNoNewMigrations()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
runner.HasMigrationsToApplyUp().ShouldBeFalse();
}
[Test]
public void HasMigrationsToApplyUpToSpecificVersionWhenTheSpecificHasNotBeenApplied()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
_fakeVersionLoader.Versions.Remove(fakeMigrationVersion2);
_fakeVersionLoader.LoadVersionInfo();
runner.HasMigrationsToApplyUp(fakeMigrationVersion2).ShouldBeTrue();
}
[Test]
public void HasMigrationsToApplyUpToSpecificVersionWhenTheSpecificHasBeenApplied()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
_fakeVersionLoader.Versions.Remove(fakeMigrationVersion2);
_fakeVersionLoader.LoadVersionInfo();
runner.HasMigrationsToApplyUp(fakeMigrationVersion1).ShouldBeFalse();
}
[Test]
public void HasMigrationsToApplyRollbackWithOneMigrationApplied()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
LoadVersionData(fakeMigrationVersion1);
runner.HasMigrationsToApplyRollback().ShouldBeTrue();
}
[Test]
public void HasMigrationsToApplyRollbackWithNoMigrationsApplied()
{
var runner = CreateRunner();
LoadVersionData();
runner.HasMigrationsToApplyRollback().ShouldBeFalse();
}
[Test]
public void HasMigrationsToApplyDownWhenTheVersionHasNotBeenApplied()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
_fakeVersionLoader.Versions.Remove(fakeMigrationVersion2);
_fakeVersionLoader.LoadVersionInfo();
runner.HasMigrationsToApplyDown(fakeMigrationVersion1).ShouldBeFalse();
}
[Test]
public void HasMigrationsToApplyDownWhenTheVersionHasBeenApplied()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
runner.HasMigrationsToApplyDown(fakeMigrationVersion1).ShouldBeTrue();
}
[Test]
public void RollbackOnlyOneStepsOfTwoShouldNotDeleteVersionInfoTable()
{
const long fakeMigrationVersion = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
var runner = CreateRunner();
Assert.NotNull(runner.VersionLoader.VersionTableMetaData.TableName);
LoadVersionData(fakeMigrationVersion, fakeMigrationVersion2);
runner.VersionLoader.LoadVersionInfo();
runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackLastVersionShouldDeleteVersionInfoTable()
{
var runner = CreateRunner();
const long fakeMigrationVersion = 2009010101;
LoadVersionData(fakeMigrationVersion);
Assert.NotNull(runner.VersionLoader.VersionTableMetaData.TableName);
runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldDeleteVersionInfoTable()
{
var runner = CreateRunner();
Assert.NotNull(runner.VersionLoader.VersionTableMetaData.TableName);
runner.RollbackToVersion(0);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldNotCreateVersionInfoTableAfterRemoval()
{
var runner = CreateRunner();
var versionInfoTableName = runner.VersionLoader.VersionTableMetaData.TableName;
runner.RollbackToVersion(0);
//Should only be called once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Once()
);
}
[Test]
public void RollbackToVersionShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
var runner = CreateRunner();
LoadVersionData(fakeMigration1,fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
runner.RollbackToVersion(2011010101);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackToVersionZeroShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
var runner = CreateRunner();
LoadVersionData(fakeMigration1, fakeMigration2, fakeMigration3);
_migrationList.Remove(fakeMigration1);
_migrationList.Remove(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
runner.RollbackToVersion(0);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackShouldLimitMigrationsToNamespace()
{
var runner = CreateRunner();
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1, fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
runner.Rollback(2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackToVersionShouldLoadVersionInfoIfVersionGreaterThanZero()
{
var runner = CreateRunner();
var versionInfoTableName = runner.VersionLoader.VersionTableMetaData.TableName;
runner.RollbackToVersion(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
//Once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Exactly(1)
);
//After setup is done, fake version loader owns the proccess
_fakeVersionLoader.DidLoadVersionInfoGetCalled.ShouldBe(true);
}
[Test]
public void ValidateVersionOrderingShouldReturnNothingIfNoUnappliedMigrations()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var runner = CreateRunner();
LoadVersionData(version1, version2);
_migrationList.Clear();
_migrationList.Add(version1,new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
Assert.DoesNotThrow(() => runner.ValidateVersionOrder());
_logMessages.ShouldContain(l => LineContainsAll(l, "Version ordering valid."));
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void ValidateVersionOrderingShouldReturnNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var runner = CreateRunner();
LoadVersionData(version1);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
Assert.DoesNotThrow(() => runner.ValidateVersionOrder());
_logMessages.ShouldContain(l => LineContainsAll(l, "Version ordering valid."));
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void ValidateVersionOrderingShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanGreatestAppliedMigrationVersion()
{
var runner = CreateRunner();
const long version1 = 2011010101;
const long version2 = 2011010102;
const long version3 = 2011010103;
const long version4 = 2011010104;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var mockMigration3 = new Mock<IMigration>();
var mockMigration4 = new Mock<IMigration>();
LoadVersionData(version1, version4);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
_migrationList.Add(version3, new MigrationInfo(version3, TransactionBehavior.Default, mockMigration3.Object));
_migrationList.Add(version4, new MigrationInfo(version4, TransactionBehavior.Default, mockMigration4.Object));
var exception = Assert.Throws<VersionOrderInvalidException>(() => runner.ValidateVersionOrder());
var invalidMigrations = exception.InvalidMigrations.ToList();
invalidMigrations.Count.ShouldBe(2);
invalidMigrations.Select(x => x.Key).ShouldContain(version2);
invalidMigrations.Select(x => x.Key).ShouldContain(version3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void CanListVersions()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
const long version3 = 2011010103;
const long version4 = 2011010104;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var mockMigration3 = new Mock<IMigration>();
var mockMigration4 = new Mock<IMigration>();
var runner = CreateRunner();
LoadVersionData(version1, version3);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
_migrationList.Add(version3, new MigrationInfo(version3, TransactionBehavior.Default, mockMigration3.Object));
_migrationList.Add(version4, new MigrationInfo(version4, TransactionBehavior.Default, true, mockMigration4.Object));
runner.ListMigrations();
_logMessages.ShouldContain(l => LineContainsAll(l, "2011010101: IMigrationProxy"));
_logMessages.ShouldContain(l => LineContainsAll(l, "2011010102: IMigrationProxy (not applied)"));
_logMessages.ShouldContain(l => LineContainsAll(l, "2011010103: IMigrationProxy (current)"));
_logMessages.ShouldContain(l => LineContainsAll(l, "2011010104: IMigrationProxy (not applied, BREAKING)"));
}
[Test]
public void IfMigrationHasAnInvalidExpressionDuringUpActionShouldThrowAnExceptionAndAnnounceTheError()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression {TableName = "Test"};
invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression));
var runner = CreateRunner();
Assert.Throws<InvalidMigrationException>(() => runner.Up(invalidMigration.Object));
var expectedErrorMessage = ErrorMessages.UpdateDataExpressionMustSpecifyWhereClauseOrAllRows;
_logMessages.ShouldContain(l => LineContainsAll(l, $"UpdateDataExpression: {expectedErrorMessage}"));
}
[Test]
public void IfMigrationHasAnInvalidExpressionDuringDownActionShouldThrowAnExceptionAndAnnounceTheError()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression { TableName = "Test" };
invalidMigration.Setup(m => m.GetDownExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression));
var runner = CreateRunner();
Assert.Throws<InvalidMigrationException>(() => runner.Down(invalidMigration.Object));
var expectedErrorMessage = ErrorMessages.UpdateDataExpressionMustSpecifyWhereClauseOrAllRows;
_logMessages.ShouldContain(l => LineContainsAll(l, $"UpdateDataExpression: {expectedErrorMessage}"));
}
[Test]
public void IfMigrationHasTwoInvalidExpressionsShouldAnnounceBothErrors()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression { TableName = "Test" };
var secondInvalidExpression = new CreateColumnExpression();
invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>()))
.Callback((IMigrationContext mc) => { mc.Expressions.Add(invalidExpression); mc.Expressions.Add(secondInvalidExpression); });
var runner = CreateRunner();
Assert.Throws<InvalidMigrationException>(() => runner.Up(invalidMigration.Object));
_logMessages.ShouldContain(l => LineContainsAll(l, $"UpdateDataExpression: {ErrorMessages.UpdateDataExpressionMustSpecifyWhereClauseOrAllRows}"));
_logMessages.ShouldContain(l => LineContainsAll(l, $"CreateColumnExpression: {ErrorMessages.TableNameCannotBeNullOrEmpty}"));
}
[Test]
public void CanLoadCustomMigrationConventions()
{
var runner = CreateRunner();
Assert.That(runner.Conventions, Is.TypeOf<CustomMigrationConventions>());
}
[Test]
public void CanLoadDefaultMigrationConventionsIfNoCustomConventionsAreSpecified()
{
var processorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose);
var serviceProvider = ServiceCollectionExtensions.CreateServices(false)
.WithProcessor(processorMock)
.BuildServiceProvider();
var runner = (MigrationRunner) serviceProvider.GetRequiredService<IMigrationRunner>();
Assert.That(runner.Conventions, Is.TypeOf<DefaultMigrationRunnerConventions>());
}
[Test]
public void CanBlockBreakingChangesByDefault()
{
var runner = CreateRunner(sc => sc.Configure<RunnerOptions>(opt => opt.AllowBreakingChange = false));
InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() =>
runner.ApplyMigrationUp(
new MigrationInfo(7, TransactionBehavior.Default, true, new TestBreakingMigration()), true));
Assert.NotNull(ex);
Assert.AreEqual(
"The migration 7: TestBreakingMigration is identified as a breaking change, and will not be executed unless the necessary flag (allow-breaking-changes|abc) is passed to the runner.",
ex.Message);
}
[Test]
public void CanRunBreakingChangesIfSpecified()
{
_serviceCollection
.Configure<RunnerOptions>(opt => opt.AllowBreakingChange = true);
var runner = CreateRunner();
Assert.DoesNotThrow(() =>
runner.ApplyMigrationUp(
new MigrationInfo(7, TransactionBehavior.Default, true, new TestBreakingMigration()), true));
}
[Test]
public void CanRunBreakingChangesInPreview()
{
_serviceCollection
.Configure<RunnerOptions>(opt => opt.AllowBreakingChange = true)
.Configure<ProcessorOptions>(opt => opt.PreviewOnly = true);
var runner = CreateRunner();
Assert.DoesNotThrow(() =>
runner.ApplyMigrationUp(
new MigrationInfo(7, TransactionBehavior.Default, true, new TestBreakingMigration()), true));
}
[Test]
public void CanLoadCustomMigrationScopeHandler()
{
_serviceCollection.AddScoped<IMigrationScopeManager>(scoped => { return _migrationScopeHandlerMock.Object; });
var runner = CreateRunner();
runner.BeginScope();
_migrationScopeHandlerMock.Verify(x => x.BeginScope(), Times.Once());
}
[Test]
public void CanLoadDefaultMigrationScopeHandlerIfNoCustomHandlerIsSpecified()
{
var runner = CreateRunner();
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.NonPublic;
FieldInfo field = typeof(MigrationRunner).GetField("_migrationScopeManager", bindFlags);
Assert.That(field.GetValue(runner), Is.TypeOf<MigrationScopeHandler>());
}
[Test]
public void DoesRunMigrationsThatMeetConstraints()
{
_migrationList.Clear();
_migrationList.Add(1, new MigrationInfo(1, TransactionBehavior.Default, new Step1Migration()));
_migrationList.Add(2, new MigrationInfo(2, TransactionBehavior.Default, new Step2Migration()));
_migrationList.Add(3, new MigrationInfo(3, TransactionBehavior.Default, new Step2Migration2()));
var runner = CreateRunner();
runner.MigrateUp();
Assert.AreEqual(1, runner.VersionLoader.VersionInfo.Latest());
}
[Test]
public void DoesRunMigrationsThatDoMeetConstraints()
{
_migrationList.Clear();
_migrationList.Add(1, new MigrationInfo(1, TransactionBehavior.Default, new Step1Migration()));
_migrationList.Add(2, new MigrationInfo(2, TransactionBehavior.Default, new Step2Migration()));
_migrationList.Add(3, new MigrationInfo(3, TransactionBehavior.Default, new Step2Migration2()));
var runner = CreateRunner();
runner.MigrateUp();
runner.MigrateUp(); // run migrations second time, this time satisfying constraints
Assert.AreEqual(3, runner.VersionLoader.VersionInfo.Latest());
}
[Test]
public void MultipleConstraintsEachNeedsToReturnTrue()
{
_migrationList.Clear();
_migrationList.Add(1, new MigrationInfo(1, TransactionBehavior.Default, new MultipleConstraintsMigration()));
var runner = CreateRunner();
runner.MigrateUp();
Assert.AreEqual(0, runner.VersionLoader.VersionInfo.Latest());
}
[Test]
public void DoesRunMigrationWithPositiveConstraint()
{
_migrationList.Clear();
_migrationList.Add(1, new MigrationInfo(1, TransactionBehavior.Default, new ConstrainedMigrationSuccess()));
var runner = CreateRunner();
runner.MigrateUp();
Assert.AreEqual(1, runner.VersionLoader.VersionInfo.Latest());
}
private static bool LineContainsAll(string line, params string[] words)
{
var pattern = string.Join(".*?", words.Select(Regex.Escape));
return Regex.IsMatch(line, pattern);
}
public class CustomMigrationConventions : MigrationRunnerConventions
{
}
}
}
| |
//==============================================================================
// TorqueLab -> ShapeLab -> Sequence Editing
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
function ShapeLab::validateSequenceName( %this,%seqName ) {
for(%i=0;%i<ShapeLab.shape.getSequenceCount();%i++)
{
%name = ShapeLab.shape.getSequenceName(%i);
devLog("Sequence Index",%i,"Name",%name,"Check",%seqName);
if (%name $= %seqName)
{
devLog("Sequence is valid",%seqName);
return %name;
}
}
devLog("Sequence is invalid",%seqName);
return "-1";
}
//==============================================================================
function ShapeLab::updateShapeSequenceData( %this,%seqName,%newName ) {
ShapeLab_SeqPillStack.clear(); //Clear the new sequence lisitng stack
//ShapeLabSequenceList.clear();
//ShapeLabSequenceList.addRow( -1, "Name" TAB "Cyclic" TAB "Blend" TAB "Frames" TAB "Priority" );
//ShapeLabSequenceList.setRowActive( -1, false );
//ShapeLabSequenceList.addRow( 0, "<rootpose>" TAB "" TAB "" TAB "" TAB "" );
%count = ShapeLab.shape.getSequenceCount();
%sourceMenu = SL_ActiveSequence-->sourceSeq;
%blendMenu = SL_ActiveSequence-->blendSeq;
%sourceMenu.clear();
%blendMenu.clear();
ShapeLab_ThreadIdList.clear();
ShapeLab_ThreadSeqList.clear();
ShapeLab_ThreadSeqList.addRow( 0, "<rootpose>" TAB "" TAB "" TAB "" TAB "" );
for ( %i = 0; %i < %count; %i++ ) {
%name = ShapeLab.shape.getSequenceName( %i );
// Ignore __backup__ sequences (only used by editor)
if ( !startswith( %name, "__backup__" ) ) {
ShapeLab.addSequencePill(%name);
ShapeLab_ThreadSeqList.addRow( %i, %name, %i );
//if ( %name !$= %seqName ) {
%sourceMenu.add( %name );
%blendMenu.add( %name );
//}
}
}
ShapeLabThreadViewer.onAddThread(); // add thread 0
}
//------------------------------------------------------------------------------
//==============================================================================
// SEQUENCE CREATE/ADD/DELETE FUNCTIONS
//==============================================================================
//==============================================================================
function ShapeLab::onAddSequence( %this, %name ) {
if ( %name $= "" )
%name = ShapeLab.getUniqueName( "sequence", "mySequence" );
// Use the currently selected sequence as the base
%curSeqName = %this.selectedSequence;
if ( %curSeqName $= "" ) {
// No sequence selected => open dialog to browse for one
%startAt = ShapeLab.shape.baseShape; //Start at current loaded shape path
if (isFile(ShapeLab.currentSeqPath))
%startAt = ShapeLab.currentSeqPath;
getLoadFilename( "Anim Files|*.dae;*.dsq|COLLADA Files|*.dae|DSQ Files|*.dsq|Google Earth Files|*.kmz", %this @ ".onAddSequenceFromBrowse", %startAt );
return;
} else {
%sourceData = ShapeLab.getSequenceSource( %curSeqName );
%from = rtrim( getFields( %sourceData, 0, 1 ) );
%start = getField( %sourceData, 2 );
%end = getField( %sourceData, 3 );
%frameCount = getField( %sourceData, 4 );
// Add the new sequence
ShapeLab.doAddSequence( %name, %curSeqName, %start, %end );
}
}
//------------------------------------------------------------------------------
//==============================================================================
function ShapeLab::onAddSequenceFromBrowse( %this, %path ) {
// Add a new sequence from the browse path
%path = makeRelativePath( %path, getMainDotCSDir() );
ShapeLabFromMenu.lastPath = %path;
ShapeLab.currentSeqPath = %path;
%name = ShapeLab.getUniqueName( "sequence", "mySequence" );
ShapeLab.doAddSequence( %name, %path, 0, -1 );
}
//------------------------------------------------------------------------------
function ShapeLab::onDeleteSequence( %this,%button ) {
devLog("ShapeLab::onDeleteSequence" );
if (isObject(%button))
%sequence = %button.seqName;
else
%sequence = ShapeLab.selectedSequence;
if (%sequence $= "")
return;
ShapeLab.doRemoveShapeData( "Sequence", %sequence );
}
//==============================================================================
// SEQUENCE UPDATE FUNCTIONS
//==============================================================================
//==============================================================================
function ShapeLab::updateSequenceName( %this,%seqName,%newName ) {
if (%seqName $= "")
%seqName = ShapeLab.selectedSequence;
if (%newName $= "")
%newName = SL_ActiveSequence-->seqName.getText();
if ( %seqName !$= "" && %newName !$= "" && %newName !$= %seqName)
ShapeLab.doRenameSequence( %seqName, %newName );
}
//------------------------------------------------------------------------------
//==============================================================================
function ShapeLab::updateSequenceCyclic( %this,%seqName,%isCyclic ) {
if ( %seqName !$= "" )
ShapeLab.doEditCyclic( %seqName, %isCyclic );
}
//------------------------------------------------------------------------------
//==============================================================================
function ShapeLab::updateSequencePriority( %this,%seqName ) {
if (%seqName $= "")
%seqName = ShapeLab.selectedSequence;
if ( %seqName !$= "" ) {
%newPriority = SL_ActiveSequence-->priority.getText();
if ( %newPriority !$= "" )
ShapeLab.doEditSequencePriority( %seqName, %newPriority );
}
}
//------------------------------------------------------------------------------
//==============================================================================
function ShapeLab::updateSequenceSource( %this, %path ,%pill ) {
// ignore for shapes without sequences
if (ShapeLab.shape.getSequenceCount() == 0)
return;
if (!isObject(%pill))
%pill = SL_ActiveSequence;
%start = %pill-->frameIn.getText();
%end = %pill-->frameOut.getText();
%seqName = %pill.seqName;
if (%seqName $= "")
return;
if ( ( %start !$= "" ) && ( %end !$= "" ) ) {
%oldSource = ShapeLab.getSequenceSource( %seqName );
if ( %path $= "" )
%path = rtrim( getFields( %oldSource, 0, 0 ) );
if ( getFields( %oldSource, 0, 3 ) !$= ( %path TAB "" TAB %start TAB %end ) )
ShapeLab.doEditSeqSource( %seqName, %path, %start, %end );
}
}
//==============================================================================
function ShapeLab::updateSequenceBlend( %this,%seqName ) {
if (%seqName $= "")
%seqName = ShapeLab.selectedSequence;
if ( %seqName !$= "" ) {
// Get the blend flags (current and new)
%oldBlendData = ShapeLab.shape.getSequenceSource( "Fake" );
%oldBlend = getField( %oldBlendData, 0 );
//MustBe Active Sequence
if (ShapeLab.selectedSequence !$= %seqName)
{
devLog("Trying to update blend on unselected sequence:",%seqName,"Selected",ShapeLab.selectedSequence);
return;
}
%blend = SL_ActiveSequence-->blend.isStateOn();
if (%blend $= "")
%blend = %oldBlend;
// Ignore changes to the blend reference for non-blend sequences
if ( !%oldBlend && !%isBlend )
return;
// OK - we're trying to change the blend properties of this sequence. The
// new reference sequence and frame must be set.
%blendSeq = SL_ActiveSequence-->blendSeq.getText();
%blendFrame = SL_ActiveSequence-->blendFrame.getText();
if ( ( %blendSeq $= "" ) || ( %blendFrame $= "" ) ) {
LabMsgOK( "Blend reference not set", "The blend reference sequence and " @
"frame must be set before changing the blend flag or frame." );
SL_ActiveSequence-->blend.setStateOn( %oldBlend );
return;
}
// Get the current blend properties (use new values if not specified)
%oldBlendSeq = getField( %oldBlendData, 1 );
if ( %oldBlendSeq $= "" )
%oldBlendSeq = %blendSeq;
%oldBlendFrame = getField( %oldBlendData, 2 );
if ( %oldBlendFrame $= "" )
%oldBlendFrame = %blendFrame;
// Check if there is anything to do
if ( ( %oldBlend TAB %oldBlendSeq TAB %oldBlendFrame ) !$= ( %blend TAB %blendSeq TAB %blendFrame ) )
ShapeLab.doEditBlend( %seqName, %blend, %blendSeq, %blendFrame );
}
}
//------------------------------------------------------------------------------
//==============================================================================
// ShapeLab Sequence Update -> Name
//==============================================================================
//==============================================================================
//==============================================================================
// ShapeLab Sequence Update -> Cyclic
//==============================================================================
//==============================================================================
// ShapeLab Sequence Update -> Priority
//==============================================================================
//==============================================================================
// ShapeLab Sequence Update -> Belnding
//==============================================================================
//==============================================================================
// ShapeLab Sequence Update -> Belnding
//==============================================================================
//==============================================================================
function ShapeLab::onEditSequenceSource( %this, %from ,%pill ) {
// ignore for shapes without sequences
if (ShapeLab.shape.getSequenceCount() == 0)
return;
if (%pill $= "")
%pill = SL_ActiveSequence;
%start = %pill-->frameIn.getText();
%end = %pill-->frameOut.getText();
%seqName = ShapeLab.validateSequenceName(%pill.seqName);
if (%seqName $= "-1")
{
warnLog("Edit source data for invalid sequence:",%pill.seqName);
return;
}
if ( ( %start !$= "" ) && ( %end !$= "" ) ) {
%oldSource = ShapeLab.getSequenceSource( %seqName );
if ( %from $= "" )
%from = rtrim( getFields( %oldSource, 0, 0 ) );
devLog("onEditSequenceSource Start",%start,"End",%end,"Seq",%seqName,"From",%from);
if ( getFields( %oldSource, 0, 3 ) !$= ( %from TAB "" TAB %start TAB %end ) )
ShapeLab.doEditSeqSource( %seqName, %from, %start, %end );
}
}
| |
namespace Fonet
{
using System;
using System.IO;
using System.Net;
using System.Xml;
using Fonet.Fo;
using Fonet.Render.Pdf;
/// <summary>
/// FonetDriver provides the client with a single interface to invoking FO.NET.
/// </summary>
/// <remarks>
/// The examples belows demonstrate several ways of invoking FO.NET. The
/// methodology is the same regardless of how FO.NET is embedded in your
/// system (ASP.NET, WinForm, Web Service, etc).
/// </remarks>
/// <example>
/// <code lang="csharp">
/// // This example demonstrates rendering an XSL-FO file to a PDF file.
/// FonetDriver driver = FonetDriver.Make();
/// driver.Render(
/// new FileStream("readme.fo", FileMode.Open),
/// new FileStream("readme.pdf", FileMode.Create));
/// </code>
/// <code lang="vb">
/// // This example demonstrates rendering an XSL-FO file to a PDF file.
/// Dim driver As FonetDriver = FonetDriver.Make
/// driver.Render( _
/// New FileStream("readme.fo", FileMode.Open), _
/// New FileStream("readme.pdf", FileMode.Create))
/// </code>
/// <code lang="csharp">
/// // This example demonstrates using an XmlDocument as the source of the
/// // XSL-FO tree. The XmlDocument could easily be dynamically generated.
/// XmlDocument doc = new XmlDocument()
/// doc.Load("reader.fo");
///
/// FonetDriver driver = FonetDriver.Make();
/// driver.Render(doc, new FileStream("readme.pdf", FileMode.Create));
/// </code>
/// <code lang="vb">
/// // This example demonstrates using an XmlDocument as the source of the
/// // XSL-FO tree. The XmlDocument could easily be dynamically generated.
/// Dim doc As XmlDocument = New XmlDocument()
/// doc.Load("reader.fo")
///
/// Dim driver As FonetDriver = FonetDriver.Make
/// driver.Render(doc, New FileStream("readme.pdf", FileMode.Create))
/// </code>
/// </example>
public class FonetDriver : IDisposable
{
/// <summary>
/// Determines if the output stream passed to Render() should
/// be closed upon completion or if a fatal exception occurs.
/// </summary>
private bool closeOnExit = true;
/// <summary>
/// Options to supply to the renderer.
/// </summary>
private PdfRendererOptions renderOptions;
/// <summary>
/// Maps a set of credentials to an internet resource
/// </summary>
private CredentialCache credentials;
/// <summary>
/// The directory that external resources such as images are loaded
/// from when using relative path references.
/// </summary>
private DirectoryInfo baseDirectory;
/// <summary>
/// The timeout used when accessing external resources via a URL.
/// </summary>
private int timeout;
/// <summary>
/// The active driver.
/// </summary>
[ThreadStatic]
private static FonetDriver activeDriver;
/// <summary>
/// The delegate subscribers must implement to receive FO.NET events.
/// </summary>
/// <remarks>
/// The <paramref name="driver"/> parameter will be a reference to
/// the active FonetDriver. The <paramref name="e"/> parameter will
/// contain a human-readable error message.
/// </remarks>
/// <param name="driver">A reference to the active FonetDriver</param>
/// <param name="e">Encapsulates a human readable error message</param>
public delegate void FonetEventHandler(object driver, FonetEventArgs e);
/// <summary>
/// An optional image handler that can be registered to load image
/// data for external graphic formatting objects.
/// </summary>
private FonetImageHandler imageHandler;
/// <summary>
/// The delegate subscribers must implement to handle the loading
/// of image data in response to external-graphic formatting objects.
/// </summary>
public delegate byte[] FonetImageHandler(string src);
/// <summary>
/// A multicast delegate. The error event FO.NET publishes.
/// </summary>
/// <remarks>
/// The method signature for this event handler should match
/// the following:
/// <pre class="code"><span class="lang">
/// void FonetError(object driver, FonetEventArgs e);
/// </span></pre>
/// The first parameter <i>driver</i> will be a reference to the
/// active FonetDriver instance.
/// </remarks>
/// <example>Subscribing to the 'error' event
/// <pre class="code"><span class="lang">[C#]</span><br/>
/// {
/// FonetDriver driver = FonetDriver.Make();
/// driver.OnError += new FonetDriver.FonetEventHandler(FonetError);
/// ...
/// }
/// </pre>
/// </example>
public event FonetEventHandler OnError;
/// <summary>
/// A multicast delegate. The warning event FO.NET publishes.
/// </summary>
/// <remarks>
/// The method signature for this event handler should match
/// the following:
/// <pre class="code"><span class="lang">
/// void FonetWarning(object driver, FonetEventArgs e);
/// </span></pre>
/// The first parameter <i>driver</i> will be a reference to the
/// active FonetDriver instance.
/// </remarks>
public event FonetEventHandler OnWarning;
/// <summary>
/// A multicast delegate. The info event FO.NET publishes.
/// </summary>
/// <remarks>
/// The method signature for this event handler should match
/// the following:
/// <pre class="code"><span class="lang">
/// void FonetInfo(object driver, FonetEventArgs e);
/// </span></pre>
/// The first parameter <i>driver</i> will be a reference to the
/// active FonetDriver instance.
/// </remarks>
public event FonetEventHandler OnInfo;
/// <summary>
/// Constructs a new FonetDriver and registers the newly created
/// driver as the active driver.
/// </summary>
/// <returns>An instance of FonetDriver</returns>
public static FonetDriver Make()
{
return new FonetDriver();
}
/// <summary>
/// Sets the the 'baseDir' property in the Configuration class using
/// the value returned by Directory.GetCurrentDirectory(). Sets the
/// default timeout to 100 seconds.
/// </summary>
public FonetDriver()
{
BaseDirectory = new DirectoryInfo(Path.GetFullPath(Directory.GetCurrentDirectory()));
Timeout = 100000;
//ActiveDriver = this; // BAD memory loss in multithreaded/thread pool environment if the developer did not set ActiveDriver to null
}
/// <summary>
/// Determines if the output stream should be automatically closed
/// upon completion of the render process.
/// </summary>
public bool CloseOnExit
{
get
{
return closeOnExit;
}
set
{
closeOnExit = value;
}
}
/// <summary>
/// Gets or sets the active <see cref="FonetDriver"/>.
/// </summary>
/// <value>
/// An instance of <see cref="FonetDriver"/> created via the factory method
/// <see cref="Make"/>.
/// </value>
public static FonetDriver ActiveDriver
{
get
{
return activeDriver;
}
/* is now an internal value to prevent memory loss
set
{
activeDriver = value;
}
*/
}
/// <summary>
/// Gets or sets the base directory used to locate external
/// resourcs such as images.
/// </summary>
/// <value>
/// Defaults to the current working directory.
/// </value>
public DirectoryInfo BaseDirectory
{
get
{
return baseDirectory;
}
set
{
baseDirectory = value;
}
}
/// <summary>
/// Gets or sets the handler that is responsible for loading the image
/// data for external graphics.
/// </summary>
/// <remarks>
/// If null is returned from the image handler, then FO.NET will perform
/// normal processing.
/// </remarks>
public FonetImageHandler ImageHandler
{
get
{
return imageHandler;
}
set
{
imageHandler = value;
}
}
/// <summary>
/// Gets or sets the time in milliseconds until an HTTP image request
/// times out.
/// </summary>
/// <remarks>
/// The default value is 100000 milliseconds.
/// </remarks>
/// <value>
/// The timeout value in milliseconds
/// </value>
public int Timeout
{
get
{
return timeout;
}
set
{
timeout = value;
}
}
/// <summary>
/// Gets a reference to a <see cref="System.Net.CredentialCache"/> object
/// that manages credentials for multiple Internet resources.
/// <seealso cref="System.Net.CredentialCache"/>
/// </summary>
/// <remarks>
/// The purpose of this property is to associate a set of credentials against
/// an Internet resource. These credentials are then used by FO.NET when
/// fetching images from one of the listed resources.
/// </remarks>
/// <example>
/// FonetDriver driver = FonetDriver.Make();
///
/// NetworkCredential nc1 = new NetworkCredential("foo", "password");
/// driver.Credentials.Add(new Uri("http://www.chive.com"), "Basic", nc1);
///
/// NetworkCredential nc2 = new NetworkCredential("john", "password", "UK");
/// driver.Credentials.Add(new Uri("http://www.xyz.com"), "Digest", nc2);
/// </example>
public CredentialCache Credentials
{
get
{
if (credentials == null)
{
credentials = new CredentialCache();
}
return credentials;
}
}
/// <summary>
/// Options that are passed to the rendering engine.
/// </summary>
public PdfRendererOptions Options
{
get
{
return renderOptions;
}
set
{
renderOptions = value;
}
}
/// <summary>
/// Executes the conversion reading the source tree from the supplied
/// XmlDocument, converting it to a format dictated by the renderer
/// and writing it to the supplied output stream.
/// </summary>
/// <param name="doc">
/// An in-memory representation of an XML document (DOM).
/// </param>
/// <param name="outputStream">
/// Any subclass of the Stream class.
/// </param>
/// <remarks>
/// Any exceptions that occur during the render process are arranged
/// into three categories: information, warning and error. You may
/// intercept any or all of theses exceptional states by registering
/// an event listener. See <see cref="FonetDriver.OnError"/> for an
/// example of registering an event listener. If there are no
/// registered listeners, the exceptions are dumped to standard out -
/// except for the error event which is wrapped in a
/// <see cref="SystemException"/>.
/// </remarks>
public virtual void Render(XmlDocument doc, Stream outputStream)
{
using(StringWriter sw = new StringWriter())
{
using(XmlTextWriter writer = new XmlTextWriter(sw))
{
doc.Save(writer);
writer.Close();
}
using(StringReader reader = new StringReader(sw.ToString()))
{
Render(reader, outputStream);
}
}
}
/// <summary>
/// Executes the conversion reading the source tree from the input
/// reader, converting it to a format dictated by the renderer and
/// writing it to the supplied output stream.
/// </summary>
/// <param name="inputReader">A character orientated stream</param>
/// <param name="outputStream">Any subclass of the Stream class</param>
public virtual void Render(TextReader inputReader, Stream outputStream)
{
using(XmlReader reader = CreateXmlTextReader(inputReader))
{
Render(reader, outputStream);
}
}
/// <summary>
/// Executes the conversion reading the source tree from the file
/// <i>inputFile</i>, converting it to a format dictated by the
/// renderer and writing it to the file identified by <i>outputFile</i>.
/// </summary>
/// <remarks>
/// If the file <i>outputFile</i> does not exist, it will created
/// otherwise it will be overwritten. Creating a file may
/// generate a variety of exceptions. See <see cref="FileStream"/>
/// for a complete list.<br/>
/// </remarks>
/// <param name="inputFile">Path to an XSL-FO file</param>
/// <param name="outputFile">Path to a file</param>
public virtual void Render(string inputFile, string outputFile)
{
using(XmlReader reader = CreateXmlTextReader(inputFile))
{
using(Stream stream = new FileStream(outputFile, FileMode.Create, FileAccess.Write)) // yes this stream will always close
{
Render(reader, stream);
}
}
}
/// <summary>
/// Executes the conversion reading the source tree from the file
/// <i>inputFile</i>, converting it to a format dictated by the
/// renderer and writing it to the supplied output stream.
/// </summary>
/// <param name="inputFile">Path to an XSL-FO file</param>
/// <param name="outputStream">
/// Any subclass of the Stream class, e.g. FileStream
/// </param>
public virtual void Render(string inputFile, Stream outputStream)
{
using(XmlReader reader = CreateXmlTextReader(inputFile))
{
Render(reader, outputStream);
}
}
/// <summary>
/// Executes the conversion reading the source tree from the input
/// stream, converting it to a format dictated by the render and
/// writing it to the supplied output stream.
/// </summary>
/// <param name="inputStream">Any subclass of the Stream class, e.g. FileStream</param>
/// <param name="outputStream">Any subclass of the Stream class, e.g. FileStream</param>
public virtual void Render(Stream inputStream, Stream outputStream)
{
using(XmlReader reader = CreateXmlTextReader(inputStream))
{
Render(reader, outputStream);
}
}
/// <summary>
/// Executes the conversion reading the source tree from the input
/// reader, converting it to a format dictated by the render and
/// writing it to the supplied output stream.
/// </summary>
/// <remarks>
/// The evaluation copy of this class will output an evaluation
/// banner to standard out
/// </remarks>
/// <param name="inputReader">
/// Reader that provides fast, non-cached, forward-only access
/// to XML data
/// </param>
/// <param name="outputStream">
/// Any subclass of the Stream class, e.g. FileStream
/// </param>
public void Render(XmlReader inputReader, Stream outputStream)
{
if(activeDriver != null)
throw new SystemException("ActiveDriver is set.");
try
{
activeDriver = this;
try
{
// Constructs an area tree renderer and supplies the renderer options
PdfRenderer renderer = new PdfRenderer(outputStream);
if(renderOptions != null)
{
renderer.Options = renderOptions;
}
// Create the stream-renderer.
StreamRenderer sr = new StreamRenderer(renderer);
// Create the tree builder and give it the stream renderer.
FOTreeBuilder tb = new FOTreeBuilder();
tb.SetStreamRenderer(sr);
// Setup the mapping between xsl:fo elements and our fo classes.
StandardElementMapping sem = new StandardElementMapping();
sem.AddToBuilder(tb);
// Start processing the xml document.
tb.Parse(inputReader);
}
finally
{
if(CloseOnExit)
{
// Flush and close the output stream
outputStream.Flush();
outputStream.Close();
}
}
}
finally
{
activeDriver = null;
}
}
/// <summary>
/// Sends an 'error' event to all registered listeners.
/// </summary>
/// <remarks>
/// If there are no listeners, a <see cref="SystemException"/> is
/// thrown immediately halting execution
/// </remarks>
/// <param name="message">Any error message, which may be null</param>
/// <exception cref="SystemException">
/// If no listener is registered for this event, a SystemException
/// will be thrown
/// </exception>
internal void FireFonetError(string message)
{
if (OnError != null)
{
OnError(this, new FonetEventArgs(message));
}
else
{
throw new SystemException(message);
}
}
/// <summary>
/// Sends a 'warning' event to all registered listeners
/// </summary>
/// <remarks>
/// If there are no listeners, <i>message</i> is written out
/// to the console instead
/// </remarks>
/// <param name="message">Any warning message, which may be null</param>
internal void FireFonetWarning(string message)
{
if (OnWarning != null)
{
OnWarning(this, new FonetEventArgs(message));
}
else
{
Console.WriteLine("[WARN] {0}", message);
Console.Error.WriteLine("[WARN] {0}", message);
}
}
/// <summary>
/// Sends an 'info' event to all registered lisetners
/// </summary>
/// <remarks>
/// If there are no listeners, <i>message</i> is written out
/// to the console instead
/// </remarks>
/// <param name="message">An info message, which may be null</param>
internal void FireFonetInfo(string message)
{
if (OnInfo != null)
{
OnInfo(this, new FonetEventArgs(message));
}
else
{
Console.WriteLine("[INFO] {0}", message);
}
}
/// <summary>
/// Utility method that creates an <see cref="System.Xml.XmlTextReader"/>
/// for the supplied file
/// </summary>
/// <remarks>
/// The returned <see cref="System.Xml.XmlReader"/> interprets all whitespace
/// </remarks>
private XmlReader CreateXmlTextReader(string inputFile)
{
XmlTextReader reader = new XmlTextReader(inputFile);
return reader;
}
/// <summary>
/// Utility method that creates an <see cref="System.Xml.XmlTextReader"/>
/// for the supplied file
/// </summary>
/// <remarks>
/// The returned <see cref="System.Xml.XmlReader"/> interprets all whitespace
/// </remarks>
private XmlReader CreateXmlTextReader(Stream inputStream)
{
XmlTextReader reader = new XmlTextReader(inputStream);
return reader;
}
/// <summary>
/// Utility method that creates an <see cref="System.Xml.XmlTextReader"/>
/// for the supplied file
/// </summary>
/// <remarks>
/// The returned <see cref="System.Xml.XmlReader"/> interprets all whitespace
/// </remarks>
private XmlReader CreateXmlTextReader(TextReader inputReader)
{
XmlTextReader reader = new XmlTextReader(inputReader);
return reader;
}
#region IDisposable Members
public void Dispose()
{
this.imageHandler = null;
this.credentials = null;
this.baseDirectory = null;
this.renderOptions = null;
this.OnError = null;
this.OnInfo = null;
this.OnWarning = null;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ODataDemo.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
#define PRETTY //Comment out when you no longer need to read JSON to disable pretty Print system-wide
//Using doubles will cause errors in VectorTemplates.cs; Unity speaks floats
#define USEFLOAT //Use floats for numbers instead of doubles (enable if you're getting too many significant digits in string output)
//#define POOLING //Currently using a build setting for this one (also it's experimental)
using System.Diagnostics;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Debug = UnityEngine.Debug;
/*
* http://www.opensource.org/licenses/lgpl-2.1.php
* JSONObject class
* for use with Unity
* Copyright Matt Schoen 2010 - 2013
*/
public class JSONObject {
#if POOLING
const int MAX_POOL_SIZE = 10000;
public static Queue<JSONObject> releaseQueue = new Queue<JSONObject>();
#endif
const int MAX_DEPTH = 100;
const string INFINITY = "\"INFINITY\"";
const string NEGINFINITY = "\"NEGINFINITY\"";
const string NaN = "\"NaN\"";
static readonly char[] WHITESPACE = new[] { ' ', '\r', '\n', '\t' };
public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL, BAKED }
public bool isContainer { get { return (type == Type.ARRAY || type == Type.OBJECT); } }
public Type type = Type.NULL;
public int Count {
get {
if(list == null)
return -1;
return list.Count;
}
}
public List<JSONObject> list;
public List<string> keys;
public string str;
#if USEFLOAT
public float n;
public float f {
get {
return n;
}
}
#else
public double n;
public float f {
get {
return (float)n;
}
}
#endif
// jfs...
public int i {
get {
return (int)n;
}
}
public bool b;
public delegate void AddJSONConents(JSONObject self);
public static JSONObject nullJO { get { return Create(Type.NULL); } } //an empty, null object
public static JSONObject obj { get { return Create(Type.OBJECT); } } //an empty object
public static JSONObject arr { get { return Create(Type.ARRAY); } } //an empty array
public JSONObject(Type t) {
type = t;
switch(t) {
case Type.ARRAY:
list = new List<JSONObject>();
break;
case Type.OBJECT:
list = new List<JSONObject>();
keys = new List<string>();
break;
}
}
public JSONObject(bool b) {
type = Type.BOOL;
this.b = b;
}
#if USEFLOAT
public JSONObject(float f) {
type = Type.NUMBER;
n = f;
}
#else
public JSONObject(double d) {
type = Type.NUMBER;
n = d;
}
#endif
public JSONObject(Dictionary<string, string> dic) {
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, string> kvp in dic) {
keys.Add(kvp.Key);
list.Add(CreateStringObject(kvp.Value));
}
}
public JSONObject(Dictionary<string, JSONObject> dic) {
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, JSONObject> kvp in dic) {
keys.Add(kvp.Key);
list.Add(kvp.Value);
}
}
public JSONObject(AddJSONConents content) {
content.Invoke(this);
}
public JSONObject(JSONObject[] objs) {
type = Type.ARRAY;
list = new List<JSONObject>(objs);
}
//Convenience function for creating a JSONObject containing a string. This is not part of the constructor so that malformed JSON data doesn't just turn into a string object
public static JSONObject StringObject(string val) { return CreateStringObject(val); }
public void Absorb(JSONObject obj) {
list.AddRange(obj.list);
keys.AddRange(obj.keys);
str = obj.str;
n = obj.n;
b = obj.b;
type = obj.type;
}
public static JSONObject Create() {
#if POOLING
JSONObject result = null;
while(result == null && releaseQueue.Count > 0) {
result = releaseQueue.Dequeue();
#if DEV
//The following cases should NEVER HAPPEN (but they do...)
if(result == null)
Debug.Log("wtf " + releaseQueue.Count);
else if(result.list != null)
Debug.Log("wtflist " + result.list.Count);
#endif
}
if(result != null)
return result;
#endif
return new JSONObject();
}
public static JSONObject Create(Type t) {
JSONObject obj = Create();
obj.type = t;
switch(t) {
case Type.ARRAY:
obj.list = new List<JSONObject>();
break;
case Type.OBJECT:
obj.list = new List<JSONObject>();
obj.keys = new List<string>();
break;
}
return obj;
}
public static JSONObject Create(bool val) {
JSONObject obj = Create();
obj.type = Type.BOOL;
obj.b = val;
return obj;
}
public static JSONObject Create(float val) {
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
return obj;
}
public static JSONObject Create(int val) {
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
return obj;
}
public static JSONObject CreateStringObject(string val) {
JSONObject obj = Create();
obj.type = Type.STRING;
obj.str = val;
return obj;
}
public static JSONObject CreateBakedObject(string val) {
JSONObject bakedObject = Create();
bakedObject.type = Type.BAKED;
bakedObject.str = val;
return bakedObject;
}
/// <summary>
/// Create a JSONObject by parsing string data
/// </summary>
/// <param name="val">The string to be parsed</param>
/// <param name="maxDepth">The maximum depth for the parser to search. Set this to to 1 for the first level,
/// 2 for the first 2 levels, etc. It defaults to -2 because -1 is the depth value that is parsed (see below)</param>
/// <param name="storeExcessLevels">Whether to store levels beyond maxDepth in baked JSONObjects</param>
/// <param name="strict">Whether to be strict in the parsing. For example, non-strict parsing will successfully
/// parse "a string" into a string-type </param>
/// <returns></returns>
///
// Default parameters fix
public static JSONObject Create(string val) { return Create(val, -2, false, false); }
public static JSONObject Create(string val, int maxDepth) { return Create(val, maxDepth, false, false); }
public static JSONObject Create(string val, int maxDepth, bool storeExcessLevels) { return Create(val, maxDepth, storeExcessLevels, false); }
public static JSONObject Create(string val, int maxDepth, bool storeExcessLevels, bool strict) {
JSONObject obj = Create();
obj.Parse(val, maxDepth, storeExcessLevels, strict);
return obj;
}
public static JSONObject Create(AddJSONConents content) {
JSONObject obj = Create();
content.Invoke(obj);
return obj;
}
public static JSONObject Create(Dictionary<string, string> dic) {
JSONObject obj = Create();
obj.type = Type.OBJECT;
obj.keys = new List<string>();
obj.list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, string> kvp in dic) {
obj.keys.Add(kvp.Key);
obj.list.Add(CreateStringObject(kvp.Value));
}
return obj;
}
public JSONObject() { }
#region PARSE
// Default parameters fix
public JSONObject(string str){ Parse(str, -2, false, false); }
public JSONObject(string str, int maxDepth, bool storeExcessLevels, bool strict) { //create a new JSONObject from a string (this will also create any children, and parse the whole string)
Parse(str, maxDepth, storeExcessLevels, strict);
}
// Default parameters fix
void Parse(string str) { Parse(str, -2, false, false); }
void Parse(string str, int maxDepth, bool storeExcessLevels, bool strict) {
if(!string.IsNullOrEmpty(str)) {
str = str.Trim(WHITESPACE);
if(strict) {
if(str[0] != '[' && str[0] != '{') {
type = Type.NULL;
Debug.LogWarning("Improper (strict) JSON formatting. First character must be [ or {");
return;
}
}
if(str.Length > 0) {
if(string.Compare(str, "true", true) == 0) {
type = Type.BOOL;
b = true;
} else if(string.Compare(str, "false", true) == 0) {
type = Type.BOOL;
b = false;
} else if(string.Compare(str, "null", true) == 0) {
type = Type.NULL;
#if USEFLOAT
} else if(str == INFINITY) {
type = Type.NUMBER;
n = float.PositiveInfinity;
} else if(str == NEGINFINITY) {
type = Type.NUMBER;
n = float.NegativeInfinity;
} else if(str == NaN) {
type = Type.NUMBER;
n = float.NaN;
#else
} else if(str == INFINITY) {
type = Type.NUMBER;
n = double.PositiveInfinity;
} else if(str == NEGINFINITY) {
type = Type.NUMBER;
n = double.NegativeInfinity;
} else if(str == NaN) {
type = Type.NUMBER;
n = double.NaN;
#endif
} else if(str[0] == '"') {
type = Type.STRING;
this.str = str.Substring(1, str.Length - 2);
} else {
int tokenTmp = 1;
/*
* Checking for the following formatting (www.json.org)
* object - {"field1":value,"field2":value}
* array - [value,value,value]
* value - string - "string"
* - number - 0.0
* - bool - true -or- false
* - null - null
*/
int offset = 0;
switch(str[offset]) {
case '{':
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
break;
case '[':
type = Type.ARRAY;
list = new List<JSONObject>();
break;
default:
try {
#if USEFLOAT
n = System.Convert.ToSingle(str);
#else
n = System.Convert.ToDouble(str);
#endif
type = Type.NUMBER;
} catch(System.FormatException) {
type = Type.NULL;
Debug.LogWarning("improper JSON formatting:" + str);
}
return;
}
string propName = "";
bool openQuote = false;
bool inProp = false;
int depth = 0;
while(++offset < str.Length) {
if(System.Array.IndexOf(WHITESPACE, str[offset]) > -1)
continue;
if(str[offset] == '\\') {
offset += 1;
continue;
}
if(str[offset] == '"') {
if(openQuote) {
if(!inProp && depth == 0 && type == Type.OBJECT)
propName = str.Substring(tokenTmp + 1, offset - tokenTmp - 1);
openQuote = false;
} else {
if(depth == 0 && type == Type.OBJECT)
tokenTmp = offset;
openQuote = true;
}
}
if(openQuote)
continue;
if(type == Type.OBJECT && depth == 0) {
if(str[offset] == ':') {
tokenTmp = offset + 1;
inProp = true;
}
}
if(str[offset] == '[' || str[offset] == '{') {
depth++;
} else if(str[offset] == ']' || str[offset] == '}') {
depth--;
}
//if (encounter a ',' at top level) || a closing ]/}
if((str[offset] == ',' && depth == 0) || depth < 0) {
inProp = false;
string inner = str.Substring(tokenTmp, offset - tokenTmp).Trim(WHITESPACE);
if(inner.Length > 0) {
if(type == Type.OBJECT)
keys.Add(propName);
if(maxDepth != -1) //maxDepth of -1 is the end of the line
list.Add(Create(inner, (maxDepth < -1) ? -2 : maxDepth - 1));
else if(storeExcessLevels)
list.Add(CreateBakedObject(inner));
}
tokenTmp = offset + 1;
}
}
}
} else type = Type.NULL;
} else type = Type.NULL; //If the string is missing, this is a null
//Profiler.EndSample();
}
#endregion
public bool IsNumber { get { return type == Type.NUMBER; } }
public bool IsNull { get { return type == Type.NULL; } }
public bool IsString { get { return type == Type.STRING; } }
public bool IsBool { get { return type == Type.BOOL; } }
public bool IsArray { get { return type == Type.ARRAY; } }
public bool IsObject { get { return type == Type.OBJECT; } }
public void Add(bool val) {
Add(Create(val));
}
public void Add(float val) {
Add(Create(val));
}
public void Add(int val) {
Add(Create(val));
}
public void Add(string str) {
Add(CreateStringObject(str));
}
public void Add(AddJSONConents content) {
Add(Create(content));
}
public void Add(JSONObject obj) {
if(obj) { //Don't do anything if the object is null
if(type != Type.ARRAY) {
type = Type.ARRAY; //Congratulations, son, you're an ARRAY now
if(list == null)
list = new List<JSONObject>();
}
list.Add(obj);
}
}
public void AddField(string name, bool val) {
AddField(name, Create(val));
}
public void AddField(string name, float val) {
AddField(name, Create(val));
}
public void AddField(string name, int val) {
AddField(name, Create(val));
}
public void AddField(string name, AddJSONConents content) {
AddField(name, Create(content));
}
public void AddField(string name, string val) {
AddField(name, CreateStringObject(val));
}
public void AddField(string name, JSONObject obj) {
if(obj) { //Don't do anything if the object is null
if(type != Type.OBJECT) {
if(keys == null)
keys = new List<string>();
if(type == Type.ARRAY) {
for(int i = 0; i < list.Count; i++)
keys.Add(i + "");
} else
if(list == null)
list = new List<JSONObject>();
type = Type.OBJECT; //Congratulations, son, you're an OBJECT now
}
keys.Add(name);
list.Add(obj);
}
}
public void SetField(string name, bool val) { SetField(name, Create(val)); }
public void SetField(string name, float val) { SetField(name, Create(val)); }
public void SetField(string name, int val) { SetField(name, Create(val)); }
public void SetField(string name, JSONObject obj) {
if(HasField(name)) {
list.Remove(this[name]);
keys.Remove(name);
}
AddField(name, obj);
}
public void RemoveField(string name) {
if(keys.IndexOf(name) > -1) {
list.RemoveAt(keys.IndexOf(name));
keys.Remove(name);
}
}
public delegate void FieldNotFound(string name);
public delegate void GetFieldResponse(JSONObject obj);
// Default parameters fix
public void GetField(ref bool field, string name) { GetField(ref field, name, null); }
public void GetField(ref bool field, string name, FieldNotFound fail) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].b;
return;
}
}
if(fail != null) fail.Invoke(name);
}
#if USEFLOAT
// Default parameters fix
public void GetField(ref float field, string name) { GetField(ref field, name, null); }
public void GetField(ref float field, string name, FieldNotFound fail) {
#else
// Default parameters fix
public void GetField(ref double field, string name) { GetField(ref field, name, null); }
public void GetField(ref double field, string name, FieldNotFound fail) {
#endif
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].n;
return;
}
}
if(fail != null) fail.Invoke(name);
}
// Default parameters fix
public void GetField(ref int field, string name) { GetField(ref field, name, null); }
public void GetField(ref int field, string name, FieldNotFound fail) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = (int)list[index].n;
return;
}
}
if(fail != null) fail.Invoke(name);
}
// Default parameters fix
public void GetField(ref uint field, string name) { GetField(ref field, name, null); }
public void GetField(ref uint field, string name, FieldNotFound fail) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = (uint)list[index].n;
return;
}
}
if(fail != null) fail.Invoke(name);
}
// Default parameters fix
public void GetField(ref string field, string name) { GetField(ref field, name, null); }
public void GetField(ref string field, string name, FieldNotFound fail) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].str;
return;
}
}
if(fail != null) fail.Invoke(name);
}
// Default parameters fix
public void GetField(string name, GetFieldResponse response) { GetField(name, response, null); }
public void GetField(string name, GetFieldResponse response, FieldNotFound fail) {
if(response != null && type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
response.Invoke(list[index]);
return;
}
}
if(fail != null) fail.Invoke(name);
}
public JSONObject GetField(string name) {
if(type == Type.OBJECT)
for(int i = 0; i < keys.Count; i++)
if(keys[i] == name)
return list[i];
return null;
}
public bool HasFields(string[] names) {
for(int i = 0; i < names.Length; i++)
if(!keys.Contains(names[i]))
return false;
return true;
}
public bool HasField(string name) {
if(type == Type.OBJECT)
for(int i = 0; i < keys.Count; i++)
if(keys[i] == name)
return true;
return false;
}
public void Clear() {
type = Type.NULL;
if(list != null)
list.Clear();
if(keys != null)
keys.Clear();
str = "";
n = 0;
b = false;
}
/// <summary>
/// Copy a JSONObject. This could probably work better
/// </summary>
/// <returns></returns>
public JSONObject Copy() {
return Create(Print());
}
/*
* The Merge function is experimental. Use at your own risk.
*/
public void Merge(JSONObject obj) {
MergeRecur(this, obj);
}
/// <summary>
/// Merge object right into left recursively
/// </summary>
/// <param name="left">The left (base) object</param>
/// <param name="right">The right (new) object</param>
static void MergeRecur(JSONObject left, JSONObject right) {
if(left.type == Type.NULL)
left.Absorb(right);
else if(left.type == Type.OBJECT && right.type == Type.OBJECT) {
for(int i = 0; i < right.list.Count; i++) {
string key = right.keys[i];
if(right[i].isContainer) {
if(left.HasField(key))
MergeRecur(left[key], right[i]);
else
left.AddField(key, right[i]);
} else {
if(left.HasField(key))
left.SetField(key, right[i]);
else
left.AddField(key, right[i]);
}
}
} else if(left.type == Type.ARRAY && right.type == Type.ARRAY) {
if(right.Count > left.Count) {
Debug.LogError("Cannot merge arrays when right object has more elements");
return;
}
for(int i = 0; i < right.list.Count; i++) {
if(left[i].type == right[i].type) { //Only overwrite with the same type
if(left[i].isContainer)
MergeRecur(left[i], right[i]);
else {
left[i] = right[i];
}
}
}
}
}
public void Bake() {
if(type != Type.BAKED) {
str = Print();
type = Type.BAKED;
}
}
public IEnumerable BakeAsync() {
if(type != Type.BAKED) {
foreach(string s in PrintAsync()) {
if(s == null)
yield return s;
else {
str = s;
}
}
type = Type.BAKED;
}
}
#pragma warning disable 219
// Default parameters fix
public string Print() { return Print(false); }
public string Print(bool pretty) {
StringBuilder builder = new StringBuilder();
Stringify(0, builder, pretty);
return builder.ToString();
}
// Default parameters fix
public IEnumerable<string> PrintAsync() { return PrintAsync(false); }
public IEnumerable<string> PrintAsync(bool pretty) {
StringBuilder builder = new StringBuilder();
printWatch.Reset();
printWatch.Start();
foreach(IEnumerable e in StringifyAsync(0, builder, pretty)) {
yield return null;
}
yield return builder.ToString();
}
#pragma warning restore 219
#region STRINGIFY
const float maxFrameTime = 0.008f;
static readonly Stopwatch printWatch = new Stopwatch();
// Default parameters fix
IEnumerable StringifyAsync(int depth, StringBuilder builder) { return StringifyAsync(depth, builder, false); }
IEnumerable StringifyAsync(int depth, StringBuilder builder, bool pretty) { //Convert the JSONObject into a string
//Profiler.BeginSample("JSONprint");
if(depth++ > MAX_DEPTH) {
Debug.Log("reached max depth!");
yield break;
}
if(printWatch.Elapsed.TotalSeconds > maxFrameTime) {
printWatch.Reset();
yield return null;
printWatch.Start();
}
switch(type) {
case Type.BAKED:
builder.Append(str);
break;
case Type.STRING:
builder.AppendFormat("\"{0}\"", str);
break;
case Type.NUMBER:
#if USEFLOAT
if(float.IsInfinity(n))
builder.Append(INFINITY);
else if(float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString());
break;
case Type.OBJECT:
builder.Append("{");
if(list.Count > 0) {
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
if(pretty)
builder.Append("\n");
#endif
for(int i = 0; i < list.Count; i++) {
string key = keys[i];
JSONObject obj = list[i];
if(obj) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
builder.AppendFormat("\"{0}\":", key);
foreach(IEnumerable e in obj.StringifyAsync(depth, builder, pretty))
yield return e;
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n");
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("}");
break;
case Type.ARRAY:
builder.Append("[");
if(list.Count > 0) {
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
for(int i = 0; i < list.Count; i++) {
if(list[i]) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
foreach(IEnumerable e in list[i].StringifyAsync(depth, builder, pretty))
yield return e;
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("]");
break;
case Type.BOOL:
if(b)
builder.Append("true");
else
builder.Append("false");
break;
case Type.NULL:
builder.Append("null");
break;
}
//Profiler.EndSample();
}
//TODO: Refactor Stringify functions to share core logic
/*
* I know, I know, this is really bad form. It turns out that there is a
* significant amount of garbage created when calling as a coroutine, so this
* method is duplicated. Hopefully there won't be too many future changes, but
* I would still like a more elegant way to optionaly yield
*/
// Default parameters fix
void Stringify(int depth, StringBuilder builder){ Stringify(depth, builder, false); }
void Stringify(int depth, StringBuilder builder, bool pretty) { //Convert the JSONObject into a string
//Profiler.BeginSample("JSONprint");
if(depth++ > MAX_DEPTH) {
Debug.Log("reached max depth!");
return;
}
switch(type) {
case Type.BAKED:
builder.Append(str);
break;
case Type.STRING:
builder.AppendFormat("\"{0}\"", str);
break;
case Type.NUMBER:
#if USEFLOAT
if(float.IsInfinity(n))
builder.Append(INFINITY);
else if(float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString());
break;
case Type.OBJECT:
builder.Append("{");
if(list.Count > 0) {
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
if(pretty)
builder.Append("\n");
#endif
for(int i = 0; i < list.Count; i++) {
string key = keys[i];
JSONObject obj = list[i];
if(obj) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
builder.AppendFormat("\"{0}\":", key);
obj.Stringify(depth, builder, pretty);
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n");
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("}");
break;
case Type.ARRAY:
builder.Append("[");
if(list.Count > 0) {
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
for(int i = 0; i < list.Count; i++) {
if(list[i]) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
list[i].Stringify(depth, builder, pretty);
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("]");
break;
case Type.BOOL:
if(b)
builder.Append("true");
else
builder.Append("false");
break;
case Type.NULL:
builder.Append("null");
break;
}
//Profiler.EndSample();
}
#endregion
public static implicit operator WWWForm(JSONObject obj) {
WWWForm form = new WWWForm();
for(int i = 0; i < obj.list.Count; i++) {
string key = i + "";
if(obj.type == Type.OBJECT)
key = obj.keys[i];
string val = obj.list[i].ToString();
if(obj.list[i].type == Type.STRING)
val = val.Replace("\"", "");
form.AddField(key, val);
}
return form;
}
public JSONObject this[int index] {
get {
if(list.Count > index) return list[index];
return null;
}
set {
if(list.Count > index)
list[index] = value;
}
}
public JSONObject this[string index] {
get {
return GetField(index);
}
set {
SetField(index, value);
}
}
public override string ToString() {
return Print();
}
public string ToString(bool pretty) {
return Print(pretty);
}
public Dictionary<string, string> ToDictionary() {
if(type == Type.OBJECT) {
Dictionary<string, string> result = new Dictionary<string, string>();
for(int i = 0; i < list.Count; i++) {
JSONObject val = list[i];
switch(val.type) {
case Type.STRING: result.Add(keys[i], val.str); break;
case Type.NUMBER: result.Add(keys[i], val.n + ""); break;
case Type.BOOL: result.Add(keys[i], val.b + ""); break;
default: Debug.LogWarning("Omitting object: " + keys[i] + " in dictionary conversion"); break;
}
}
return result;
}
Debug.LogWarning("Tried to turn non-Object JSONObject into a dictionary");
return null;
}
public static implicit operator bool(JSONObject o) {
return o != null;
}
#if POOLING
static bool pool = true;
public static void ClearPool() {
pool = false;
releaseQueue.Clear();
pool = true;
}
~JSONObject() {
if(pool && releaseQueue.Count < MAX_POOL_SIZE) {
type = Type.NULL;
list = null;
keys = null;
str = "";
n = 0;
b = false;
releaseQueue.Enqueue(this);
}
}
#endif
}
| |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.TestingHost.Utils;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.General
{
/// <summary>
/// Summary description for ObserverTests
/// </summary>
public class ObserverTests : HostedTestClusterEnsureDefaultStarted
{
private readonly TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(10);
private int callbackCounter;
private readonly bool[] callbacksRecieved = new bool[2];
// we keep the observer objects as instance variables to prevent them from
// being garbage collected permaturely (the runtime stores them as weak references).
private SimpleGrainObserver observer1;
private SimpleGrainObserver observer2;
public void TestInitialize()
{
callbackCounter = 0;
callbacksRecieved[0] = false;
callbacksRecieved[1] = false;
observer1 = null;
observer2 = null;
}
private ISimpleObserverableGrain GetGrain()
{
return GrainFactory.GetGrain<ISimpleObserverableGrain>(GetRandomGrainId());
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SimpleNotification()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(this.observer1);
await grain.Subscribe(reference);
await grain.SetA(3);
await grain.SetB(2);
Assert.True(await result.WaitForFinished(timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SimpleNotification_GeneratedFactory()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(3);
await grain.SetB(2);
Assert.True(await result.WaitForFinished(timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_SimpleNotification_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_SimpleNotification_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
if (a == 3 && b == 0)
callbacksRecieved[0] = true;
else if (a == 3 && b == 2)
callbacksRecieved[1] = true;
else
throw new ArgumentOutOfRangeException("Unexpected callback with values: a=" + a + ",b=" + b);
if (callbackCounter == 1)
{
// Allow for callbacks occurring in any order
Assert.True(callbacksRecieved[0] || callbacksRecieved[1]);
}
else if (callbackCounter == 2)
{
Assert.True(callbacksRecieved[0] && callbacksRecieved[1]);
result.Done = true;
}
else
{
Assert.True(false);
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_DoubleSubscriptionSameReference()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionSameReference_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(1); // Use grain
try
{
await grain.Subscribe(reference);
}
catch (TimeoutException)
{
throw;
}
catch (Exception exc)
{
Exception baseException = exc.GetBaseException();
logger.Info("Received exception: {0}", baseException);
Assert.IsAssignableFrom<OrleansException>(baseException);
if (!baseException.Message.StartsWith("Cannot subscribe already subscribed observer"))
{
Assert.True(false, "Unexpected exception message: " + baseException);
}
}
await grain.SetA(2); // Use grain
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetA(2)", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_DoubleSubscriptionSameReference_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_DoubleSubscriptionSameReference_Callback for {0} time with a={1} and b={2}", callbackCounter, a, b);
Assert.True(callbackCounter <= 2, "Callback has been called more times than was expected " + callbackCounter);
if (callbackCounter == 2)
{
result.Continue = true;
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_SubscribeUnsubscribe()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SubscribeUnsubscribe_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(5);
Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await grain.Unsubscribe(reference);
await grain.SetB(3);
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_SubscribeUnsubscribe_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_SubscribeUnsubscribe_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
Assert.True(callbackCounter < 2, "Callback has been called more times than was expected.");
Assert.Equal(5, a);
Assert.Equal(0, b);
result.Continue = true;
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_Unsubscribe()
{
TestInitialize();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(null, null);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
try
{
await grain.Unsubscribe(reference);
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
catch (TimeoutException)
{
throw;
}
catch (Exception exc)
{
Exception baseException = exc.GetBaseException();
if (!(baseException is OrleansException))
Assert.True(false);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_DoubleSubscriptionDifferentReferences()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result);
ISimpleGrainObserver reference1 = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
observer2 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result);
ISimpleGrainObserver reference2 = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer2);
await grain.Subscribe(reference1);
await grain.Subscribe(reference2);
grain.SetA(6).Ignore();
Assert.True(await result.WaitForFinished(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference1);
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference2);
}
void ObserverTest_DoubleSubscriptionDifferentReferences_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_DoubleSubscriptionDifferentReferences_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
Assert.True(callbackCounter < 3, "Callback has been called more times than was expected.");
Assert.Equal(6, a);
Assert.Equal(0, b);
if (callbackCounter == 2)
result.Done = true;
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_DeleteObject()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_DeleteObject_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(5);
Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
await grain.SetB(3);
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout));
}
void ObserverTest_DeleteObject_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_DeleteObject_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
Assert.True(callbackCounter < 2, "Callback has been called more times than was expected.");
Assert.Equal(5, a);
Assert.Equal(0, b);
result.Continue = true;
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SubscriberMustBeGrainReference()
{
TestInitialize();
await Xunit.Assert.ThrowsAsync(typeof(NotSupportedException), async () =>
{
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result);
ISimpleGrainObserver reference = observer1;
// Should be: GrainFactory.CreateObjectReference<ISimpleGrainObserver>(obj);
await grain.Subscribe(reference);
// Not reached
});
}
internal class SimpleGrainObserver : ISimpleGrainObserver
{
readonly Action<int, int, AsyncResultHandle> action;
readonly AsyncResultHandle result;
public SimpleGrainObserver(Action<int, int, AsyncResultHandle> action, AsyncResultHandle result)
{
this.action = action;
this.result = result;
}
#region ISimpleGrainObserver Members
public void StateChanged(int a, int b)
{
GrainClient.Logger.Verbose("SimpleGrainObserver.StateChanged a={0} b={1}", a, b);
action?.Invoke(a, b, result);
}
#endregion
}
}
}
| |
// Copyright (C) 2005 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the AbstractDataIndexer.java source file found in the
//original java implementation of MaxEnt.
using System;
using System.Collections.Generic;
namespace SharpEntropy
{
/// <summary>
/// Abstract base for DataIndexer implementations.
/// </summary>
/// <author>
/// Tom Morton
/// </author>
/// <author>
/// Richard J. Northedge
/// </author>
public abstract class AbstractDataIndexer : ITrainingDataIndexer
{
private int[][] mContexts;
private int[] mOutcomeList;
private int[] mNumTimesEventsSeen;
private string[] mPredicateLabels;
private string[] mOutcomeLabels;
/// <summary>
/// Gets an array of context data calculated from the training data.
/// </summary>
/// <returns>
/// Array of integer arrays, each containing the context data for an event.
/// </returns>
public virtual int[][] GetContexts()
{
return mContexts;
}
/// <summary>
/// Sets the array of context data calculated from the training data.
/// </summary>
/// <param name="newContexts">
/// Array of integer arrays, each containing the context data for an event.
/// </param>
protected internal void SetContexts(int[][] newContexts)
{
mContexts = newContexts;
}
/// <summary>
/// Gets an array indicating how many times each event is seen.
/// </summary>
/// <returns>
/// Integer array with event frequencies.
/// </returns>
public virtual int[] GetNumTimesEventsSeen()
{
return mNumTimesEventsSeen;
}
/// <summary>
/// Sets an array indicating how many times each event is seen.
/// </summary>
/// <param name="newNumTimesEventsSeen">
/// Integer array with event frequencies.
/// </param>
protected internal void SetNumTimesEventsSeen(int[] newNumTimesEventsSeen)
{
mNumTimesEventsSeen = newNumTimesEventsSeen;
}
/// <summary>
/// Gets an outcome list.
/// </summary>
/// <returns>
/// Integer array of outcomes.
/// </returns>
public virtual int[] GetOutcomeList()
{
return mOutcomeList;
}
/// <summary>
/// Sets an outcome list.
/// </summary>
/// <param name="newOutcomeList">
/// Integer array of outcomes.
/// </param>
protected internal void SetOutcomeList(int[] newOutcomeList)
{
mOutcomeList = newOutcomeList;
}
/// <summary>
/// Gets an array of predicate labels.
/// </summary>
/// <returns>
/// Array of predicate labels.
/// </returns>
public virtual string[] GetPredicateLabels()
{
return mPredicateLabels;
}
/// <summary>
/// Sets an array of predicate labels.
/// </summary>
/// <param name="newPredicateLabels">
/// Array of predicate labels.
/// </param>
protected internal void SetPredicateLabels(string[] newPredicateLabels)
{
mPredicateLabels = newPredicateLabels;
}
/// <summary>
/// Gets an array of outcome labels.
/// </summary>
/// <returns>
/// Array of outcome labels.
/// </returns>
public virtual string[] GetOutcomeLabels()
{
return mOutcomeLabels;
}
/// <summary>
/// Sets an array of outcome labels.
/// </summary>
/// <param name="newOutcomeLabels">
/// Array of outcome labels.
/// </param>
protected internal void SetOutcomeLabels(string[] newOutcomeLabels)
{
mOutcomeLabels = newOutcomeLabels;
}
/// <summary>
/// Sorts and uniques the array of comparable events. This method
/// will alter the eventsToCompare array -- it does an in place
/// sort, followed by an in place edit to remove duplicates.
/// </summary>
/// <param name="eventsToCompare">
/// a List of <code>ComparableEvent</code> values
/// </param>
protected internal virtual void SortAndMerge(List<ComparableEvent> eventsToCompare)
{
eventsToCompare.Sort();
int eventCount = eventsToCompare.Count;
int uniqueEventCount = 1; // assertion: eventsToCompare.length >= 1
if (eventCount <= 1)
{
return; // nothing to do; edge case (see assertion)
}
ComparableEvent comparableEvent = eventsToCompare[0];
for (int currentEvent = 1; currentEvent < eventCount; currentEvent++)
{
ComparableEvent eventToCompare = eventsToCompare[currentEvent];
if (comparableEvent.Equals(eventToCompare))
{
comparableEvent.SeenCount++; // increment the seen count
eventsToCompare[currentEvent] = null; // kill the duplicate
}
else
{
comparableEvent = eventToCompare; // a new champion emerges...
uniqueEventCount++; // increment the # of unique events
}
}
//NotifyProgress("done. Reduced " + eventCount + " events to " + uniqueEventCount + ".");
mContexts = new int[uniqueEventCount][];
mOutcomeList = new int[uniqueEventCount];
mNumTimesEventsSeen = new int[uniqueEventCount];
for (int currentEvent = 0, currentStoredEvent = 0; currentEvent < eventCount; currentEvent++)
{
ComparableEvent eventToStore = eventsToCompare[currentEvent];
if (null == eventToStore)
{
continue; // this was a dupe, skip over it.
}
mNumTimesEventsSeen[currentStoredEvent] = eventToStore.SeenCount;
mOutcomeList[currentStoredEvent] = eventToStore.Outcome;
mContexts[currentStoredEvent] = eventToStore.GetPredicateIndexes();
++currentStoredEvent;
}
}
/// <summary>
/// Utility method for creating a string[] array from a dictionary whose
/// keys are labels (strings) to be stored in the array and whose
/// values are the indices (integers) at which the corresponding
/// labels should be inserted.
/// </summary>
/// <param name="labelToIndexMap">
/// a <code>Dictionary</code> value
/// </param>
/// <returns>
/// a <code>string[]</code> value
/// </returns>
protected internal static string[] ToIndexedStringArray(Dictionary<string, int> labelToIndexMap)
{
string[] indexedArray = new string[labelToIndexMap.Count];
int[] indices = new int[labelToIndexMap.Count];
labelToIndexMap.Keys.CopyTo(indexedArray, 0);
labelToIndexMap.Values.CopyTo(indices, 0);
Array.Sort(indices, indexedArray);
return indexedArray;
}
}
}
| |
using Elm327.Core.ObdModes;
using System;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
namespace Elm327.Core
{
/// <summary>
/// A driver for the ELM327 chip (www.elmelectronics.com). This class provides the
/// basic communication infrastructure for the ELM.
/// </summary>
public class Driver : IDisposable
{
#region Constants
/// <summary>
/// The baud rate used to communicate with the ELM. TODO: We need
/// to enable a high baud rate (500kbps, which is the max supported
/// by the ELM chip), but right now it is locked to 38400. Pin 6 of
/// the ELM is expected to be tied to a high level to enable this baud
/// rate.
/// </summary>
private const int BAUD_RATE = 38400;
/// <summary>
/// The character that will be sent by the ELM when it is ready to
/// accept commands.
/// </summary>
private const char CHIP_READY_PROMPT_CHAR = '>';
/// <summary>
/// The maximum amount of time, in seconds, to wait for the ELM to
/// send us a message response. A timeout error will occur if the chip
/// doesn't respond within this amount of time.
/// </summary>
private const int MAX_WAIT_RECEIVE_SECONDS = 10;
/// <summary>
/// The message reported by the ELM when there's a problem communicating
/// on the CAN bus.
/// </summary>
private const string MESSAGE_CAN_ERROR = "CAN ERROR";
/// <summary>
/// The message reported by the ELM when it is unable to connect via
/// one of the OBD protocols.
/// </summary>
private const string MESSAGE_NO_CONNECTION = "UNABLE TO CONNECT";
/// <summary>
/// The message reported by the ELM when a bus request times out or
/// an unsupported PID is requested.
/// </summary>
private const string MESSAGE_NO_DATA = "NO DATA";
/// <summary>
/// The message reported by the ELM when it is performing a search on
/// one of the protocols.
/// </summary>
private static string MESSAGE_SEARCHING = "SEARCHING..." + Driver.MESSAGE_TERMINATOR_CHAR;
/// <summary>
/// The character used to indicate the end of a message sent to or
/// received from the ELM.
/// </summary>
internal const char MESSAGE_TERMINATOR_CHAR = '\r';
/// <summary>
/// The size of the receive buffer for data received from the ELM.
/// </summary>
private const int RECEIVE_BUFFER_SIZE = 1024;
#endregion
#region Variables
/// <summary>
/// Stores the currently selected OBD protocol.
/// </summary>
private ObdProtocolType protocolType;
/// <summary>
/// The buffer used to hold data received from the ELM.
/// </summary>
private byte[] receiveBuffer;
/// <summary>
/// The serial port used to communicate with the ELM. Note that
/// we typically put a lock() statement around the use of this
/// object to prevent concurrency issues.
/// </summary>
private SerialPort serialPort;
#endregion
#region Event Definitions
/// <summary>
/// Basic delegate used for ELM events. This will probably change.
/// </summary>
public delegate void Elm327EventHandler();
/// <summary>
/// Fired when a CAN bus error has occurred. This probably means an
/// incorrect CAN protocol was chosen or there is a wiring issue with
/// the ELM327 circuit.
/// </summary>
public event Elm327EventHandler CanBusError;
/// <summary>
/// Fired when the ELM reports that it is unable to connect to
/// the vehicle via one of the OBD protocols. Note that although the event
/// is named <see cref="ObdConnectionLost"/>, it could also mean that there
/// was never an available connection to start with. If this event is fired,
/// you should probably attempt to close and reopen the connection to the ELM.
/// </summary>
//public event Elm327EventHandler ObdConnectionLost;
/// <summary>
///
/// </summary>
public event EventHandler<ErrorEventArgs> ObdErrorEvent;
#endregion
#region Constructors
/// <summary>
/// Creates an instance of the ELM327 driver.
/// </summary>
/// <param name="serialPortName">The name of the serial port the ELM is connected to
/// ("COM1", "COM2", etc.).</param>
/// <param name="protocolType">The desired OBD protocol to use. Using
/// <see cref="Elm327.Core.Driver.ElmObdProtocolType.Automatic"/> is usually a good idea.</param>
/// <param name="measuringUnit">The desired unit type for reporting readings.</param>
public Driver(
string serialPortName,
ObdProtocolType protocolType,
MeasuringUnitType measuringUnit)
{
this.MeasuringUnitType = measuringUnit;
this.ElmVersionID = string.Empty;
this.ObdMode01 = new ObdGenericMode01(this);
this.ObdMode09 = new ObdGenericMode09(this);
this.protocolType = protocolType;
this.receiveBuffer = new byte[Driver.RECEIVE_BUFFER_SIZE];
this.serialPort = new SerialPort(
serialPortName,
Driver.BAUD_RATE,
Parity.None,
8,
StopBits.One);
this.serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(this.UartErrorReceived);
}
/// <summary>
/// Creates an instance of the ELM327 driver.
/// </summary>
/// <param name="serialPortName">The name of the serial port the ELM is connected to
/// ("COM1", "COM2", etc.).</param>
public Driver(string serialPortName)
: this(serialPortName, ObdProtocolType.Automatic, MeasuringUnitType.English)
{
}
#endregion
#region Public Instance Properties
/// <summary>
/// Gets the battery voltage reading. Note that this value is read
/// directly off the supply pin from the OBD port.
/// </summary>
public double BatteryVoltage
{
get
{
try
{
// The reading will come back as something like "12.7V", so get
// rid of the 'V' and Double.Parse() the rest
string reading = this.SendAndReceiveMessage("ATRV");
if (reading != null && reading != string.Empty)
return Double.Parse(reading.Substring(0, reading.Length - 1));
else
return 0;
}
catch (Exception exception)
{
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(exception));
}
return 0;
}
}
}
/// <summary>
/// Gets the version identifier for the connected ELM chip.
/// </summary>
public string ElmVersionID
{
get;
private set;
}
/// <summary>
/// Contains methods and properties for retrieving generic
/// OBD mode 01 PIDs.
/// </summary>
public ObdGenericMode01 ObdMode01
{
get;
private set;
}
/// <summary>
/// Contains methods and properties for retrieving generic
/// OBD mode 09 PIDs.
/// </summary>
public ObdGenericMode09 ObdMode09
{
get;
private set;
}
/// <summary>
/// Gets or sets the measuring unit. Setting this property will
/// affect the values of OBD readings returned. The value is set
/// to <see cref="MeasuringUnitType.English"/> by default.
/// </summary>
public MeasuringUnitType MeasuringUnitType
{
get;
set;
}
/// <summary>
/// Gets or sets the current OBD protocol. Note that if this value was originally
/// set to <see cref="Elm327.Core.Driver.ElmObdProtocolType.Automatic"/>, the value you
/// get when requesting this property should be the actual protocol that
/// is in use.
/// </summary>
public ObdProtocolType ProtocolType
{
get
{
return this.protocolType;
}
set
{
this.SendAndReceiveMessage("ATSP" + (char)value);
this.protocolType = value;
}
}
#endregion
#region Private Instance Methods
/// <summary>
/// Returns a message received from the ELM. Note that this call
/// waits until the ready prompt character is received from the ELM
/// before returning control.
/// </summary>
/// <returns>The received message. If a null value is returned, it means
/// either an error occurred during the read attempt or a timeout
/// occurred while waiting for the ELM to respond.</returns>
private string ReceiveMessage()
{
try
{
lock (this.serialPort)
{
// Keep reading from the serial connection until the ELM sends the
// ready prompt character or we time out. We wait for the ready prompt
// because while most responses from the ELM will be only one line,
// some will be multiline, so we need to keep reading lines until we
// receive the ready prompt.
DateTime timeStarted = DateTime.Now;
int i = 0;
do
{
if (this.serialPort.BytesToRead > 0 && this.serialPort.Read(this.receiveBuffer, i, 1) > 0)
{
if (this.receiveBuffer[i] == Driver.CHIP_READY_PROMPT_CHAR)
{
string message = new string(
Encoding.UTF8.GetChars(this.receiveBuffer),
0,
i);
// Trim the message to the point just before the last EOL terminator
message = message.Substring(0, message.LastIndexOf(Driver.MESSAGE_TERMINATOR_CHAR) - 1).Trim();
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(new IOException("RCV <- " + message)));
}
if (message.IndexOf(Driver.MESSAGE_NO_DATA) > -1)
{
// A request timed out or a PID not supported by an ECU
// was requested
return null;
}
else if (message.IndexOf(Driver.MESSAGE_NO_CONNECTION) > -1)
{
// The ELM is unable to connect to the vehicle's OBD system for
// some reason
//throw new InvalidOperationException
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(new InvalidOperationException("Connection lost!")));
}
//if (this.ObdConnectionLost != null)
// this.ObdConnectionLost();
return null;
}
else if (message.IndexOf(Driver.MESSAGE_CAN_ERROR) > -1)
{
if (this.CanBusError != null)
this.CanBusError();
return null;
}
else if (message.IndexOf(Driver.MESSAGE_SEARCHING) > -1)
{
// If the ELM returned a "SEARCHING..." message, trim it
// out before returning to the caller
return
message.Length > Driver.MESSAGE_SEARCHING.Length ?
message.Substring(Driver.MESSAGE_SEARCHING.Length) :
string.Empty;
}
else
return message;
}
i++;
}
Thread.Sleep(1);
}
while (timeStarted.AddSeconds(Driver.MAX_WAIT_RECEIVE_SECONDS) > DateTime.Now);
// Reaching this point means we've waited too long for the chip to send us a response
return null;
}
}
catch (Exception exception)
{
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(exception));
}
return null;
}
}
#endregion
#region Internal Instance Methods
/// <summary>
/// Attempts to send a message to the ELM and then receive a response from it.
/// Note that this call waits until the ready prompt character is received
/// from the ELM before returning control.
/// </summary>
/// <param name="message">The message to send to the ELM. The message terminator
/// character will be appended to this message automatically.</param>
/// <returns>The received message. If a null value is returned, it means
/// either an error occurred during the send or receive attempt.</returns>
internal string SendAndReceiveMessage(string message)
{
lock (this.serialPort)
{
try
{
this.serialPort.Write(
Encoding.UTF8.GetBytes(message + Driver.MESSAGE_TERMINATOR_CHAR),
0,
message.Length + 1);
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(new IOException("SND -> " + message)));
}
}
catch (Exception exception)
{
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(exception));
}
return null;
}
return this.ReceiveMessage();
}
}
#endregion
#region Public Instance Methods
/// <summary>
/// Attempts to open a connection to the ELM chip.
/// </summary>
/// <returns>A value indicating the result of the connection attempt.</returns>
public ConnectionResultType Connect()
{
// Try to force the connection closed if it is open and the caller wants to
// reinitialize
lock (this.serialPort)
{
if (this.serialPort.IsOpen)
{
// TODO: This is untested
try
{
this.serialPort.Close();
}
catch (Exception exception)
{
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(exception));
}
}
}
}
// Try to open the COM port
lock (this.serialPort)
{
try
{
this.serialPort.Open();
//this.serialPort.DiscardInBuffer()//.Flush();
this.serialPort.DiscardInBuffer();
this.serialPort.DiscardOutBuffer();
}
catch (Exception exception)
{
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(exception));
}
return ConnectionResultType.NoConnectionToElm;
}
}
// Perform a reset on the ELM. If we get a null back from this call,
// it means we're unable to see it (probably a wiring issue).
if (this.SendAndReceiveMessage("ATZ") == null)
return ConnectionResultType.NoConnectionToElm;
// Turn line feeds and echo off, turn on space printing (as our code currently
// expects it) and retrieve the ELM's version information
// TODO: ELM responses will be faster if we turn off space printing, but leaving
// as-is for now to enable easy message parsing
this.SendAndReceiveMessage("ATL0");
this.SendAndReceiveMessage("ATE0");
this.SendAndReceiveMessage("ATS1");
this.ElmVersionID = this.SendAndReceiveMessage("ATI");
// Set the caller's desired protocol, then make a simple "0100" call to
// make sure the ECU responds. If we get anything back other than something
// that starts with "41 00", it means the ELM can't talk to the OBD
// system.
this.ProtocolType = this.protocolType;
string response = this.SendAndReceiveMessage("0100");
if (response == null || response.IndexOf("41 00") != 0)
return ConnectionResultType.NoConnectionToObd;
// Ask the ELM to give us the protocol it's using. We need to ask for
// this value in case the user chose the "Automatic" setting for protocol
// type, so we'll know which protocol was actually selected by the ELM.
response = this.SendAndReceiveMessage("ATDPN");
if (response != null && response.Length > 0)
{
try
{
// 'A' will be the first character returned if the user chose
// automatic search mode
if (response[0] == 'A' && response.Length > 1)
this.protocolType = (ObdProtocolType)response[1];
else
this.protocolType = (ObdProtocolType)response[0];
}
catch (Exception exception)
{
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(exception));
}
}
}
return ConnectionResultType.Connected;
}
/// <summary>
/// Attempts to disconnect from the ELM chip.
/// </summary>
public void Disconnect()
{
try
{
// Simply try to close the serial connection
if (this.serialPort.IsOpen)
this.serialPort.Close();
}
catch (Exception exception)
{
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(exception));
}
}
}
/// <summary>
/// Cleans up all resources used by the driver.
/// </summary>
public void Dispose()
{
this.Disconnect();
try
{
this.serialPort = null;
}
catch (Exception exception)
{
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(exception));
}
}
}
#endregion
#region Private Static Methods
/// <summary>
/// Called when a serial communication error occurs.
/// </summary>
private void UartErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
// TODO
if (this.ObdErrorEvent != null)
{
this.ObdErrorEvent(this, new ErrorEventArgs(new Exception(e.ToString())));
}
}
#endregion
}
}
| |
#pragma warning disable 0168
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using nHydrate.Generator.Common.EventArgs;
namespace nHydrate.Generator.ModelUI
{
public partial class StatisticsForm : Form
{
public StatisticsForm()
{
InitializeComponent();
this.IsExpanded = false;
lblHeader.Text = "These files were found in folders with generated files, however they were not part of the generation. They are most likely old files that need to be deleted. Please verify that you wish to remove these files.";
this.KeyDown += StatisticsForm_KeyDown;
}
private void StatisticsForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.Q)
{
var text = "Extension Directory: " + nHydrate.Generator.Common.GeneratorFramework.AddinAppData.Instance.ExtensionDirectory + "\n" +
"Current Location: " + System.Reflection.Assembly.GetExecutingAssembly().Location + "\n" +
"DTE: " + nHydrate.Generator.Common.Util.EnvDTEHelper.Instance.Version;
MessageBox.Show(text, "Debug", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#region Class Members
private bool _isExpanded = false;
private List<ProjectItemGeneratedEventArgs> _generatedFileList = new List<ProjectItemGeneratedEventArgs>();
#endregion
#region Property Implementations
public bool IsExpanded
{
get { return _isExpanded; }
set
{
_isExpanded = value;
if (this.IsExpanded)
{
//Expand
this.FormBorderStyle = FormBorderStyle.Sizable;
this.Size = new Size(this.MinimumSize.Width, this.MinimumSize.Height * 2);
this.cmdDetails.Text = "<< Details";
}
else
{
//Shrink
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.Size = this.MinimumSize;
this.cmdDetails.Text = "Details >>";
}
}
}
public string DisplayText
{
get { return txtStats.Text; }
set { txtStats.Text = value; }
}
public List<ProjectItemGeneratedEventArgs> GeneratedFileList
{
get { return _generatedFileList; }
set
{
try
{
_generatedFileList = value;
if (_generatedFileList == null)
_generatedFileList = new List<ProjectItemGeneratedEventArgs>();
lstFile.Items.Clear();
//Load the parent folders
var folderList = new ArrayList();
foreach (var e in this.GeneratedFileList)
{
var fileName = e.FullName;
if (!string.IsNullOrEmpty(fileName))
{
var fi = new FileInfo(fileName);
if (!folderList.Contains(fi.DirectoryName))
folderList.Add(fi.DirectoryName);
}
}
//Now we have a folder list so load all files in all folders
foreach (string folderName in folderList)
{
var di = new DirectoryInfo(folderName);
var fileList = di.GetFiles("*.*");
foreach (var fi in fileList)
{
//Skip the projects
if ((fi.Extension.ToLower() != ".csproj") &&
(fi.Extension.ToLower() != ".scc") &&
(fi.Extension.ToLower() != ".vssscc") &&
(!fi.FullName.ToLower().Contains(".csproj.")))
{
lstFile.Items.Add(fi.FullName);
}
}
}
//Now loop and remove the items that were generated
foreach (var e in this.GeneratedFileList)
{
var fileName = e.FullName;
if (!string.IsNullOrEmpty(fileName))
{
var fi = new FileInfo(fileName);
lstFile.Items.Remove(fi.FullName);
}
}
}
catch (Exception ex)
{
throw;
}
}
}
#endregion
#region Button Handlers
private void cmdDetails_Click(object sender, EventArgs e)
{
this.IsExpanded = !this.IsExpanded;
}
private void cmdOK_Click(object sender, EventArgs e)
{
this.Close();
}
private void cmdDelete_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you wish to delete all checked files?", "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
var sortedList = new SortedDictionary<string, ProjectItemGeneratedEventArgs>();
foreach (var item in this.GeneratedFileList)
{
sortedList.Add(item.FullName, item);
}
var indexes = new List<int>();
for (var ii = 0; ii < lstFile.Items.Count; ii++)
{
if (this.lstFile.GetItemChecked(ii))
{
var fileName = (string)lstFile.Items[ii];
indexes.Add(ii);
var fi = new FileInfo(fileName);
fi.Attributes = FileAttributes.Normal;
fi.Delete();
}
}
//Remove the deleted file entry
for (var jj = indexes.Count - 1; jj >= 0; jj--)
lstFile.Items.RemoveAt((int)indexes[jj]);
}
catch (Exception ex)
{
throw;
}
}
}
private void cmdCheckAll_Click(object sender, EventArgs e)
{
for (var ii = 0; ii < lstFile.Items.Count; ii++)
lstFile.SetItemChecked(ii, true);
}
private void cmdUncheckAll_Click(object sender, EventArgs e)
{
for (var ii = 0; ii < lstFile.Items.Count; ii++)
lstFile.SetItemChecked(ii, false);
}
#endregion
}
}
| |
/*
* Copyright (c) Intel Corporation
* 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 the Intel Corporation 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 INTEL OR ITS
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Http;
using CableBeachMessages;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
using Caps = OpenSim.Framework.Capabilities.Caps;
using RegionInfo = CableBeachMessages.RegionInfo;
[assembly: Addin("ModCableBeach", "0.1")]
[assembly: AddinDependency("OpenSim", "0.5")]
namespace ModCableBeach
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class ModCableBeach : ISharedRegionModule
{
private static readonly ILog m_Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly Dictionary<string, string> DEFAULT_CAPS_PATHS;
private bool m_Enabled = false;
private Dictionary<ulong, WorldServiceConnector> m_regionWorldServiceConnectors = new Dictionary<ulong, WorldServiceConnector>();
public Type ReplaceableInterface { get { return null; } }
public bool IsSharedModule { get { return true; } }
/// <summary>Name of this region module</summary>
public string Name
{
get { return "ModCableBeach"; }
}
static ModCableBeach()
{
DEFAULT_CAPS_PATHS = new Dictionary<string, string>();
DEFAULT_CAPS_PATHS.Add(CableBeachServices.ASSET_CREATE_ASSET, "/assets/create_asset");
DEFAULT_CAPS_PATHS.Add(CableBeachServices.FILESYSTEM_CREATE_FILESYSTEM, "/filesystem/create_filesystem");
DEFAULT_CAPS_PATHS.Add(CableBeachServices.FILESYSTEM_CREATE_OBJECT, "/filesystem/create_object");
DEFAULT_CAPS_PATHS.Add(CableBeachServices.FILESYSTEM_GET_ACTIVE_GESTURES, "/filesystem/get_active_gestures");
DEFAULT_CAPS_PATHS.Add(CableBeachServices.FILESYSTEM_GET_FILESYSTEM_SKELETON, "/filesystem/get_filesystem_skeleton");
DEFAULT_CAPS_PATHS.Add(CableBeachServices.FILESYSTEM_GET_FOLDER_CONTENTS, "/filesystem/get_folder_contents");
DEFAULT_CAPS_PATHS.Add(CableBeachServices.FILESYSTEM_GET_FOLDER_FOR_TYPE, "/filesystem/get_folder_for_type");
DEFAULT_CAPS_PATHS.Add(CableBeachServices.FILESYSTEM_GET_OBJECT, "/filesystem/get_object");
DEFAULT_CAPS_PATHS.Add(CableBeachServices.FILESYSTEM_GET_ROOT_FOLDER, "/filesystem/get_root_folder");
DEFAULT_CAPS_PATHS.Add(CableBeachServices.FILESYSTEM_PURGE_FOLDER, "/filesystem/purge_folder");
DEFAULT_CAPS_PATHS.Add(CableBeachServices.FILESYSTEM_DELETE_OBJECT, "/filesystem/delete_object");
}
public void Initialise(IConfigSource source)
{
WorldServiceConnector.OnWorldServiceConnectorLoaded += WorldServiceConnectorLoadedHandler;
m_Log.Info("[CABLE BEACH MOD]: ModCableBeach initialized");
}
public void PostInitialise()
{
}
public void Close()
{
if (m_Enabled)
{
m_Enabled = false;
MainServer.Instance.RemoveLLSDHandler("/enable_client", EnableClientMessageHandler);
MainServer.Instance.RemoveLLSDHandler("/close_agent_connection", CloseAgentConnectionHandler);
}
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
{
if (MainServer.Instance != null)
{
m_Enabled = true;
MainServer.Instance.AddLLSDHandler("/enable_client", EnableClientMessageHandler);
MainServer.Instance.AddLLSDHandler("/close_agent_connection", CloseAgentConnectionHandler);
m_Log.Info("[CABLE BEACH MOD]: Cable Beach service endpoints initialized");
}
else
{
m_Log.Error("[CABLE BEACH MOD]: No running HTTP server, Cable Beach service endpoints will not be available");
}
}
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
}
public static bool TryGetDefaultCap(Uri baseUri, string capIdentifier, out Uri capability)
{
capability = null;
if (baseUri == null || String.IsNullOrEmpty(capIdentifier))
return false;
string fragment;
if (DEFAULT_CAPS_PATHS.TryGetValue(capIdentifier, out fragment))
{
capability = new Uri(baseUri, fragment);
return true;
}
return false;
}
/// <summary>
/// Event handler that is fired when the world service connector is loaded
/// </summary>
/// <param name="instance">Reference to the world service connector</param>
private void WorldServiceConnectorLoadedHandler(WorldServiceConnector instance)
{
m_regionWorldServiceConnectors[instance.Scene.RegionInfo.RegionHandle] = instance;
m_Log.Info("[CABLE BEACH MOD]: Registered region " + instance.Scene.RegionInfo.RegionName);
}
#region LLSD Handlers
private OSD EnableClientMessageHandler(string path, OSD request, string endpoint)
{
EnableClientMessage message = new EnableClientMessage();
EnableClientReplyMessage reply = new EnableClientReplyMessage();
if (request.Type == OSDType.Map)
{
message.Deserialize((OSDMap)request);
WorldServiceConnector wsConnector;
if (m_regionWorldServiceConnectors.TryGetValue(message.RegionHandle, out wsConnector))
{
Scene scene = wsConnector.Scene;
AgentCircuitData agentData = new AgentCircuitData();
agentData.AgentID = message.AgentID;
agentData.BaseFolder = UUID.Zero; // TODO: What is this?
agentData.CapsPath = CapsUtil.GetRandomCapsObjectPath();
agentData.child = message.ChildAgent;
agentData.circuitcode = (uint)message.CircuitCode;
agentData.firstname = GetStringAttribute(message.Attributes, AvatarAttributes.FIRST_NAME);
agentData.lastname = GetStringAttribute(message.Attributes, AvatarAttributes.LAST_NAME);
agentData.SecureSessionID = message.SecureSessionID;
agentData.SessionID = message.SessionID;
agentData.startpos = GetVector3Attribute(message.Attributes, AvatarAttributes.LAST_POSITION);
UserAgentData useragent = new UserAgentData();
useragent.AgentIP = message.IP.ToString();
useragent.AgentOnline = true;
useragent.AgentPort = 0u;
useragent.Handle = scene.RegionInfo.RegionHandle;
useragent.InitialRegion = scene.RegionInfo.RegionID;
useragent.LoginTime = Util.UnixTimeSinceEpoch();
useragent.LogoutTime = 0;
useragent.Position = agentData.startpos;
useragent.Region = useragent.InitialRegion;
useragent.SecureSessionID = agentData.SecureSessionID;
useragent.SessionID = agentData.SessionID;
UserProfileData userProfile = new UserProfileData();
userProfile.AboutText = GetStringAttribute(message.Attributes, AvatarAttributes.BIOGRAPHY);
userProfile.CanDoMask = (uint)GetIntegerAttribute(message.Attributes, AvatarAttributes.CAN_DO);
userProfile.Created = (int)Utils.DateTimeToUnixTime(GetDateAttribute(message.Attributes, AvatarAttributes.BIRTH_DATE));
userProfile.CurrentAgent = useragent;
userProfile.CustomType = "CableBeach";
userProfile.FirstLifeAboutText = GetStringAttribute(message.Attributes, AvatarAttributes.FIRST_LIFE_BIOGRAPHY);
userProfile.FirstLifeImage = GetUUIDAttribute(message.Attributes, AvatarAttributes.FIRST_LIFE_IMAGE_ID);
userProfile.FirstName = agentData.firstname;
userProfile.GodLevel = GetIntegerAttribute(message.Attributes, AvatarAttributes.GOD_LEVEL);
userProfile.HomeLocation = GetVector3Attribute(message.Attributes, AvatarAttributes.HOME_POSITION);
userProfile.HomeLocationX = userProfile.HomeLocation.X;
userProfile.HomeLocationY = userProfile.HomeLocation.Y;
userProfile.HomeLocationZ = userProfile.HomeLocation.Z;
userProfile.HomeLookAt = GetVector3Attribute(message.Attributes, AvatarAttributes.HOME_LOOKAT);
userProfile.HomeLookAtX = userProfile.HomeLookAt.X;
userProfile.HomeLookAtY = userProfile.HomeLookAt.Y;
userProfile.HomeLookAtZ = userProfile.HomeLookAt.Z;
userProfile.HomeRegionID = GetUUIDAttribute(message.Attributes, AvatarAttributes.HOME_REGION_ID);
userProfile.HomeRegionX = (uint)GetIntegerAttribute(message.Attributes, AvatarAttributes.HOME_REGION_X);
userProfile.HomeRegionY = (uint)GetIntegerAttribute(message.Attributes, AvatarAttributes.HOME_REGION_Y);
userProfile.HomeRegion = Utils.UIntsToLong(userProfile.HomeRegionX, userProfile.HomeRegionY);
userProfile.ID = agentData.AgentID;
userProfile.Image = UUID.Zero;
userProfile.LastLogin = useragent.LoginTime;
userProfile.Partner = GetUUIDAttribute(message.Attributes, AvatarAttributes.PARTNER_ID);
userProfile.PasswordHash = "$1$";
userProfile.PasswordSalt = String.Empty;
userProfile.SurName = agentData.lastname;
userProfile.UserFlags = GetIntegerAttribute(message.Attributes, AvatarAttributes.USER_FLAGS);
userProfile.WantDoMask = (uint)GetIntegerAttribute(message.Attributes, AvatarAttributes.WANT_DO);
userProfile.WebLoginKey = UUID.Zero;
// Cable Beach does not tie all endpoints for a service under a single URL, so these won't do
userProfile.UserAssetURI = String.Empty;
userProfile.UserInventoryURI = String.Empty;
// Stick our user data in the cache so the region will know something about us
scene.CommsManager.UserProfileCacheService.PreloadUserCache(userProfile);
// Add this incoming EnableClient message to the database of active sessions
wsConnector.EnableClientMessages.Add(message.Identity, message.AgentID, message);
// Call 'new user' event handler
string reason;
if (wsConnector.NewUserConnection(agentData, out reason))
{
string capsSeedPath = CapsUtil.GetCapsSeedPath(
scene.CapsModule.GetCapsHandlerForUser(agentData.AgentID).CapsObjectPath);
// Set the response message to successful
reply.Success = true;
reply.SeedCapability = wsConnector.GetServiceEndpoint(capsSeedPath);
m_Log.Info("[CABLE BEACH MOD]: enable_client succeeded for " + userProfile.Name);
}
else
{
reply.Message = "Connection refused: " + reason;
m_Log.Error("[CABLE BEACH MOD]: enable_client failed: " + reason);
}
}
else
{
m_Log.Error("[CABLE BEACH MOD]: enable_client received an unrecognized region handle " + message.RegionHandle);
}
}
return reply.Serialize();
}
private OSD CloseAgentConnectionHandler(string path, OSD request, string endpoint)
{
// FIXME: Implement this
return new OSD();
}
#endregion LLSD Handlers
#region Attribute Fetching
private static UUID GetUUIDAttribute(Dictionary<Uri, OSD> attributes, Uri attribute)
{
OSD attributeData;
if (attributes.TryGetValue(attribute, out attributeData))
return attributeData.AsUUID();
return UUID.Zero;
}
private static string GetStringAttribute(Dictionary<Uri, OSD> attributes, Uri attribute)
{
OSD attributeData;
if (attributes.TryGetValue(attribute, out attributeData))
return attributeData.AsString();
return "<EMPTY>";
}
private static int GetIntegerAttribute(Dictionary<Uri, OSD> attributes, Uri attribute)
{
OSD attributeData;
if (attributes.TryGetValue(attribute, out attributeData))
return attributeData.AsInteger();
return 0;
}
private static DateTime GetDateAttribute(Dictionary<Uri, OSD> attributes, Uri attribute)
{
OSD attributeData;
if (attributes.TryGetValue(attribute, out attributeData))
return attributeData.AsDate();
return Utils.Epoch;
}
private static Vector3 GetVector3Attribute(Dictionary<Uri, OSD> attributes, Uri attribute)
{
OSD attributeData;
if (attributes.TryGetValue(attribute, out attributeData))
return attributeData.AsVector3();
return new Vector3(128f, 128f, 100f);
}
#endregion Attribute Fetching
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ContosoUniversity.Data.Entities;
using ContosoUniversity.Common.Interfaces;
using ContosoUniversity.Common;
using ContosoUniversity.Data.DbContexts;
using Microsoft.AspNetCore.Authorization;
namespace ContosoUniversity.Web.Controllers
{
public class StudentsController : Controller
{
private readonly IRepository<Student> _studentRepo;
private readonly IModelBindingHelperAdaptor _modelBindingHelperAdaptor;
public StudentsController(UnitOfWork<ApplicationContext> unitOfWork, IModelBindingHelperAdaptor modelBindingHelperAdaptor)
{
_studentRepo = unitOfWork.StudentRepository;
_modelBindingHelperAdaptor = modelBindingHelperAdaptor;
}
public async Task<IActionResult> Index(string sortOrder, string searchString, int? page, string currentFilter)
{
ViewData["CurrentSort"] = sortOrder;
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "LastName_desc" : "";
ViewData["DateSortParm"] = sortOrder == "EnrollmentDate" ? "EnrollmentDate_desc" : "EnrollmentDate";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewData["CurrentFilter"] = searchString;
var students = from s in _studentRepo.GetAll() select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.LastName.Contains(searchString) || s.FirstMidName.Contains(searchString));
}
if (string.IsNullOrEmpty(sortOrder))
{
sortOrder = "LastName";
}
bool descending = false;
if (sortOrder.EndsWith("_desc"))
{
sortOrder = sortOrder.Substring(0, sortOrder.Length - 5);
descending = true;
}
if (descending)
{
students = students.OrderByDescending(e => e.GetType().GetProperty(sortOrder).GetValue(e, null));
}
else
{
students = students.OrderBy(e => e.GetType().GetProperty(sortOrder).GetValue(e, null));
}
int pageSize = 3;
return View(await PaginatedList<Student>.CreateAsync(students.AsGatedNoTracking(), page ?? 1, pageSize));
}
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var student = await _studentRepo.Get(id.Value)
.Include(s => s.Enrollments)
.ThenInclude(e => e.Course)
.AsGatedNoTracking()
.SingleOrDefaultAsync();
if (student == null)
{
return NotFound();
}
return View(student);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("LastName,FirstMidName,EnrollmentDate")] Student student)
{
try
{
if (ModelState.IsValid)
{
await _studentRepo.AddAsync(student);
await _studentRepo.SaveChangesAsync();
return RedirectToAction("Index");
}
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(student);
}
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var student = await _studentRepo.Get(id.Value).SingleOrDefaultAsync();
if (student == null)
{
return NotFound();
}
return View(student);
}
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditPost(int? id)
{
if (id == null)
{
return NotFound();
}
var studentToUpdate = await _studentRepo.Get(id.Value).SingleOrDefaultAsync();
if (await _modelBindingHelperAdaptor.TryUpdateModelAsync<Student>(this, studentToUpdate, "", s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate))
{
try
{
studentToUpdate.ModifiedDate = DateTime.UtcNow;
await _studentRepo.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator");
}
}
return View(studentToUpdate);
}
[Authorize(Roles = "Administrator")]
public async Task<IActionResult> Delete(int? id, bool? saveChangesError = false)
{
if (id == null)
{
return NotFound();
}
var student = await _studentRepo.Get(id.Value)
.AsGatedNoTracking()
.SingleOrDefaultAsync();
if (student == null)
{
return NotFound();
}
if (saveChangesError.GetValueOrDefault())
{
ViewData["ErrorMessage"] = "Delete failed. Try again, and if the problem persists see your system administrator";
}
return View(student);
}
[Authorize(Roles = "Administrator")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var student = await _studentRepo.Get(id)
.AsGatedNoTracking()
.SingleOrDefaultAsync();
if (student == null)
{
return RedirectToAction("Index");
}
try
{
_studentRepo.Delete(student);
await _studentRepo.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateException)
{
return RedirectToAction("Delete", new { id = id, saveChangesError = true });
}
}
private bool StudentExists(int id)
{
return _studentRepo.GetAll().Any(e => e.ID == id);
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
namespace Stratus
{
public class StratusTimestampParameters
{
public bool year = true;
public bool month = true;
public bool day = true;
public bool hour = true;
public bool minute = true;
public bool second = false;
public char separator = '_';
public static readonly StratusTimestampParameters defaultValue = new StratusTimestampParameters();
}
/// <summary>
/// Utlity functions for IO operations
/// </summary>
public static partial class StratusIO
{
//------------------------------------------------------------------------/
// Properties
//------------------------------------------------------------------------/
public static bool IsInMacOS => SystemInfo.operatingSystem.IndexOf("Mac OS") != -1;
public static bool IsInWinOS => SystemInfo.operatingSystem.IndexOf("Windows") != -1;
//------------------------------------------------------------------------/
// Methods
//------------------------------------------------------------------------/
/// <summary>
/// Returns a relative path of an asset
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string MakeRelative(string path)
{
var relativePath = "Assets" + path.Substring(Application.dataPath.Length);
relativePath = relativePath.Replace("\\", "/");
return relativePath;
}
/// <summary>
/// Deletes the file at the given file path.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool DeleteFile(string filePath)
{
if (!FileExists(filePath))
{
return false;
}
File.Delete(filePath);
return true;
}
/// <summary>
/// Reveals the file/directory at the given path
/// </summary>
/// <param name="path"></param>
public static void Open(string path)
{
if (IsInWinOS)
{
OpenInWin(path);
}
else if (IsInMacOS)
{
OpenInMac(path);
}
else // couldn't determine OS
{
OpenInWin(path);
OpenInMac(path);
}
}
/// <summary>
/// Returns true if the file exists
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool FileExists(string filePath) => File.Exists(filePath);
/// <summary>
/// Given a filename, changes its extension
/// </summary>
/// <param name="fileName"></param>
/// <param name="extension"></param>
/// <returns></returns>
public static string ChangeExtension(string fileName, string extension) => Path.ChangeExtension(fileName, extension);
/// <summary>
/// Combines multiple paths together
/// </summary>
/// <param name="paths"></param>
/// <returns></returns>
public static string CombinePath(params string[] paths)
{
string result = string.Empty;
for (int i = 0; i < paths.Length; i++)
{
string p = paths[i];
result = Path.Combine(result, p);
}
return result;
}
/// <summary>
/// There are following custom format specifiers y (year),
/// M (month), d (day), h (hour 12), H (hour 24), m (minute),
/// s (second), f (second fraction), F (second fraction,
/// trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
/// </summary>
/// <returns></returns>
public static string GetTimestamp(string format = "yyyy-MM-dd_HH-mm")
{
return DateTime.Now.ToString(format);
}
/// <summary>
/// There are following custom format specifiers y (year),
/// M (month), d (day), h (hour 12), H (hour 24), m (minute),
/// s (second), f (second fraction), F (second fraction,
/// trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
/// </summary>
/// <returns></returns>
public static string GetTimestamp(StratusTimestampParameters parameters)
{
List<string> values = new List<string>();
if (parameters.year) values.Add("yyyy");
if (parameters.month) values.Add("MM");
if (parameters.day) values.Add("dd");
if (parameters.hour) values.Add("HH");
if (parameters.minute) values.Add("mm");
if (parameters.second) values.Add("ss");
string format = values.Join(parameters.separator);
return DateTime.Now.ToString(format);
}
/// <summary>
/// Returns the filename
/// </summary>
public static string GetFileName(string filePath, bool extension = true)
{
return extension ? Path.GetFileName(filePath) : Path.GetFileNameWithoutExtension(filePath);
}
/// <summary>
/// Returns the relative path of a given folder name (if found within the application's assets folder)
/// </summary>
/// <param name="folderName"></param>
/// <returns></returns>
public static string GetFolderPath(string folderName)
{
//var dirInfo = new DirectoryInfo(Application.dataPath);
var dirs = GetDirectories(Application.dataPath);
var folderPath = dirs.Find(x => x.Contains(folderName));
return folderPath;
}
public static byte[] FileReadAllBytes(string filePath)
{
if (!FileExists(filePath))
{
return null;
}
byte[] result = File.ReadAllBytes(filePath);
return result;
}
public static Texture2D LoadImage2D(string filePath, StratusImageEncoding encoding = StratusImageEncoding.JPG)
{
byte[] data = FileReadAllBytes(filePath);
if (data == null)
{
return null;
}
Texture2D image = new Texture2D(0, 0);
image.LoadImage(data);
return image;
}
public static bool SaveImage2D(Texture2D texture, string filePath, StratusImageEncoding encoding = StratusImageEncoding.JPG)
{
byte[] data = null;
switch (encoding)
{
case StratusImageEncoding.PNG:
data = texture.EncodeToPNG();
break;
case StratusImageEncoding.JPG:
data = texture.EncodeToJPG();
break;
default:
break;
}
if (data == null)
{
return false;
}
File.WriteAllBytes(filePath, data);
return true;
}
private static List<string> GetDirectories(string path)
{
List<string> dirs = new List<string>();
ProcessDirectory(path, dirs);
return dirs;
}
private static void ProcessDirectory(string dirPath, List<string> dirs)
{
// Add this directory
dirs.Add(MakeRelative(dirPath));
// Now look for any subdirectories
var subDirectoryEntries = Directory.GetDirectories(dirPath);
foreach (var dir in subDirectoryEntries)
{
ProcessDirectory(dir, dirs);
}
}
public static void OpenInMac(string path)
{
bool openInsidesOfFolder = false;
// try mac
string macPath = path.Replace("\\", "/"); // mac finder doesn't like backward slashes
if (System.IO.Directory.Exists(macPath)) // if path requested is a folder, automatically open insides of that folder
{
openInsidesOfFolder = true;
}
if (!macPath.StartsWith("\""))
{
macPath = "\"" + macPath;
}
if (!macPath.EndsWith("\""))
{
macPath = macPath + "\"";
}
string arguments = (openInsidesOfFolder ? "" : "-R ") + macPath;
try
{
System.Diagnostics.Process.Start("open", arguments);
}
catch (System.ComponentModel.Win32Exception e)
{
// tried to open mac finder in windows
// just silently skip error
// we currently have no platform define for the current OS we are in, so we resort to this
e.HelpLink = ""; // do anything with this variable to silence warning about not using it
}
}
public static void OpenInWin(string path)
{
bool openInsidesOfFolder = false;
// try windows
string winPath = path.Replace("/", "\\"); // windows explorer doesn't like forward slashes
if (System.IO.Directory.Exists(winPath)) // if path requested is a folder, automatically open insides of that folder
{
openInsidesOfFolder = true;
}
try
{
System.Diagnostics.Process.Start("explorer.exe", (openInsidesOfFolder ? "/root," : "/select,") + winPath);
}
catch (System.ComponentModel.Win32Exception e)
{
// tried to open win explorer in mac
// just silently skip error
// we currently have no platform define for the current OS we are in, so we resort to this
e.HelpLink = ""; // do anything with this variable to silence warning about not using it
}
}
}
}
| |
namespace GitVersion
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Linq;
public class ArgumentParser
{
public static Arguments ParseArguments(string commandLineArguments)
{
var arguments = commandLineArguments
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
return ParseArguments(arguments);
}
static void EnsureArgumentValueCount(string[] values, int maxArguments = 1)
{
if (values != null && values.Length > maxArguments)
{
throw new WarningException(string.Format("Could not parse command line parameter '{0}'.", values[1]));
}
}
public static Arguments ParseArguments(List<string> commandLineArguments)
{
if (commandLineArguments.Count == 0)
{
return new Arguments
{
TargetPath = Environment.CurrentDirectory
};
}
var firstArgument = commandLineArguments.First();
if (firstArgument.IsHelp())
{
return new Arguments
{
IsHelp = true
};
}
if (firstArgument.IsInit())
{
return new Arguments
{
TargetPath = Environment.CurrentDirectory,
Init = true
};
}
var arguments = new Arguments();
bool firstArgumentIsSwitch;
var switchesAndValues = CollectSwitchesAndValuesFromArguments(commandLineArguments, out firstArgumentIsSwitch);
for (var i = 0; i < switchesAndValues.AllKeys.Length; i++)
{
var name = switchesAndValues.AllKeys[i];
var values = switchesAndValues.GetValues(name);
var value = values != null ? values.FirstOrDefault() : null;
if (name.IsSwitch("version"))
{
EnsureArgumentValueCount(values);
arguments.IsVersion = true;
continue;
}
if (name.IsSwitch("l"))
{
EnsureArgumentValueCount(values);
arguments.LogFilePath = value;
continue;
}
if (name.IsSwitch("targetpath"))
{
EnsureArgumentValueCount(values);
arguments.TargetPath = value;
continue;
}
if (name.IsSwitch("dynamicRepoLocation"))
{
EnsureArgumentValueCount(values);
arguments.DynamicRepositoryLocation = value;
continue;
}
if (name.IsSwitch("url"))
{
EnsureArgumentValueCount(values);
arguments.TargetUrl = value;
continue;
}
if (name.IsSwitch("b"))
{
EnsureArgumentValueCount(values);
arguments.TargetBranch = value;
continue;
}
if (name.IsSwitch("u"))
{
EnsureArgumentValueCount(values);
arguments.Authentication.Username = value;
continue;
}
if (name.IsSwitch("p"))
{
EnsureArgumentValueCount(values);
arguments.Authentication.Password = value;
continue;
}
if (name.IsSwitch("c"))
{
EnsureArgumentValueCount(values);
arguments.CommitId = value;
continue;
}
if (name.IsSwitch("exec"))
{
EnsureArgumentValueCount(values);
arguments.Exec = value;
continue;
}
if (name.IsSwitch("execargs"))
{
EnsureArgumentValueCount(values);
arguments.ExecArgs = value;
continue;
}
if (name.IsSwitch("proj"))
{
EnsureArgumentValueCount(values);
arguments.Proj = value;
continue;
}
if (name.IsSwitch("projargs"))
{
EnsureArgumentValueCount(values);
arguments.ProjArgs = value;
continue;
}
if (name.IsSwitch("diag"))
{
if (value == null || value.IsTrue())
{
arguments.Diag = true;
}
continue;
}
if (name.IsSwitch("updateAssemblyInfo"))
{
if (value.IsTrue())
{
arguments.UpdateAssemblyInfo = true;
}
else if (value.IsFalse())
{
arguments.UpdateAssemblyInfo = false;
}
else if (values != null && values.Length > 1)
{
arguments.UpdateAssemblyInfo = true;
foreach (var v in values)
{
arguments.AddAssemblyInfoFileName(v);
}
}
else if (!value.IsSwitchArgument())
{
arguments.UpdateAssemblyInfo = true;
arguments.AddAssemblyInfoFileName(value);
}
else
{
arguments.UpdateAssemblyInfo = true;
}
if (arguments.UpdateAssemblyInfoFileName.Count > 1 && arguments.EnsureAssemblyInfo)
{
throw new WarningException("Can't specify multiple assembly info files when using -ensureassemblyinfo switch, either use a single assembly info file or do not specify -ensureassemblyinfo and create assembly info files manually");
}
continue;
}
if (name.IsSwitch("assemblyversionformat"))
{
throw new WarningException("assemblyversionformat switch removed, use AssemblyVersioningScheme configuration value instead");
}
if (name.IsSwitch("v") || name.IsSwitch("showvariable"))
{
string versionVariable = null;
if (!string.IsNullOrWhiteSpace(value))
{
versionVariable = VersionVariables.AvailableVariables.SingleOrDefault(av => av.Equals(value.Replace("'", ""), StringComparison.CurrentCultureIgnoreCase));
}
if (versionVariable == null)
{
var messageFormat = "{0} requires a valid version variable. Available variables are:\n{1}";
var message = string.Format(messageFormat, name, String.Join(", ", VersionVariables.AvailableVariables.Select(x => string.Concat("'", x, "'"))));
throw new WarningException(message);
}
arguments.ShowVariable = versionVariable;
continue;
}
if (name.IsSwitch("showConfig"))
{
if (value.IsTrue())
{
arguments.ShowConfig = true;
}
else if (value.IsFalse())
{
arguments.UpdateAssemblyInfo = false;
}
else
{
arguments.ShowConfig = true;
}
continue;
}
if (name.IsSwitch("output"))
{
OutputType outputType;
if (!Enum.TryParse(value, true, out outputType))
{
throw new WarningException(string.Format("Value '{0}' cannot be parsed as output type, please use 'json' or 'buildserver'", value));
}
arguments.Output = outputType;
continue;
}
if (name.IsSwitch("nofetch"))
{
arguments.NoFetch = true;
continue;
}
if (name.IsSwitch("ensureassemblyinfo"))
{
if (value.IsTrue())
{
arguments.EnsureAssemblyInfo = true;
}
else if (value.IsFalse())
{
arguments.EnsureAssemblyInfo = false;
}
else
{
arguments.EnsureAssemblyInfo = true;
}
if (arguments.UpdateAssemblyInfoFileName.Count > 1 && arguments.EnsureAssemblyInfo)
{
throw new WarningException("Can't specify multiple assembly info files when using /ensureassemblyinfo switch, either use a single assembly info file or do not specify /ensureassemblyinfo and create assembly info files manually");
}
continue;
}
if (name.IsSwitch("overrideconfig"))
{
var keyValueOptions = (value ?? "").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (keyValueOptions.Length == 0)
{
continue;
}
arguments.HasOverrideConfig = true;
if (keyValueOptions.Length > 1)
{
throw new WarningException("Can't specify multiple /overrideconfig options: currently supported only 'tag-prefix' option");
}
// key=value
foreach (var keyValueOption in keyValueOptions)
{
var keyAndValue = keyValueOption.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (keyAndValue.Length != 2)
{
throw new WarningException(string.Format("Could not parse /overrideconfig option: {0}. Ensure it is in format 'key=value'", keyValueOption));
}
var optionKey = keyAndValue[0].ToLowerInvariant();
switch (optionKey)
{
case "tag-prefix":
arguments.OverrideConfig.TagPrefix = keyAndValue[1];
break;
default:
throw new WarningException(string.Format("Could not parse /overrideconfig option: {0}. Currently supported only 'tag-prefix' option", optionKey));
}
}
continue;
}
if (name.IsSwitch("nocache"))
{
arguments.NoCache = true;
continue;
}
if (name.IsSwitch("verbosity"))
{
if (!Enum.TryParse(value, true, out arguments.Verbosity))
{
throw new WarningException(String.Format("Could not parse Verbosity value '{0}'", value));
}
continue;
}
var couldNotParseMessage = string.Format("Could not parse command line parameter '{0}'.", name);
// If we've reached through all argument switches without a match, we can relatively safely assume that the first argument isn't a switch, but the target path.
if (i == 0)
{
if (name.StartsWith("/"))
{
if (Path.DirectorySeparatorChar == '/' && name.IsValidPath())
{
arguments.TargetPath = name;
continue;
}
}
else if (!name.IsSwitchArgument())
{
arguments.TargetPath = name;
continue;
}
couldNotParseMessage += " If it is the target path, make sure it exists.";
}
throw new WarningException(couldNotParseMessage);
}
if (arguments.TargetPath == null)
{
// If the first argument is a switch, it should already have been consumed in the above loop,
// or else a WarningException should have been thrown and we wouldn't end up here.
arguments.TargetPath = firstArgumentIsSwitch
? Environment.CurrentDirectory
: firstArgument;
}
return arguments;
}
static NameValueCollection CollectSwitchesAndValuesFromArguments(IList<string> namedArguments, out bool firstArgumentIsSwitch)
{
firstArgumentIsSwitch = true;
var switchesAndValues = new NameValueCollection();
string currentKey = null;
var argumentRequiresValue = false;
for (var i = 0; i < namedArguments.Count; i = i + 1)
{
var arg = namedArguments[i];
// If the current (previous) argument doesn't require a value parameter and this is a switch, create new name/value entry for it, with a null value.
if (!argumentRequiresValue && arg.IsSwitchArgument())
{
currentKey = arg;
argumentRequiresValue = arg.ArgumentRequiresValue(i);
switchesAndValues.Add(currentKey, null);
}
// If this is a value (not a switch)
else if (currentKey != null)
{
// And if the current switch does not have a value yet and the value is not itself a switch, set its value to this argument.
if (string.IsNullOrEmpty(switchesAndValues[currentKey]))
{
switchesAndValues[currentKey] = arg;
}
// Otherwise add the value under the same switch.
else
{
switchesAndValues.Add(currentKey, arg);
}
// Reset the boolean argument flag so the next argument won't be ignored.
argumentRequiresValue = false;
}
else if (i == 0)
{
firstArgumentIsSwitch = false;
}
}
return switchesAndValues;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.