context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display;
using OrchardCore.Contents;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.Modules;
namespace OrchardCore.ContentPreview.Controllers
{
public class PreviewController : Controller
{
private readonly IContentManager _contentManager;
private readonly IContentManagerSession _contentManagerSession;
private readonly IContentItemDisplayManager _contentItemDisplayManager;
private readonly IAuthorizationService _authorizationService;
private readonly IClock _clock;
private readonly IUpdateModelAccessor _updateModelAccessor;
public PreviewController(
IContentManager contentManager,
IContentItemDisplayManager contentItemDisplayManager,
IContentManagerSession contentManagerSession,
IAuthorizationService authorizationService,
IClock clock,
IUpdateModelAccessor updateModelAccessor)
{
_authorizationService = authorizationService;
_clock = clock;
_contentItemDisplayManager = contentItemDisplayManager;
_contentManager = contentManager;
_contentManagerSession = contentManagerSession;
_updateModelAccessor = updateModelAccessor;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Render()
{
if (!await _authorizationService.AuthorizeAsync(User, CommonPermissions.PreviewContent))
{
return this.ChallengeOrForbid();
}
// Mark request as a `Preview` request so that drivers / handlers or underlying services can be aware of an active preview mode.
HttpContext.Features.Set(new ContentPreviewFeature());
var contentItemType = Request.Form["ContentItemType"];
var contentItem = await _contentManager.NewAsync(contentItemType);
// Assign the ids from the currently edited item so that validation thinks
// it's working on the same item. For instance if drivers are checking name unicity
// they need to think this is the same existing item (AutoroutePart).
var contentItemId = Request.Form["PreviewContentItemId"];
var contentItemVersionId = Request.Form["PreviewContentItemVersionId"];
// Unique contentItem.Id that only Preview is using such that another
// stored document can't have the same one in the IContentManagerSession index
contentItem.Id = -1;
contentItem.ContentItemId = contentItemId;
contentItem.ContentItemVersionId = contentItemVersionId;
contentItem.CreatedUtc = _clock.UtcNow;
contentItem.ModifiedUtc = _clock.UtcNow;
contentItem.PublishedUtc = _clock.UtcNow;
contentItem.Published = true;
// TODO: we should probably get this value from the main editor as it might impact validators
var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true);
if (!ModelState.IsValid)
{
var errors = new List<string>();
foreach (var modelState in ValidationHelpers.GetModelStateList(ViewData, false))
{
for (var i = 0; i < modelState.Errors.Count; i++)
{
var modelError = modelState.Errors[i];
var errorText = ValidationHelpers.GetModelErrorMessageOrDefault(modelError);
errors.Add(errorText);
}
}
return StatusCode(500, new { errors = errors });
}
var previewAspect = await _contentManager.PopulateAspectAsync(contentItem, new PreviewAspect());
if (!String.IsNullOrEmpty(previewAspect.PreviewUrl))
{
// The PreviewPart is configured, we need to set the fake content item
_contentManagerSession.Store(contentItem);
if (!previewAspect.PreviewUrl.StartsWith('/'))
{
previewAspect.PreviewUrl = "/" + previewAspect.PreviewUrl;
}
Request.HttpContext.Items["PreviewPath"] = previewAspect.PreviewUrl;
return Ok();
}
model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, _updateModelAccessor.ModelUpdater, "Detail");
return View(model);
}
}
internal static class ValidationHelpers
{
public static string GetModelErrorMessageOrDefault(ModelError modelError)
{
Debug.Assert(modelError != null);
if (!string.IsNullOrEmpty(modelError.ErrorMessage))
{
return modelError.ErrorMessage;
}
// Default in the ValidationSummary case is no error message.
return string.Empty;
}
public static string GetModelErrorMessageOrDefault(
ModelError modelError,
ModelStateEntry containingEntry,
ModelExplorer modelExplorer)
{
Debug.Assert(modelError != null);
Debug.Assert(containingEntry != null);
Debug.Assert(modelExplorer != null);
if (!string.IsNullOrEmpty(modelError.ErrorMessage))
{
return modelError.ErrorMessage;
}
// Default in the ValidationMessage case is a fallback error message.
var attemptedValue = containingEntry.AttemptedValue ?? "null";
return modelExplorer.Metadata.ModelBindingMessageProvider.ValueIsInvalidAccessor(attemptedValue);
}
// Returns non-null list of model states, which caller will render in order provided.
public static IList<ModelStateEntry> GetModelStateList(
ViewDataDictionary viewData,
bool excludePropertyErrors)
{
if (excludePropertyErrors)
{
viewData.ModelState.TryGetValue(viewData.TemplateInfo.HtmlFieldPrefix, out var ms);
if (ms != null)
{
return new[] { ms };
}
}
else if (viewData.ModelState.Count > 0)
{
var metadata = viewData.ModelMetadata;
var modelStateDictionary = viewData.ModelState;
var entries = new List<ModelStateEntry>();
Visit(modelStateDictionary.Root, metadata, entries);
if (entries.Count < modelStateDictionary.Count)
{
// Account for entries in the ModelStateDictionary that do not have corresponding ModelMetadata values.
foreach (var entry in modelStateDictionary)
{
if (!entries.Contains(entry.Value))
{
entries.Add(entry.Value);
}
}
}
return entries;
}
return Array.Empty<ModelStateEntry>();
}
private static void Visit(
ModelStateEntry modelStateEntry,
ModelMetadata metadata,
List<ModelStateEntry> orderedModelStateEntries)
{
if (metadata.ElementMetadata != null && modelStateEntry.Children != null)
{
foreach (var indexEntry in modelStateEntry.Children)
{
Visit(indexEntry, metadata.ElementMetadata, orderedModelStateEntries);
}
}
else
{
for (var i = 0; i < metadata.Properties.Count; i++)
{
var propertyMetadata = metadata.Properties[i];
var propertyModelStateEntry = modelStateEntry.GetModelStateForProperty(propertyMetadata.PropertyName);
if (propertyModelStateEntry != null)
{
Visit(propertyModelStateEntry, propertyMetadata, orderedModelStateEntries);
}
}
}
if (!modelStateEntry.IsContainerNode)
{
orderedModelStateEntries.Add(modelStateEntry);
}
}
}
}
| |
/* Copyright (c) 2007, Dr. WPF
* 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.
*
* * The name Dr. WPF may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Dr. WPF ``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 Dr. WPF BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
namespace AmazonSqs.Status.Components
{
[Serializable]
public class ObservableDictionary<TKey, TValue> :
IDictionary<TKey, TValue>,
ICollection<KeyValuePair<TKey, TValue>>,
IEnumerable<KeyValuePair<TKey, TValue>>,
IDictionary,
ICollection,
IEnumerable,
ISerializable,
IDeserializationCallback,
INotifyCollectionChanged,
INotifyPropertyChanged
{
#region constructors
#region public
public ObservableDictionary()
{
_keyedEntryCollection = new KeyedDictionaryEntryCollection<TKey>();
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary)
{
_keyedEntryCollection = new KeyedDictionaryEntryCollection<TKey>();
foreach (KeyValuePair<TKey, TValue> entry in dictionary)
DoAddEntry((TKey)entry.Key, (TValue)entry.Value);
}
public ObservableDictionary(IEqualityComparer<TKey> comparer)
{
_keyedEntryCollection = new KeyedDictionaryEntryCollection<TKey>(comparer);
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
{
_keyedEntryCollection = new KeyedDictionaryEntryCollection<TKey>(comparer);
foreach (KeyValuePair<TKey, TValue> entry in dictionary)
DoAddEntry((TKey)entry.Key, (TValue)entry.Value);
}
#endregion public
#region protected
protected ObservableDictionary(SerializationInfo info, StreamingContext context)
{
_siInfo = info;
}
#endregion protected
#endregion constructors
#region properties
#region public
public IEqualityComparer<TKey> Comparer
{
get { return _keyedEntryCollection.Comparer; }
}
public int Count
{
get { return _keyedEntryCollection.Count; }
}
public Dictionary<TKey, TValue>.KeyCollection Keys
{
get { return TrueDictionary.Keys; }
}
public TValue this[TKey key]
{
get { return (TValue)_keyedEntryCollection[key].Value; }
set { DoSetEntry(key, value); }
}
public Dictionary<TKey, TValue>.ValueCollection Values
{
get { return TrueDictionary.Values; }
}
#endregion public
#region private
private Dictionary<TKey, TValue> TrueDictionary
{
get
{
if (_dictionaryCacheVersion != _version)
{
_dictionaryCache.Clear();
foreach (DictionaryEntry entry in _keyedEntryCollection)
_dictionaryCache.Add((TKey)entry.Key, (TValue)entry.Value);
_dictionaryCacheVersion = _version;
}
return _dictionaryCache;
}
}
#endregion private
#endregion properties
#region methods
#region public
public void Add(TKey key, TValue value)
{
DoAddEntry(key, value);
}
public void Clear()
{
DoClearEntries();
}
public bool ContainsKey(TKey key)
{
return _keyedEntryCollection.Contains(key);
}
public bool ContainsValue(TValue value)
{
return TrueDictionary.ContainsValue(value);
}
public IEnumerator GetEnumerator()
{
return new Enumerator<TKey, TValue>(this, false);
}
public bool Remove(TKey key)
{
return DoRemoveEntry(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
bool result = _keyedEntryCollection.Contains(key);
value = result ? (TValue)_keyedEntryCollection[key].Value : default(TValue);
return result;
}
#endregion public
#region protected
protected virtual bool AddEntry(TKey key, TValue value)
{
_keyedEntryCollection.Add(new DictionaryEntry(key, value));
return true;
}
protected virtual bool ClearEntries()
{
// check whether there are entries to clear
bool result = (Count > 0);
if (result)
{
// if so, clear the dictionary
_keyedEntryCollection.Clear();
}
return result;
}
protected int GetIndexAndEntryForKey(TKey key, out DictionaryEntry entry)
{
entry = new DictionaryEntry();
int index = -1;
if (_keyedEntryCollection.Contains(key))
{
entry = _keyedEntryCollection[key];
index = _keyedEntryCollection.IndexOf(entry);
}
return index;
}
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
{
if (CollectionChanged != null)
CollectionChanged(this, args);
}
protected virtual void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
protected virtual bool RemoveEntry(TKey key)
{
// remove the entry
return _keyedEntryCollection.Remove(key);
}
protected virtual bool SetEntry(TKey key, TValue value)
{
bool keyExists = _keyedEntryCollection.Contains(key);
// if identical key/value pair already exists, nothing to do
if (keyExists && value.Equals((TValue)_keyedEntryCollection[key].Value))
return false;
// otherwise, remove the existing entry
if (keyExists)
_keyedEntryCollection.Remove(key);
// add the new entry
_keyedEntryCollection.Add(new DictionaryEntry(key, value));
return true;
}
#endregion protected
#region private
private void DoAddEntry(TKey key, TValue value)
{
if (AddEntry(key, value))
{
_version++;
DictionaryEntry entry;
int index = GetIndexAndEntryForKey(key, out entry);
FireEntryAddedNotifications(entry, index);
}
}
private void DoClearEntries()
{
if (ClearEntries())
{
_version++;
FireResetNotifications();
}
}
private bool DoRemoveEntry(TKey key)
{
DictionaryEntry entry;
int index = GetIndexAndEntryForKey(key, out entry);
bool result = RemoveEntry(key);
if (result)
{
_version++;
if (index > -1)
FireEntryRemovedNotifications(entry, index);
}
return result;
}
private void DoSetEntry(TKey key, TValue value)
{
DictionaryEntry entry;
int index = GetIndexAndEntryForKey(key, out entry);
if (SetEntry(key, value))
{
_version++;
// if prior entry existed for this key, fire the removed notifications
if (index > -1)
{
FireEntryRemovedNotifications(entry, index);
// force the property change notifications to fire for the modified entry
_countCache--;
}
// then fire the added notifications
index = GetIndexAndEntryForKey(key, out entry);
FireEntryAddedNotifications(entry, index);
}
}
private void FireEntryAddedNotifications(DictionaryEntry entry, int index)
{
// fire the relevant PropertyChanged notifications
FirePropertyChangedNotifications();
// fire CollectionChanged notification
if (index > -1)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new KeyValuePair<TKey, TValue>((TKey)entry.Key, (TValue)entry.Value), index));
else
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
private void FireEntryRemovedNotifications(DictionaryEntry entry, int index)
{
// fire the relevant PropertyChanged notifications
FirePropertyChangedNotifications();
// fire CollectionChanged notification
if (index > -1)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new KeyValuePair<TKey, TValue>((TKey)entry.Key, (TValue)entry.Value), index));
else
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
private void FirePropertyChangedNotifications()
{
if (Count != _countCache)
{
_countCache = Count;
OnPropertyChanged("Count");
OnPropertyChanged("Item[]");
OnPropertyChanged("Keys");
OnPropertyChanged("Values");
}
}
private void FireResetNotifications()
{
// fire the relevant PropertyChanged notifications
FirePropertyChangedNotifications();
// fire CollectionChanged notification
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#endregion private
#endregion methods
#region interfaces
#region IDictionary<TKey, TValue>
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
DoAddEntry(key, value);
}
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
return DoRemoveEntry(key);
}
bool IDictionary<TKey, TValue>.ContainsKey(TKey key)
{
return _keyedEntryCollection.Contains(key);
}
bool IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)
{
return TryGetValue(key, out value);
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return Keys; }
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return Values; }
}
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get { return (TValue)_keyedEntryCollection[key].Value; }
set { DoSetEntry(key, value); }
}
#endregion IDictionary<TKey, TValue>
#region IDictionary
void IDictionary.Add(object key, object value)
{
DoAddEntry((TKey)key, (TValue)value);
}
void IDictionary.Clear()
{
DoClearEntries();
}
bool IDictionary.Contains(object key)
{
return _keyedEntryCollection.Contains((TKey)key);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator<TKey, TValue>(this, true);
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return false; }
}
object IDictionary.this[object key]
{
get { return _keyedEntryCollection[(TKey)key].Value; }
set { DoSetEntry((TKey)key, (TValue)value); }
}
ICollection IDictionary.Keys
{
get { return Keys; }
}
void IDictionary.Remove(object key)
{
DoRemoveEntry((TKey)key);
}
ICollection IDictionary.Values
{
get { return Values; }
}
#endregion IDictionary
#region ICollection<KeyValuePair<TKey, TValue>>
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> kvp)
{
DoAddEntry(kvp.Key, kvp.Value);
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
DoClearEntries();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> kvp)
{
return _keyedEntryCollection.Contains(kvp.Key);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("CopyTo() failed: array parameter was null");
}
if ((index < 0) || (index > array.Length))
{
throw new ArgumentOutOfRangeException("CopyTo() failed: index parameter was outside the bounds of the supplied array");
}
if ((array.Length - index) < _keyedEntryCollection.Count)
{
throw new ArgumentException("CopyTo() failed: supplied array was too small");
}
foreach (DictionaryEntry entry in _keyedEntryCollection)
array[index++] = new KeyValuePair<TKey, TValue>((TKey)entry.Key, (TValue)entry.Value);
}
int ICollection<KeyValuePair<TKey, TValue>>.Count
{
get { return _keyedEntryCollection.Count; }
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> kvp)
{
return DoRemoveEntry(kvp.Key);
}
#endregion ICollection<KeyValuePair<TKey, TValue>>
#region ICollection
void ICollection.CopyTo(Array array, int index)
{
((ICollection)_keyedEntryCollection).CopyTo(array, index);
}
int ICollection.Count
{
get { return _keyedEntryCollection.Count; }
}
bool ICollection.IsSynchronized
{
get { return ((ICollection)_keyedEntryCollection).IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_keyedEntryCollection).SyncRoot; }
}
#endregion ICollection
#region IEnumerable<KeyValuePair<TKey, TValue>>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator<TKey, TValue>(this, false);
}
#endregion IEnumerable<KeyValuePair<TKey, TValue>>
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion IEnumerable
#region ISerializable
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
Collection<DictionaryEntry> entries = new Collection<DictionaryEntry>();
foreach (DictionaryEntry entry in _keyedEntryCollection)
entries.Add(entry);
info.AddValue("entries", entries);
}
#endregion ISerializable
#region IDeserializationCallback
public virtual void OnDeserialization(object sender)
{
if (_siInfo != null)
{
Collection<DictionaryEntry> entries = (Collection<DictionaryEntry>)
_siInfo.GetValue("entries", typeof(Collection<DictionaryEntry>));
foreach (DictionaryEntry entry in entries)
AddEntry((TKey)entry.Key, (TValue)entry.Value);
}
}
#endregion IDeserializationCallback
#region INotifyCollectionChanged
event NotifyCollectionChangedEventHandler INotifyCollectionChanged.CollectionChanged
{
add { CollectionChanged += value; }
remove { CollectionChanged -= value; }
}
protected virtual event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion INotifyCollectionChanged
#region INotifyPropertyChanged
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add { PropertyChanged += value; }
remove { PropertyChanged -= value; }
}
protected virtual event PropertyChangedEventHandler PropertyChanged;
#endregion INotifyPropertyChanged
#endregion interfaces
#region protected classes
#region KeyedDictionaryEntryCollection<TKey>
protected class KeyedDictionaryEntryCollection<TKey> : KeyedCollection<TKey, DictionaryEntry>
{
#region constructors
#region public
public KeyedDictionaryEntryCollection() : base() { }
public KeyedDictionaryEntryCollection(IEqualityComparer<TKey> comparer) : base(comparer) { }
#endregion public
#endregion constructors
#region methods
#region protected
protected override TKey GetKeyForItem(DictionaryEntry entry)
{
return (TKey)entry.Key;
}
#endregion protected
#endregion methods
}
#endregion KeyedDictionaryEntryCollection<TKey>
#endregion protected classes
#region public structures
#region Enumerator
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Enumerator<TKey, TValue> : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, IDictionaryEnumerator, IEnumerator
{
#region constructors
internal Enumerator(ObservableDictionary<TKey, TValue> dictionary, bool isDictionaryEntryEnumerator)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = -1;
_isDictionaryEntryEnumerator = isDictionaryEntryEnumerator;
_current = new KeyValuePair<TKey, TValue>();
}
#endregion constructors
#region properties
#region public
public KeyValuePair<TKey, TValue> Current
{
get
{
ValidateCurrent();
return _current;
}
}
#endregion public
#endregion properties
#region methods
#region public
public void Dispose()
{
}
public bool MoveNext()
{
ValidateVersion();
_index++;
if (_index < _dictionary._keyedEntryCollection.Count)
{
_current = new KeyValuePair<TKey, TValue>((TKey)_dictionary._keyedEntryCollection[_index].Key, (TValue)_dictionary._keyedEntryCollection[_index].Value);
return true;
}
_index = -2;
_current = new KeyValuePair<TKey, TValue>();
return false;
}
#endregion public
#region private
private void ValidateCurrent()
{
if (_index == -1)
{
throw new InvalidOperationException("The enumerator has not been started.");
}
else if (_index == -2)
{
throw new InvalidOperationException("The enumerator has reached the end of the collection.");
}
}
private void ValidateVersion()
{
if (_version != _dictionary._version)
{
throw new InvalidOperationException("The enumerator is not valid because the dictionary changed.");
}
}
#endregion private
#endregion methods
#region IEnumerator implementation
object IEnumerator.Current
{
get
{
ValidateCurrent();
if (_isDictionaryEntryEnumerator)
{
return new DictionaryEntry(_current.Key, _current.Value);
}
return new KeyValuePair<TKey, TValue>(_current.Key, _current.Value);
}
}
void IEnumerator.Reset()
{
ValidateVersion();
_index = -1;
_current = new KeyValuePair<TKey, TValue>();
}
#endregion IEnumerator implemenation
#region IDictionaryEnumerator implemenation
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
ValidateCurrent();
return new DictionaryEntry(_current.Key, _current.Value);
}
}
object IDictionaryEnumerator.Key
{
get
{
ValidateCurrent();
return _current.Key;
}
}
object IDictionaryEnumerator.Value
{
get
{
ValidateCurrent();
return _current.Value;
}
}
#endregion
#region fields
private ObservableDictionary<TKey, TValue> _dictionary;
private int _version;
private int _index;
private KeyValuePair<TKey, TValue> _current;
private bool _isDictionaryEntryEnumerator;
#endregion fields
}
#endregion Enumerator
#endregion public structures
#region fields
protected KeyedDictionaryEntryCollection<TKey> _keyedEntryCollection;
private int _countCache = 0;
private Dictionary<TKey, TValue> _dictionaryCache = new Dictionary<TKey, TValue>();
private int _dictionaryCacheVersion = 0;
private int _version = 0;
[NonSerialized]
private SerializationInfo _siInfo = null;
#endregion fields
}
}
| |
using System;
using System.Linq;
using LinqToDB;
using LinqToDB.Mapping;
using NUnit.Framework;
namespace Tests.Linq
{
[TestFixture]
public class CharTypesTests : TestBase
{
[Table("ALLTYPES", Configuration = ProviderName.DB2)]
[Table("AllTypes")]
public class StringTestTable
{
[Column("ID")]
public int Id;
[Column("char20DataType")]
[Column(Configuration = ProviderName.SqlCe, IsColumn = false)]
[Column(Configuration = ProviderName.DB2, IsColumn = false)]
[Column(Configuration = ProviderName.PostgreSQL, IsColumn = false)]
[Column(Configuration = ProviderName.MySql, IsColumn = false)]
[Column(Configuration = ProviderName.MySqlConnector, IsColumn = false)]
[Column(Configuration = TestProvName.MySql57, IsColumn = false)]
[Column(Configuration = TestProvName.MariaDB, IsColumn = false)]
public string String;
[Column("ncharDataType")]
[Column("nchar20DataType", Configuration = ProviderName.SapHana)]
[Column("CHAR20DATATYPE" , Configuration = ProviderName.DB2)]
[Column("char20DataType" , Configuration = ProviderName.PostgreSQL)]
[Column("char20DataType" , Configuration = ProviderName.MySql)]
[Column("char20DataType" , Configuration = ProviderName.MySqlConnector)]
[Column("char20DataType" , Configuration = TestProvName.MySql57)]
[Column("char20DataType" , Configuration = TestProvName.MariaDB)]
[Column( Configuration = ProviderName.Firebird, IsColumn = false)]
public string NString;
}
[Table("ALLTYPES", Configuration = ProviderName.DB2)]
[Table("AllTypes")]
public class CharTestTable
{
[Column("ID")]
public int Id;
[Column("char20DataType")]
[Column(Configuration = ProviderName.SqlCe, IsColumn = false)]
[Column(Configuration = ProviderName.DB2, IsColumn = false)]
[Column(Configuration = ProviderName.PostgreSQL, IsColumn = false)]
[Column(Configuration = ProviderName.MySql, IsColumn = false)]
[Column(Configuration = ProviderName.MySqlConnector, IsColumn = false)]
[Column(Configuration = TestProvName.MySql57, IsColumn = false)]
[Column(Configuration = TestProvName.MariaDB, IsColumn = false)]
public char? Char;
[Column("ncharDataType" , DataType = DataType.NChar)]
[Column("nchar20DataType", DataType = DataType.NChar, Configuration = ProviderName.SapHana)]
[Column("CHAR20DATATYPE" , DataType = DataType.NChar, Configuration = ProviderName.DB2)]
[Column("char20DataType" , DataType = DataType.NChar, Configuration = ProviderName.PostgreSQL)]
[Column("char20DataType" , DataType = DataType.NChar, Configuration = ProviderName.MySql)]
[Column("char20DataType" , DataType = DataType.NChar, Configuration = ProviderName.MySqlConnector)]
[Column("char20DataType" , DataType = DataType.NChar, Configuration = TestProvName.MySql57)]
[Column("char20DataType" , DataType = DataType.NChar, Configuration = TestProvName.MariaDB)]
[Column( Configuration = ProviderName.Firebird, IsColumn = false)]
public char? NChar;
}
// most of ending characters here trimmed by default by .net string TrimX methods
// unicode test cases not used for String
static readonly StringTestTable[] StringTestData =
{
new StringTestTable() { String = "test01", NString = "test01" },
new StringTestTable() { String = "test02 ", NString = "test02 " },
new StringTestTable() { String = "test03\x09 ", NString = "test03\x09 " },
new StringTestTable() { String = "test04\x0A ", NString = "test04\x0A " },
new StringTestTable() { String = "test05\x0B ", NString = "test05\x0B " },
new StringTestTable() { String = "test06\x0C ", NString = "test06\x0C " },
new StringTestTable() { String = "test07\x0D ", NString = "test07\x0D " },
new StringTestTable() { String = "test08\xA0 ", NString = "test08\xA0 " },
new StringTestTable() { String = "test09 ", NString = "test09\u2000 " },
new StringTestTable() { String = "test10 ", NString = "test10\u2001 " },
new StringTestTable() { String = "test11 ", NString = "test11\u2002 " },
new StringTestTable() { String = "test12 ", NString = "test12\u2003 " },
new StringTestTable() { String = "test13 ", NString = "test13\u2004 " },
new StringTestTable() { String = "test14 ", NString = "test14\u2005 " },
new StringTestTable() { String = "test15 ", NString = "test15\u2006 " },
new StringTestTable() { String = "test16 ", NString = "test16\u2007 " },
new StringTestTable() { String = "test17 ", NString = "test17\u2008 " },
new StringTestTable() { String = "test18 ", NString = "test18\u2009 " },
new StringTestTable() { String = "test19 ", NString = "test19\u200A " },
new StringTestTable() { String = "test20 ", NString = "test20\u3000 " },
new StringTestTable() { String = "test21\0 ", NString = "test21\0 " },
new StringTestTable()
};
// TODO: MySql57 disabled due to encoding issues on CI
[Test]
public void StringTrimming([DataSources(false, TestProvName.MySql57, ProviderName.Informix)] string context)
{
using (var db = GetDataContext(context))
{
var lastId = db.GetTable<StringTestTable>().Select(_ => _.Id).Max();
try
{
var testData = GetStringData(context);
foreach (var record in testData)
{
var query = db.GetTable<StringTestTable>().Value(_ => _.NString, record.NString);
if (!SkipChar(context))
query = query.Value(_ => _.String, record.String);
if ( context == ProviderName.Firebird
|| context == ProviderName.Firebird + ".LinqService"
|| context == TestProvName.Firebird3
|| context == TestProvName.Firebird3 + ".LinqService")
query = db.GetTable<StringTestTable>().Value(_ => _.String, record.String);
query.Insert();
}
var records = db.GetTable<StringTestTable>().Where(_ => _.Id > lastId).OrderBy(_ => _.Id).ToArray();
Assert.AreEqual(testData.Length, records.Length);
for (var i = 0; i < records.Length; i++)
{
if (!SkipChar(context))
Assert.AreEqual(testData[i].String?.TrimEnd(' '), records[i].String);
if (context != ProviderName.Firebird
&& context != ProviderName.Firebird + ".LinqService"
&& context != TestProvName.Firebird3
&& context != TestProvName.Firebird3 + ".LinqService")
Assert.AreEqual(testData[i].NString?.TrimEnd(' '), records[i].NString);
}
}
finally
{
db.GetTable<StringTestTable>().Where(_ => _.Id > lastId).Delete();
}
}
}
private static CharTestTable[] GetCharData([DataSources] string context)
{
// filter out null-character test cases for servers/providers without support
if ( context.Contains(ProviderName.PostgreSQL)
|| context == ProviderName.DB2
|| context == ProviderName.DB2 + ".LinqService"
|| context == ProviderName.SqlCe
|| context == ProviderName.SqlCe + ".LinqService"
|| context == ProviderName.SapHana
|| context == ProviderName.SapHana + ".LinqService")
return CharTestData.Where(_ => _.NChar != '\0').ToArray();
// I wonder why
if ( context == ProviderName.Firebird
|| context == ProviderName.Firebird + ".LinqService"
|| context == TestProvName.Firebird3
|| context == TestProvName.Firebird3 + ".LinqService")
return CharTestData.Where(_ => _.NChar != '\xA0').ToArray();
// also strange
if ( context == ProviderName.Informix
|| context == ProviderName.Informix + ".LinqService")
return CharTestData.Where(_ => _.NChar != '\0' && (_.NChar ?? 0) < byte.MaxValue).ToArray();
return CharTestData;
}
private static StringTestTable[] GetStringData([DataSources] string context)
{
// filter out null-character test cases for servers/providers without support
if (context.Contains(ProviderName.PostgreSQL)
|| context == ProviderName.DB2
|| context == ProviderName.DB2 + ".LinqService"
|| context == ProviderName.SQLiteClassic
|| context == ProviderName.SQLiteClassic + ".LinqService"
|| context == ProviderName.SQLiteMS
|| context == ProviderName.SQLiteMS + ".LinqService"
|| context == ProviderName.SqlCe
|| context == ProviderName.SqlCe + ".LinqService"
|| context == ProviderName.SapHana
|| context == ProviderName.SapHana + ".LinqService")
return StringTestData.Where(_ => !(_.NString ?? string.Empty).Contains("\0")).ToArray();
// I wonder why
if ( context == ProviderName.Firebird
|| context == ProviderName.Firebird + ".LinqService"
|| context == TestProvName.Firebird3
|| context == TestProvName.Firebird3 + ".LinqService")
return StringTestData.Where(_ => !(_.NString ?? string.Empty).Contains("\xA0")).ToArray();
// also strange
if ( context == ProviderName.Informix
|| context == ProviderName.Informix + ".LinqService")
return StringTestData.Where(_ => !(_.NString ?? string.Empty).Contains("\0")
&& !(_.NString ?? string.Empty).Any(c => (int)c > byte.MaxValue)).ToArray();
return StringTestData;
}
static readonly CharTestTable[] CharTestData =
{
new CharTestTable() { Char = ' ', NChar = ' ' },
new CharTestTable() { Char = '\x09', NChar = '\x09' },
new CharTestTable() { Char = '\x0A', NChar = '\x0A' },
new CharTestTable() { Char = '\x0B', NChar = '\x0B' },
new CharTestTable() { Char = '\x0C', NChar = '\x0C' },
new CharTestTable() { Char = '\x0D', NChar = '\x0D' },
new CharTestTable() { Char = '\xA0', NChar = '\xA0' },
new CharTestTable() { Char = ' ', NChar = '\u2000' },
new CharTestTable() { Char = ' ', NChar = '\u2001' },
new CharTestTable() { Char = ' ', NChar = '\u2002' },
new CharTestTable() { Char = ' ', NChar = '\u2003' },
new CharTestTable() { Char = ' ', NChar = '\u2004' },
new CharTestTable() { Char = ' ', NChar = '\u2005' },
new CharTestTable() { Char = ' ', NChar = '\u2006' },
new CharTestTable() { Char = ' ', NChar = '\u2007' },
new CharTestTable() { Char = ' ', NChar = '\u2008' },
new CharTestTable() { Char = ' ', NChar = '\u2009' },
new CharTestTable() { Char = ' ', NChar = '\u200A' },
new CharTestTable() { Char = ' ', NChar = '\u3000' },
new CharTestTable() { Char = '\0', NChar = '\0' },
new CharTestTable()
};
// TODO: MySql57 disabled due to encoding issues on CI
[Test]
public void CharTrimming([DataSources(false, TestProvName.MySql57, ProviderName.Informix)] string context)
{
using (var db = GetDataContext(context))
{
var lastId = db.GetTable<CharTestTable>().Select(_ => _.Id).Max();
try
{
var testData = GetCharData(context);
foreach (var record in testData)
{
var query = db.GetTable<CharTestTable>().Value(_ => _.NChar, record.NChar);
if (!SkipChar(context))
query = query.Value(_ => _.Char, record.Char);
if ( context == ProviderName.Firebird
|| context == ProviderName.Firebird + ".LinqService"
|| context == TestProvName.Firebird3
|| context == TestProvName.Firebird3 + ".LinqService")
query = db.GetTable<CharTestTable>().Value(_ => _.Char, record.Char);
query.Insert();
}
var records = db.GetTable<CharTestTable>().Where(_ => _.Id > lastId).OrderBy(_ => _.Id).ToArray();
Assert.AreEqual(testData.Length, records.Length);
for (var i = 0; i < records.Length; i++)
{
if (context == ProviderName.SapHana || context == ProviderName.SapHana + ".LinqService")
{
// for some reason, SAP returns \0 for space character
// or we insert it incorrectly?
if (testData[i].Char == ' ')
Assert.AreEqual('\0', records[i].Char);
else
Assert.AreEqual(testData[i].Char, records[i].Char);
if (testData[i].NChar == ' ')
Assert.AreEqual('\0', records[i].NChar);
else
Assert.AreEqual(testData[i].NChar, records[i].NChar);
continue;
}
if (!SkipChar(context))
Assert.AreEqual(testData[i].Char, records[i].Char);
if (context == ProviderName.MySql
|| context == ProviderName.MySql + ".LinqService"
|| context == ProviderName.MySqlConnector
|| context == ProviderName.MySqlConnector + ".LinqService"
|| context == TestProvName.MySql57
|| context == TestProvName.MySql57 + ".LinqService"
|| context == TestProvName.MariaDB
|| context == TestProvName.MariaDB + ".LinqService")
// for some reason mysql doesn't insert space
Assert.AreEqual(testData[i].NChar == ' ' ? '\0' : testData[i].NChar, records[i].NChar);
else if (context != ProviderName.Firebird
&& context != ProviderName.Firebird + ".LinqService"
&& context != TestProvName.Firebird3
&& context != TestProvName.Firebird3 + ".LinqService")
Assert.AreEqual(testData[i].NChar, records[i].NChar);
}
}
finally
{
db.GetTable<CharTestTable>().Where(_ => _.Id > lastId).Delete();
}
}
}
private static bool SkipChar([DataSources] string context)
{
return context == ProviderName.SqlCe
|| context == ProviderName.SqlCe + ".LinqService"
|| context == ProviderName.DB2
|| context == ProviderName.DB2 + ".LinqService"
|| context.Contains(ProviderName.PostgreSQL)
|| context == ProviderName.MySql
|| context == ProviderName.MySql + ".LinqService"
|| context == ProviderName.MySqlConnector
|| context == ProviderName.MySqlConnector + ".LinqService"
|| context == TestProvName.MySql57
|| context == TestProvName.MySql57 + ".LinqService"
|| context == TestProvName.MariaDB
|| context == TestProvName.MariaDB + ".LinqService";
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
namespace ZXing.Client.Result
{
/// <summary>
/// Represents a parsed result that encodes contact information, like that in an address book entry.
/// </summary>
/// <author>Sean Owen</author>
public sealed class AddressBookParsedResult : ParsedResult
{
private readonly String[] names;
private readonly String[] nicknames;
private readonly String pronunciation;
private readonly String[] phoneNumbers;
private readonly String[] phoneTypes;
private readonly String[] emails;
private readonly String[] emailTypes;
private readonly String instantMessenger;
private readonly String note;
private readonly String[] addresses;
private readonly String[] addressTypes;
private readonly String org;
private readonly String birthday;
private readonly String title;
private readonly String[] urls;
private readonly String[] geo;
public AddressBookParsedResult(String[] names,
String[] phoneNumbers,
String[] phoneTypes,
String[] emails,
String[] emailTypes,
String[] addresses,
String[] addressTypes)
: this(names,
null,
null,
phoneNumbers,
phoneTypes,
emails,
emailTypes,
null,
null,
addresses,
addressTypes,
null,
null,
null,
null,
null)
{
}
public AddressBookParsedResult(String[] names,
String[] nicknames,
String pronunciation,
String[] phoneNumbers,
String[] phoneTypes,
String[] emails,
String[] emailTypes,
String instantMessenger,
String note,
String[] addresses,
String[] addressTypes,
String org,
String birthday,
String title,
String[] urls,
String[] geo)
: base(ParsedResultType.ADDRESSBOOK)
{
this.names = names;
this.nicknames = nicknames;
this.pronunciation = pronunciation;
this.phoneNumbers = phoneNumbers;
this.phoneTypes = phoneTypes;
this.emails = emails;
this.emailTypes = emailTypes;
this.instantMessenger = instantMessenger;
this.note = note;
this.addresses = addresses;
this.addressTypes = addressTypes;
this.org = org;
this.birthday = birthday;
this.title = title;
this.urls = urls;
this.geo = geo;
displayResultValue = getDisplayResult();
}
public String[] Names
{
get { return names; }
}
public String[] Nicknames
{
get { return nicknames; }
}
/// <summary>
/// In Japanese, the name is written in kanji, which can have multiple readings. Therefore a hint
/// is often provided, called furigana, which spells the name phonetically.
/// </summary>
/// <return>The pronunciation of the getNames() field, often in hiragana or katakana.</return>
public String Pronunciation
{
get { return pronunciation; }
}
public String[] PhoneNumbers
{
get { return phoneNumbers; }
}
/// <return>optional descriptions of the type of each phone number. It could be like "HOME", but,
/// there is no guaranteed or standard format.</return>
public String[] PhoneTypes
{
get { return phoneTypes; }
}
public String[] Emails
{
get { return emails; }
}
/// <return>optional descriptions of the type of each e-mail. It could be like "WORK", but,
/// there is no guaranteed or standard format.</return>
public String[] EmailTypes
{
get { return emailTypes; }
}
public String InstantMessenger
{
get { return instantMessenger; }
}
public String Note
{
get { return note; }
}
public String[] Addresses
{
get { return addresses; }
}
/// <return>optional descriptions of the type of each e-mail. It could be like "WORK", but,
/// there is no guaranteed or standard format.</return>
public String[] AddressTypes
{
get { return addressTypes; }
}
public String Title
{
get { return title; }
}
public String Org
{
get { return org; }
}
public String[] URLs
{
get { return urls; }
}
/// <return>birthday formatted as yyyyMMdd (e.g. 19780917)</return>
public String Birthday
{
get { return birthday; }
}
/// <return>a location as a latitude/longitude pair</return>
public String[] Geo
{
get { return geo; }
}
private String getDisplayResult()
{
var result = new StringBuilder(100);
maybeAppend(names, result);
maybeAppend(nicknames, result);
maybeAppend(pronunciation, result);
maybeAppend(title, result);
maybeAppend(org, result);
maybeAppend(addresses, result);
maybeAppend(phoneNumbers, result);
maybeAppend(emails, result);
maybeAppend(instantMessenger, result);
maybeAppend(urls, result);
maybeAppend(birthday, result);
maybeAppend(geo, result);
maybeAppend(note, result);
return result.ToString();
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// An in-memory representation of a JSON Schema.
/// </summary>
public class JsonSchema
{
/// <summary>
/// Gets or sets the id.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets whether the object is required.
/// </summary>
public bool? Required { get; set; }
/// <summary>
/// Gets or sets whether the object is read only.
/// </summary>
public bool? ReadOnly { get; set; }
/// <summary>
/// Gets or sets whether the object is visible to users.
/// </summary>
public bool? Hidden { get; set; }
/// <summary>
/// Gets or sets whether the object is transient.
/// </summary>
public bool? Transient { get; set; }
/// <summary>
/// Gets or sets the description of the object.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets the types of values allowed by the object.
/// </summary>
/// <value>The type.</value>
public JsonSchemaType? Type { get; set; }
/// <summary>
/// Gets or sets the pattern.
/// </summary>
/// <value>The pattern.</value>
public string Pattern { get; set; }
/// <summary>
/// Gets or sets the minimum length.
/// </summary>
/// <value>The minimum length.</value>
public int? MinimumLength { get; set; }
/// <summary>
/// Gets or sets the maximum length.
/// </summary>
/// <value>The maximum length.</value>
public int? MaximumLength { get; set; }
/// <summary>
/// Gets or sets a number that the value should be divisble by.
/// </summary>
/// <value>A number that the value should be divisble by.</value>
public double? DivisibleBy { get; set; }
/// <summary>
/// Gets or sets the minimum.
/// </summary>
/// <value>The minimum.</value>
public double? Minimum { get; set; }
/// <summary>
/// Gets or sets the maximum.
/// </summary>
/// <value>The maximum.</value>
public double? Maximum { get; set; }
/// <summary>
/// Gets or sets a flag indicating whether the value can not equal the number defined by the "minimum" attribute.
/// </summary>
/// <value>A flag indicating whether the value can not equal the number defined by the "minimum" attribute.</value>
public bool? ExclusiveMinimum { get; set; }
/// <summary>
/// Gets or sets a flag indicating whether the value can not equal the number defined by the "maximum" attribute.
/// </summary>
/// <value>A flag indicating whether the value can not equal the number defined by the "maximum" attribute.</value>
public bool? ExclusiveMaximum { get; set; }
/// <summary>
/// Gets or sets the minimum number of items.
/// </summary>
/// <value>The minimum number of items.</value>
public int? MinimumItems { get; set; }
/// <summary>
/// Gets or sets the maximum number of items.
/// </summary>
/// <value>The maximum number of items.</value>
public int? MaximumItems { get; set; }
/// <summary>
/// Gets or sets the <see cref="JsonSchema"/> of items.
/// </summary>
/// <value>The <see cref="JsonSchema"/> of items.</value>
public IList<JsonSchema> Items { get; set; }
/// <summary>
/// Gets or sets the <see cref="JsonSchema"/> of properties.
/// </summary>
/// <value>The <see cref="JsonSchema"/> of properties.</value>
public IDictionary<string, JsonSchema> Properties { get; set; }
/// <summary>
/// Gets or sets the <see cref="JsonSchema"/> of additional properties.
/// </summary>
/// <value>The <see cref="JsonSchema"/> of additional properties.</value>
public JsonSchema AdditionalProperties { get; set; }
/// <summary>
/// Gets or sets the pattern properties.
/// </summary>
/// <value>The pattern properties.</value>
public IDictionary<string, JsonSchema> PatternProperties { get; set; }
/// <summary>
/// Gets or sets a value indicating whether additional properties are allowed.
/// </summary>
/// <value>
/// <c>true</c> if additional properties are allowed; otherwise, <c>false</c>.
/// </value>
public bool AllowAdditionalProperties { get; set; }
/// <summary>
/// Gets or sets the required property if this property is present.
/// </summary>
/// <value>The required property if this property is present.</value>
public string Requires { get; set; }
/// <summary>
/// Gets or sets the identity.
/// </summary>
/// <value>The identity.</value>
public IList<string> Identity { get; set; }
/// <summary>
/// Gets or sets the a collection of valid enum values allowed.
/// </summary>
/// <value>A collection of valid enum values allowed.</value>
public IList<JToken> Enum { get; set; }
/// <summary>
/// Gets or sets a collection of options.
/// </summary>
/// <value>A collection of options.</value>
public IDictionary<JToken, string> Options { get; set; }
/// <summary>
/// Gets or sets disallowed types.
/// </summary>
/// <value>The disallow types.</value>
public JsonSchemaType? Disallow { get; set; }
/// <summary>
/// Gets or sets the default value.
/// </summary>
/// <value>The default value.</value>
public JToken Default { get; set; }
/// <summary>
/// Gets or sets the extend <see cref="JsonSchema"/>.
/// </summary>
/// <value>The extended <see cref="JsonSchema"/>.</value>
public JsonSchema Extends { get; set; }
/// <summary>
/// Gets or sets the format.
/// </summary>
/// <value>The format.</value>
public string Format { get; set; }
private readonly string _internalId = Guid.NewGuid().ToString("N");
internal string InternalId
{
get { return _internalId; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonSchema"/> class.
/// </summary>
public JsonSchema()
{
AllowAdditionalProperties = true;
}
/// <summary>
/// Reads a <see cref="JsonSchema"/> from the specified <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the JSON Schema to read.</param>
/// <returns>The <see cref="JsonSchema"/> object representing the JSON Schema.</returns>
public static JsonSchema Read(JsonReader reader)
{
return Read(reader, new JsonSchemaResolver());
}
/// <summary>
/// Reads a <see cref="JsonSchema"/> from the specified <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the JSON Schema to read.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> to use when resolving schema references.</param>
/// <returns>The <see cref="JsonSchema"/> object representing the JSON Schema.</returns>
public static JsonSchema Read(JsonReader reader, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
JsonSchemaBuilder builder = new JsonSchemaBuilder(resolver);
return builder.Parse(reader);
}
/// <summary>
/// Load a <see cref="JsonSchema"/> from a string that contains schema JSON.
/// </summary>
/// <param name="json">A <see cref="String"/> that contains JSON.</param>
/// <returns>A <see cref="JsonSchema"/> populated from the string that contains JSON.</returns>
public static JsonSchema Parse(string json)
{
return Parse(json, new JsonSchemaResolver());
}
/// <summary>
/// Parses the specified json.
/// </summary>
/// <param name="json">The json.</param>
/// <param name="resolver">The resolver.</param>
/// <returns>A <see cref="JsonSchema"/> populated from the string that contains JSON.</returns>
public static JsonSchema Parse(string json, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(json, "json");
JsonReader reader = new JsonTextReader(new StringReader(json));
return Read(reader, resolver);
}
/// <summary>
/// Writes this schema to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
public void WriteTo(JsonWriter writer)
{
WriteTo(writer, new JsonSchemaResolver());
}
/// <summary>
/// Writes this schema to a <see cref="JsonWriter"/> using the specified <see cref="JsonSchemaResolver"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="resolver">The resolver used.</param>
public void WriteTo(JsonWriter writer, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
JsonSchemaWriter schemaWriter = new JsonSchemaWriter(writer, resolver);
schemaWriter.WriteSchema(this);
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
WriteTo(jsonWriter);
return writer.ToString();
}
}
}
| |
// 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.Collections.Generic;
using System.Text;
namespace WebsitePanel.EnterpriseServer
{
public class SuspendOverusedPackagesTask : SchedulerTask
{
public const string DISKSPACE_FORMAT_STRING = "disk space usage - {0}%";
public const string BANDWIDTH_FORMAT_STRING = "bandwidth usage - {0}%";
public override void DoWork()
{
// Input parameters:
// - DISKSPACE_OVERUSED
// - BANDWIDTH_OVERUSED
BackgroundTask topTask = TaskManager.TopTask;
// get the list of all packages
List<PackageInfo> packages = PackageController.GetPackagePackages(topTask.PackageId, false);
TaskManager.Write("Packages to verify: " + packages.Count.ToString());
bool checkDiskspace = (String.Compare((string)topTask.GetParamValue("DISKSPACE_OVERUSED"), "true", true) == 0);
bool checkBandwidth = (String.Compare((string)topTask.GetParamValue("BANDWIDTH_OVERUSED"), "true", true) == 0);
bool suspendOverused = Convert.ToBoolean(topTask.GetParamValue("SUSPEND_OVERUSED"));
bool sendWarningEmail = Convert.ToBoolean(topTask.GetParamValue("SEND_WARNING_EMAIL"));
bool sendSuspensionEmail = Convert.ToBoolean(topTask.GetParamValue("SEND_SUSPENSION_EMAIL"));
int warningUsageThreshold = Convert.ToInt32(topTask.GetParamValue("WARNING_USAGE_THRESHOLD"));
int suspensionUsageThreshold = Convert.ToInt32(topTask.GetParamValue("SUSPENSION_USAGE_THRESHOLD"));
string warningMailFrom = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_FROM"));
string warningMailBcc = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_BCC"));
string warningMailSubject = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_SUBJECT"));
string warningMailBody = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_BODY"));
string suspensionMailFrom = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_FROM"));
string suspensionMailBcc = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_BCC"));
string suspensionMailSubject = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_SUBJECT"));
string suspensionMailBody = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_BODY"));
int suspendedPackages = 0;
foreach (PackageInfo package in packages)
{
bool isBandwidthBelowWarningThreshold = true;
bool isBandwidthBelowSuspensionThreshold = true;
bool isDiskSpaceBelowWarningThreshold = true;
bool isDiskSpaceBelowSuspensionThreshold = true;
UserInfo userInfo = UserController.GetUser(package.UserId);
int diskSpaceUsage = 0;
int bandwidthUsage = 0;
// disk space
if (checkDiskspace)
{
QuotaValueInfo dsQuota = PackageController.GetPackageQuota(package.PackageId, Quotas.OS_DISKSPACE);
if (dsQuota.QuotaAllocatedValue > 0)
{
diskSpaceUsage = (dsQuota.QuotaUsedValue*100/dsQuota.QuotaAllocatedValue);
isDiskSpaceBelowWarningThreshold = diskSpaceUsage < warningUsageThreshold;
isDiskSpaceBelowSuspensionThreshold = diskSpaceUsage < suspensionUsageThreshold;
}
}
// bandwidth
if (checkBandwidth)
{
QuotaValueInfo bwQuota = PackageController.GetPackageQuota(package.PackageId, Quotas.OS_BANDWIDTH);
if (bwQuota.QuotaAllocatedValue > 0)
{
bandwidthUsage = (bwQuota.QuotaUsedValue*100/bwQuota.QuotaAllocatedValue);
isBandwidthBelowWarningThreshold = bandwidthUsage < warningUsageThreshold;
isBandwidthBelowSuspensionThreshold = bandwidthUsage < suspensionUsageThreshold;
}
}
string userName = String.Format("{0} {1} ({2})/{3}", userInfo.FirstName, userInfo.LastName, userInfo.Username, userInfo.Email);
//
List<string> formatItems = new List<string>();
// add diskspace usage if enabled
if (checkDiskspace) formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, diskSpaceUsage));
// add bandwidth usage if enabled
if (checkBandwidth) formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, bandwidthUsage));
// build usage string
string usage = String.Join(", ", formatItems.ToArray());
// cleanup items
formatItems.Clear();
// add diskspace warning max usage
if (checkDiskspace) formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, warningUsageThreshold));
// add bandwidth warning max usage
if (checkBandwidth) formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, warningUsageThreshold));
// build warning max usage string
string warningMaxUsage = String.Join(", ", formatItems.ToArray());
// cleanup items
formatItems.Clear();
// add diskspace suspension max usage
if (checkDiskspace) formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, suspensionUsageThreshold));
// add bandwidth suspension max usage
if (checkBandwidth) formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, suspensionUsageThreshold));
// build suspension max usage string
string suspensionMaxUsage = String.Join(", ", formatItems.ToArray());
string warningMailSubjectProcessed = ReplaceVariables(warningMailSubject, warningMaxUsage, usage, package.PackageName, userName);
string warningMailBodyProcessed = ReplaceVariables(warningMailBody, warningMaxUsage, usage, package.PackageName, userName);
string suspensionMailSubjectProcessed = ReplaceVariables(suspensionMailSubject, suspensionMaxUsage, usage, package.PackageName, userName);
string suspensionMailBodyProcessed = ReplaceVariables(suspensionMailBody, suspensionMaxUsage, usage, package.PackageName, userName);
// Send email notifications
if (sendWarningEmail && (!isDiskSpaceBelowWarningThreshold || !isBandwidthBelowWarningThreshold))
{
// Send warning email.
this.SendEmail(warningMailFrom, userInfo.Email, warningMailBcc, warningMailSubjectProcessed, warningMailBodyProcessed, false);
}
if (sendSuspensionEmail && (!isDiskSpaceBelowSuspensionThreshold || !isBandwidthBelowSuspensionThreshold))
{
// Send suspension email.
this.SendEmail(suspensionMailFrom, userInfo.Email, suspensionMailBcc, suspensionMailSubjectProcessed, suspensionMailBodyProcessed, false);
}
// suspend package if required
if (suspendOverused && (!isDiskSpaceBelowSuspensionThreshold || !isBandwidthBelowSuspensionThreshold))
{
suspendedPackages++;
// load user details
UserInfo user = PackageController.GetPackageOwner(package.PackageId);
TaskManager.Write(String.Format("Suspend space '{0}' of user '{1}'",
package.PackageName, user.Username));
try
{
PackageController.ChangePackageStatus(null, package.PackageId, PackageStatus.Suspended, false);
}
catch (Exception ex)
{
TaskManager.WriteError("Error while changing space status: " + ex.ToString());
}
}
}
// log results
TaskManager.Write("Total packages suspended: " + suspendedPackages.ToString());
}
private string ReplaceVariables(string content, string threshold, string usage, string spaceName, string customerName)
{
if (!String.IsNullOrEmpty(content))
{
content = Utils.ReplaceStringVariable(content, "threshold", threshold);
content = Utils.ReplaceStringVariable(content, "date", DateTime.Now.ToString());
content = Utils.ReplaceStringVariable(content, "usage", usage);
content = Utils.ReplaceStringVariable(content, "space", spaceName);
content = Utils.ReplaceStringVariable(content, "customer", customerName);
}
return content;
}
private void SendEmail(string from, string to, string bcc, string subject, string body, bool isHtml)
{
// check input parameters
if (String.IsNullOrEmpty(from))
{
TaskManager.WriteWarning("Specify 'Mail From' task parameter");
return;
}
if (String.IsNullOrEmpty(to))
{
TaskManager.WriteWarning("Specify 'Mail To' task parameter");
return;
}
// send mail message
MailHelper.SendMessage(from, to, bcc, subject, body, isHtml);
}
}
}
| |
// 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 Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LoadBalancerProbesOperations operations.
/// </summary>
internal partial class LoadBalancerProbesOperations : IServiceOperations<NetworkManagementClient>, ILoadBalancerProbesOperations
{
/// <summary>
/// Initializes a new instance of the LoadBalancerProbesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LoadBalancerProbesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Gets all the load balancer probes.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Probe>>> ListWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Probe>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Probe>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets load balancer probe.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='probeName'>
/// The name of the probe.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Probe>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string probeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (probeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "probeName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("probeName", probeName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{probeName}", System.Uri.EscapeDataString(probeName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Probe>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Probe>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the load balancer probes.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Probe>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Probe>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Probe>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Storage
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// UsageOperations operations.
/// </summary>
internal partial class UsageOperations : IServiceOperations<StorageManagementClient>, IUsageOperations
{
/// <summary>
/// Initializes a new instance of the UsageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal UsageOperations(StorageManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the StorageManagementClient
/// </summary>
public StorageManagementClient Client { get; private set; }
/// <summary>
/// Gets the current usage count and the limit for the resources under the
/// subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Usage>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Usage>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//-----------------------------------------------------------------------------
//
// <copyright file="ManagedFilter.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// Managed equivalent of IFilter implementation
// Defines base class and helper class for interop
//
// History:
// 02/02/2004: BruceMac: Initial implementation.
// 02/17/2004: JohnLarc: Content of ManagedFilterMarshalingHelper now in IndexingFilterMarshaler.cs.
// 08/26/2004: JohnLarc: Removed access to indexing filters from managed code.
// 07/18/2005: ArindamB: Removed ManagedFilterBase and added IManagedFilter.
//
//-----------------------------------------------------------------------------
using System.Diagnostics;
using System;
using System.Windows; // for ExceptionStringTable
using System.IO; // for FileAccess
using System.Runtime.InteropServices;
using System.Collections;
using System.Security; // for SecurityCritical
using MS.Internal.Interop; // for CHUNK_BREAKTYPE, etc.
using MS.Internal; // for Invariant
using MS.Win32; // for NativeMethods
using MS.Internal.PresentationFramework; // SecurityHelper
// Not using the whole of System.Runtime.InteropServices.ComTypes so as to avoid collisions.
using IPersistFile = System.Runtime.InteropServices.ComTypes.IPersistFile;
namespace MS.Internal.IO.Packaging
{
#region Managed Struct Equivalents
/// <summary>
/// Managed equivalent of a PROPSPEC
/// </summary>
internal class ManagedPropSpec
{
/// <summary>
/// Property Type (int or string)
/// </summary>
/// <value></value>
internal PropSpecType PropType
{
get
{
return _propType;
}
// The following code is not being compiled, but should not be removed; since some container-filter
// plug-in (e.g. metadata) may use it in future.
#if false
set
{
switch (value)
{
case PropSpecType.Id: break;
case PropSpecType.Name: break;
default:
throw new ArgumentException(SR.Get(SRID.FilterPropSpecUnknownUnionSelector), "propSpec");
}
_propType = value;
}
#endif
}
/// <summary>
/// Property name (only valid if PropType is Name
/// </summary>
/// <value></value>
internal string PropName
{
get
{
System.Diagnostics.Debug.Assert(_propType == PropSpecType.Name, "ManagedPropSpec.PropName - PropName only meaningful if PropType is type string");
return _name;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
_name = value;
_id = 0;
_propType = PropSpecType.Name;
}
}
/// <summary>
/// Property Id (only valid if PropType is Id)
/// </summary>
/// <value></value>
internal uint PropId
{
get
{
System.Diagnostics.Debug.Assert(_propType == PropSpecType.Id, "ManagedPropSpec.PropId - PropId only meaningful if PropType is numeric");
return _id;
}
set
{
_id = value;
_name = null;
_propType = PropSpecType.Id;
}
}
/// <summary>
/// Create a int-type PropSpec
/// </summary>
/// <param name="id"></param>
internal ManagedPropSpec(uint id)
{
// Assign to a property rather than a field to ensure consistency through side-effects.
PropId = id;
}
/// <summary>
/// Create a ManagedPropSpec from an unmanaged one
/// </summary>
/// <SecurityNote>
/// Critical - This code could be used to attempt to build a string from arbitrary data.
/// TreatAsSafe - There is a demand in this code. This code is not intended to be called from PT code.
/// Not designed to be exposed to public surface at all. Invoked (indirectly) by unmanaged client code.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal ManagedPropSpec(PROPSPEC propSpec)
{
SecurityHelper.DemandUnmanagedCode();
// Assign to properties rather than fields to ensure consistency through side-effects.
switch ((PropSpecType)propSpec.propType)
{
case PropSpecType.Id:
{
PropId = propSpec.union.propId;
break;
}
case PropSpecType.Name:
{
PropName = Marshal.PtrToStringUni(propSpec.union.name);
break;
}
default:
throw new ArgumentException(SR.Get(SRID.FilterPropSpecUnknownUnionSelector), "propSpec");
}
}
/// <summary>
/// Private properties
/// </summary>
private PropSpecType _propType;
private uint _id; // valid if we are an ID property type
private string _name; // valid if we are a Name property type
}
/// <summary>
/// ManagedFullPropSpec
/// </summary>
internal class ManagedFullPropSpec
{
/// <summary>
/// Guid
/// </summary>
/// <value></value>
internal Guid Guid
{
get { return _guid; }
}
/// <summary>
/// Property
/// </summary>
/// <value></value>
internal ManagedPropSpec Property
{
get
{
return _property;
}
}
/// <summary>
/// constructor
/// </summary>
/// <param name="guid"></param>
/// <param name="propId"></param>
internal ManagedFullPropSpec(Guid guid, uint propId)
{
_guid = guid;
_property = new ManagedPropSpec(propId);
}
// If the following is not used once metadata filtering is implemented, remove completely from the code.
#if false
/// <summary>
/// Helper constructor
/// </summary>
/// <param name="guid">property guid</param>
/// <param name="propName"></param>
internal ManagedFullPropSpec(Guid guid, string propName)
{
_guid = guid;
_property = new ManagedPropSpec(propName);
}
#endif
/// <summary>
/// Handles native FULLPROPSPEC and does marshaling
/// </summary>
/// <param name="nativePropSpec"></param>
internal ManagedFullPropSpec(FULLPROPSPEC nativePropSpec)
{
_guid = nativePropSpec.guid;
_property = new ManagedPropSpec(nativePropSpec.property);
}
private Guid _guid;
private ManagedPropSpec _property;
}
///<summary>
/// A descriptor for a chunk
/// </summary>
internal class ManagedChunk
{
#region Constructors
///<summary>Build a contents chunk, passing the contents string.</summary>
/// <param name="index">id</param>
/// <param name="breakType">The opening break for the chunk.</param>
/// <param name="attribute">attribute</param>
/// <param name="lcid">The locale ID for the chunk.</param>
/// <param name="flags">Indicates if it is text or value chunk.</param>
/// <remarks>
/// All the chunks returned by the XAML filter and the container filter are text chunks.
/// Should a future filter implementation be capable of returning value chunks, a new constructor
/// and a Flags property will have to be defined.
/// </remarks>
internal ManagedChunk(uint index, CHUNK_BREAKTYPE breakType, ManagedFullPropSpec attribute, uint lcid, CHUNKSTATE flags)
{
// Argument errors can only be due to internal inconsistencies, since no input data makes its way here.
Invariant.Assert(breakType >= CHUNK_BREAKTYPE.CHUNK_NO_BREAK && breakType <= CHUNK_BREAKTYPE.CHUNK_EOC);
Invariant.Assert(attribute != null);
// Note that lcid values potentially cover the full range of uint values
// (see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/intl/nls_8sj7.asp)
// and so no useful validation can be made for lcid.
_index = index;
_breakType = breakType;
_lcid = lcid;
_attribute = attribute;
_flags = flags;
// Since pseudo-properties (a.k.a. internal values) are not supported by the XPS filters,
// all chunks we return are expected to have idChunkSource equal to idChunk.
// (See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/indexsrv/html/ixufilt_8ib8.asp)
_idChunkSource = _index;
}
#endregion Constructors
#region Properties
internal uint ID
{
get
{
return _index;
}
set
{
_index = value;
}
}
/// <summary>
/// Flags
/// </summary>
/// <value></value>
internal CHUNKSTATE Flags
{
get
{
return _flags;
}
}
// The following code is not being compiled, but should not be removed; since some container-filter
// plug-in (e.g. metadata) may use it in future.
#if false
///<summary>Always null, since no named property is supported by the Indexing Services in Longhorn.</summary>
internal string PropertyName
{
get
{
return null;
}
}
#endif
///<summary>Indicates the type of break that precedes the chunk.</summary>
internal CHUNK_BREAKTYPE BreakType
{
get
{
return _breakType;
}
set
{
// Argument errors can only be due to internal inconsistencies,
// since no input data makes its way here.
Invariant.Assert(value >= CHUNK_BREAKTYPE.CHUNK_NO_BREAK
&& value <= CHUNK_BREAKTYPE.CHUNK_EOC);
_breakType = value;
}
}
///<summary>Indicates the locale the chunk belongs to.</summary>
internal uint Locale
{
get
{
return _lcid;
}
set
{
_lcid = value;
}
}
internal uint ChunkSource
{
get
{
return _idChunkSource;
}
}
internal uint StartSource
{
get
{
return _startSource;
}
}
internal uint LenSource
{
get
{
return _lenSource;
}
}
internal ManagedFullPropSpec Attribute
{
get
{
return _attribute;
}
set
{
_attribute = value;
}
}
#endregion Properties
#region Private Fields
private uint _index; // chunk id
private CHUNK_BREAKTYPE _breakType;
private CHUNKSTATE _flags;
private uint _lcid;
private ManagedFullPropSpec _attribute;
private uint _idChunkSource;
private uint _startSource = 0;
private uint _lenSource = 0;
#endregion Private Fields
}
#endregion Managed Struct Equivalents
#region IManagedFilter
/// <summary>
/// Interface for managed implementations of IFilter handlers
/// </summary>
interface IManagedFilter
{
/// <summary>
/// Init
/// </summary>
/// <param name="grfFlags">Usage flags. See IFilter spec for details.</param>
/// <param name="aAttributes">
/// Array of Managed FULLPROPSPEC structs to restrict responses.
/// May be null.</param>
/// <returns>flags</returns>
IFILTER_FLAGS Init(
IFILTER_INIT grfFlags,
ManagedFullPropSpec[] aAttributes); // restrict responses to the specified attributes
/// <summary>
/// GetChunk
/// </summary>
/// <returns>
/// The next managed chunk if it exists, null otherwise.
/// For valid chunk, ID of returned chunk should be greater than zero.
/// </returns>
/// <remarks>
/// This should not throw exception to indicate end of chunks, and should
/// return null instead.
///
/// This is to avoid the perf hit of throwing an exception even for cases
/// in which it doesn't get propagated to the unmanaged IFilter client.
///
/// Specifically, when this ManagedFilter is for a content part in a package,
/// PackageFilter moves to the next part when the current part has no more
/// chunks, and in this case no need for an exception to be thrown
/// to indicate FILTER_E_END_OF_CHUNKS.
/// </remarks>
ManagedChunk GetChunk();
/// <summary>
/// GetText
/// </summary>
/// <param name="bufferCharacterCount">
/// maximum number of Unicode characters to return in the String</param>
/// <returns>string associated with the last returned Chunk</returns>
String GetText(int bufferCharacterCount);
/// <summary>
/// GetValue
/// </summary>
/// <remarks>Only supports string types at this time</remarks>
/// <returns>property associated with the last returned Chunk</returns>
Object GetValue();
}
#endregion IManagedFilter
}
| |
using System;
namespace Rs317.Sharp
{
public class GameObjectDefinition
{
public static GameObjectDefinition getDefinition(int objectId)
{
for(int c = 0; c < 20; c++)
{
if(cache[c].id == objectId)
{
return cache[c];
}
}
cacheIndex = (cacheIndex + 1) % 20;
GameObjectDefinition definition = cache[cacheIndex];
stream.position = streamOffsets[objectId];
definition.id = objectId;
definition.setDefaults();
definition.loadDefinition(stream);
return definition;
}
public static void load(Archive archive)
{
GameObjectDefinition.stream = new Default317Buffer(archive.decompressFile("loc.dat"));
Default317Buffer indexStream = new Default317Buffer(archive.decompressFile("loc.idx"));
int objectCount = indexStream.getUnsignedLEShort();
streamOffsets = new int[objectCount];
int offset = 2;
for(int index = 0; index < objectCount; index++)
{
streamOffsets[index] = offset;
offset += indexStream.getUnsignedLEShort();
}
cache = new GameObjectDefinition[20];
for(int c = 0; c < 20; c++)
{
cache[c] = new GameObjectDefinition();
}
}
public static void nullLoader()
{
modelCache = null;
animatedModelCache = null;
streamOffsets = null;
cache = null;
stream = null;
}
public bool unknownAttribute;
/// <summary>
/// Ambient lighting modifier.
/// </summary>
public byte ambient { get; private set; }
public int translateX { get; private set; }
public String name;
public int scaleZ { get; private set; }
/// <summary>
/// Diffuse lighting modifier.
/// </summary>
public byte diffuse { get; private set; }
public int sizeX;
public int translateY { get; private set; }
public int icon;
public int[] originalModelColors { get; private set; }
public int scaleX { get; private set; }
public int configIds;
public bool rotated { get; private set; }
public static bool lowMemory;
private static Default317Buffer stream;
public int id;
private static int[] streamOffsets;
public bool walkable;
public int mapScene;
public int[] childIds;
public int _solid { get; private set; }
public int sizeY;
public bool adjustToTerrain;
public bool wall;
private bool unwalkableSolid;
public bool solid;
public int face;
public bool delayShading { get; private set; }
private static int cacheIndex;
public int scaleY { get; private set; }
public int[] modelIds { get; private set; }
public int varBitId;
public int offsetAmplifier;
public int[] modelTypes { get; private set; }
public byte[] description;
public bool hasActions;
public bool castsShadow;
public static Cache animatedModelCache = new Cache(30);
public int animationId;
private static GameObjectDefinition[] cache;
public int translateZ { get; private set; }
public int[] modifiedModelColors { get; private set; }
public static Cache modelCache = new Cache(500);
public String[] actions;
public static int DefinitionCount => streamOffsets != null ? streamOffsets.Length : 0;
private GameObjectDefinition()
{
id = -1;
}
public GameObjectDefinition getChildDefinition(IInterfaceSettingsProvider interfaceSettingsProvider)
{
int child = -1;
if(varBitId != -1)
{
VarBit varBit = VarBit.values[varBitId];
int configId = varBit.configId;
int lsb = varBit.leastSignificantBit;
int msb = varBit.mostSignificantBit;
int bit = ConstantData.GetBitfieldMaxValue(msb - lsb);
child = interfaceSettingsProvider.GetInterfaceSettings(configId) >> lsb & bit;
}
else if(configIds != -1)
{
child = interfaceSettingsProvider.GetInterfaceSettings(configIds);
}
if(child < 0 || child >= childIds.Length || childIds[child] == -1)
{
return null;
}
else
{
return getDefinition(childIds[child]);
}
}
private void loadDefinition(Default317Buffer stream)
{
int _actions = -1;
do
{
int opcode;
do
{
opcode = stream.getUnsignedByte();
if(opcode == 0)
goto label0;
if(opcode == 1)
{
int modelCount = stream.getUnsignedByte();
if(modelCount > 0)
{
if(modelIds == null || lowMemory)
{
modelTypes = new int[modelCount];
modelIds = new int[modelCount];
for(int m = 0; m < modelCount; m++)
{
modelIds[m] = stream.getUnsignedLEShort();
modelTypes[m] = stream.getUnsignedByte();
}
}
else
{
stream.position += modelCount * 3;
}
}
}
else if(opcode == 2)
{
name = stream.getString();
}
else if(opcode == 3)
{
description = stream.readBytes();
}
else if(opcode == 5)
{
int modelCount = stream.getUnsignedByte();
if(modelCount > 0)
{
if(modelIds == null || lowMemory)
{
modelTypes = null;
modelIds = new int[modelCount];
for(int m = 0; m < modelCount; m++)
{
modelIds[m] = stream.getUnsignedLEShort();
}
}
else
{
stream.position += modelCount * 2;
}
}
}
else if(opcode == 14)
{
sizeX = stream.getUnsignedByte();
}
else if(opcode == 15)
{
sizeY = stream.getUnsignedByte();
}
else if(opcode == 17)
{
solid = false;
}
else if(opcode == 18)
{
walkable = false;
}
else if(opcode == 19)
{
_actions = stream.getUnsignedByte();
if(_actions == 1)
{
hasActions = true;
}
}
else if(opcode == 21)
{
adjustToTerrain = true;
}
else if(opcode == 22)
{
delayShading = true;
}
else if(opcode == 23)
{
wall = true;
}
else if(opcode == 24)
{
animationId = stream.getUnsignedLEShort();
if(animationId == 65535)
{
animationId = -1;
}
}
else if(opcode == 28)
{
offsetAmplifier = stream.getUnsignedByte();
}
else if(opcode == 29)
{
ambient = stream.get();
}
else if(opcode == 39)
{
diffuse = stream.get();
}
else if(opcode >= 30 && opcode < 39)
{
if(actions == null)
{
actions = new String[5];
}
actions[opcode - 30] = stream.getString();
if(actions[opcode - 30].Equals("hidden", StringComparison.InvariantCultureIgnoreCase))
{
actions[opcode - 30] = null;
}
}
else if(opcode == 40)
{
int colourCount = stream.getUnsignedByte();
modifiedModelColors = new int[colourCount];
originalModelColors = new int[colourCount];
for(int c = 0; c < colourCount; c++)
{
modifiedModelColors[c] = stream.getUnsignedLEShort();
originalModelColors[c] = stream.getUnsignedLEShort();
}
}
else if(opcode == 60)
{
icon = stream.getUnsignedLEShort();
}
else if(opcode == 62)
{
rotated = true;
}
else if(opcode == 64)
{
castsShadow = false;
}
else if(opcode == 65)
{
scaleX = stream.getUnsignedLEShort();
}
else if(opcode == 66)
{
scaleY = stream.getUnsignedLEShort();
}
else if(opcode == 67)
{
scaleZ = stream.getUnsignedLEShort();
}
else if(opcode == 68)
{
mapScene = stream.getUnsignedLEShort();
}
else if(opcode == 69)
{
face = stream.getUnsignedByte();
}
else if(opcode == 70)
{
translateX = stream.getShort();
}
else if(opcode == 71)
{
translateY = stream.getShort();
}
else if(opcode == 72)
{
translateZ = stream.getShort();
}
else if(opcode == 73)
{
unknownAttribute = true;
}
else if(opcode == 74)
{
unwalkableSolid = true;
}
else
{
if(opcode != 75)
{
continue;
}
_solid = stream.getUnsignedByte();
}
continue;
} while(opcode != 77);
varBitId = stream.getUnsignedLEShort();
if(varBitId == 65535)
{
varBitId = -1;
}
configIds = stream.getUnsignedLEShort();
if(configIds == 65535)
{
configIds = -1;
}
int childCount = stream.getUnsignedByte();
childIds = new int[childCount + 1];
for(int c = 0; c <= childCount; c++)
{
childIds[c] = stream.getUnsignedLEShort();
if(childIds[c] == 65535)
{
childIds[c] = -1;
}
}
} while(true);
label0:
if(_actions == -1)
{
hasActions = modelIds != null && (modelTypes == null || modelTypes[0] == 10);
if(actions != null)
{
hasActions = true;
}
}
if(unwalkableSolid)
{
solid = false;
walkable = false;
}
if(_solid == -1)
{
_solid = solid ? 1 : 0;
}
}
private void setDefaults()
{
modelIds = null;
modelTypes = null;
name = null;
description = null;
modifiedModelColors = null;
originalModelColors = null;
sizeX = 1;
sizeY = 1;
solid = true;
walkable = true;
hasActions = false;
adjustToTerrain = false;
delayShading = false;
wall = false;
animationId = -1;
offsetAmplifier = 16;
ambient = 0;
diffuse = 0;
actions = null;
icon = -1;
mapScene = -1;
rotated = false;
castsShadow = true;
scaleX = 128;
scaleY = 128;
scaleZ = 128;
face = 0;
translateX = 0;
translateY = 0;
translateZ = 0;
unknownAttribute = false;
unwalkableSolid = false;
_solid = -1;
varBitId = -1;
configIds = -1;
childIds = null;
}
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Xml
{
internal partial class XmlWellFormedWriter : XmlWriter
{
//
// Private types
//
private class NamespaceResolverProxy : IXmlNamespaceResolver
{
private XmlWellFormedWriter _wfWriter;
internal NamespaceResolverProxy(XmlWellFormedWriter wfWriter)
{
_wfWriter = wfWriter;
}
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
throw NotImplemented.ByDesign;
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return _wfWriter.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _wfWriter.LookupPrefix(namespaceName);
}
}
private partial struct ElementScope
{
internal int prevNSTop;
internal string prefix;
internal string localName;
internal string namespaceUri;
internal XmlSpace xmlSpace;
internal string xmlLang;
internal void Set(string prefix, string localName, string namespaceUri, int prevNSTop)
{
this.prevNSTop = prevNSTop;
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.localName = localName;
this.xmlSpace = (System.Xml.XmlSpace)(int)-1;
this.xmlLang = null;
}
internal void WriteEndElement(XmlRawWriter rawWriter)
{
rawWriter.WriteEndElement(prefix, localName, namespaceUri);
}
internal void WriteFullEndElement(XmlRawWriter rawWriter)
{
rawWriter.WriteFullEndElement(prefix, localName, namespaceUri);
}
}
private enum NamespaceKind
{
Written,
NeedToWrite,
Implied,
Special,
}
private partial struct Namespace
{
internal string prefix;
internal string namespaceUri;
internal NamespaceKind kind;
internal int prevNsIndex;
internal void Set(string prefix, string namespaceUri, NamespaceKind kind)
{
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.kind = kind;
this.prevNsIndex = -1;
}
internal void WriteDecl(XmlWriter writer, XmlRawWriter rawWriter)
{
Debug.Assert(kind == NamespaceKind.NeedToWrite);
if (null != rawWriter)
{
rawWriter.WriteNamespaceDeclaration(prefix, namespaceUri);
}
else
{
if (prefix.Length == 0)
{
writer.WriteStartAttribute(string.Empty, "xmlns", XmlReservedNs.NsXmlNs);
}
else
{
writer.WriteStartAttribute("xmlns", prefix, XmlReservedNs.NsXmlNs);
}
writer.WriteString(namespaceUri);
writer.WriteEndAttribute();
}
}
}
private struct AttrName
{
internal string prefix;
internal string namespaceUri;
internal string localName;
internal int prev;
internal void Set(string prefix, string localName, string namespaceUri)
{
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.localName = localName;
this.prev = 0;
}
internal bool IsDuplicate(string prefix, string localName, string namespaceUri)
{
return ((this.localName == localName)
&& ((this.prefix == prefix) || (this.namespaceUri == namespaceUri)));
}
}
private enum SpecialAttribute
{
No = 0,
DefaultXmlns,
PrefixedXmlns,
XmlSpace,
XmlLang
}
private partial class AttributeValueCache
{
private enum ItemType
{
EntityRef,
CharEntity,
SurrogateCharEntity,
Whitespace,
String,
StringChars,
Raw,
RawChars,
ValueString,
}
private class Item
{
internal ItemType type;
internal object data;
internal Item() { }
internal void Set(ItemType type, object data)
{
this.type = type;
this.data = data;
}
}
private class BufferChunk
{
internal char[] buffer;
internal int index;
internal int count;
internal BufferChunk(char[] buffer, int index, int count)
{
this.buffer = buffer;
this.index = index;
this.count = count;
}
}
private StringBuilder _stringValue = new StringBuilder();
private string _singleStringValue; // special-case for a single WriteString call
private Item[] _items;
private int _firstItem;
private int _lastItem = -1;
internal string StringValue
{
get
{
if (_singleStringValue != null)
{
return _singleStringValue;
}
else
{
return _stringValue.ToString();
}
}
}
internal void WriteEntityRef(string name)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
switch (name)
{
case "lt":
_stringValue.Append('<');
break;
case "gt":
_stringValue.Append('>');
break;
case "quot":
_stringValue.Append('"');
break;
case "apos":
_stringValue.Append('\'');
break;
case "amp":
_stringValue.Append('&');
break;
default:
_stringValue.Append('&');
_stringValue.Append(name);
_stringValue.Append(';');
break;
}
AddItem(ItemType.EntityRef, name);
}
internal void WriteCharEntity(char ch)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(ch);
AddItem(ItemType.CharEntity, ch);
}
internal void WriteSurrogateCharEntity(char lowChar, char highChar)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(highChar);
_stringValue.Append(lowChar);
AddItem(ItemType.SurrogateCharEntity, new char[] { lowChar, highChar });
}
internal void WriteWhitespace(string ws)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(ws);
AddItem(ItemType.Whitespace, ws);
}
internal void WriteString(string text)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
else
{
// special-case for a single WriteString
if (_lastItem == -1)
{
_singleStringValue = text;
return;
}
}
_stringValue.Append(text);
AddItem(ItemType.String, text);
}
internal void WriteChars(char[] buffer, int index, int count)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(buffer, index, count);
AddItem(ItemType.StringChars, new BufferChunk(buffer, index, count));
}
internal void WriteRaw(char[] buffer, int index, int count)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(buffer, index, count);
AddItem(ItemType.RawChars, new BufferChunk(buffer, index, count));
}
internal void WriteRaw(string data)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(data);
AddItem(ItemType.Raw, data);
}
internal void WriteValue(string value)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(value);
AddItem(ItemType.ValueString, value);
}
internal void Replay(XmlWriter writer)
{
if (_singleStringValue != null)
{
writer.WriteString(_singleStringValue);
return;
}
BufferChunk bufChunk;
for (int i = _firstItem; i <= _lastItem; i++)
{
Item item = _items[i];
switch (item.type)
{
case ItemType.EntityRef:
writer.WriteEntityRef((string)item.data);
break;
case ItemType.CharEntity:
writer.WriteCharEntity((char)item.data);
break;
case ItemType.SurrogateCharEntity:
char[] chars = (char[])item.data;
writer.WriteSurrogateCharEntity(chars[0], chars[1]);
break;
case ItemType.Whitespace:
writer.WriteWhitespace((string)item.data);
break;
case ItemType.String:
writer.WriteString((string)item.data);
break;
case ItemType.StringChars:
bufChunk = (BufferChunk)item.data;
writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count);
break;
case ItemType.Raw:
writer.WriteRaw((string)item.data);
break;
case ItemType.RawChars:
bufChunk = (BufferChunk)item.data;
writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count);
break;
case ItemType.ValueString:
writer.WriteValue((string)item.data);
break;
default:
Debug.Assert(false, "Unexpected ItemType value.");
break;
}
}
}
// This method trims whitespaces from the beginnig and the end of the string and cached writer events
internal void Trim()
{
// if only one string value -> trim the write spaces directly
if (_singleStringValue != null)
{
_singleStringValue = XmlConvert.TrimString(_singleStringValue);
return;
}
// trim the string in StringBuilder
string valBefore = _stringValue.ToString();
string valAfter = XmlConvert.TrimString(valBefore);
if (valBefore != valAfter)
{
_stringValue = new StringBuilder(valAfter);
}
// trim the beginning of the recorded writer events
XmlCharType xmlCharType = XmlCharType.Instance;
int i = _firstItem;
while (i == _firstItem && i <= _lastItem)
{
Item item = _items[i];
switch (item.type)
{
case ItemType.Whitespace:
_firstItem++;
break;
case ItemType.String:
case ItemType.Raw:
case ItemType.ValueString:
item.data = XmlConvert.TrimStringStart((string)item.data);
if (((string)item.data).Length == 0)
{
// no characters left -> move the firstItem index to exclude it from the Replay
_firstItem++;
}
break;
case ItemType.StringChars:
case ItemType.RawChars:
BufferChunk bufChunk = (BufferChunk)item.data;
int endIndex = bufChunk.index + bufChunk.count;
while (bufChunk.index < endIndex && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index]))
{
bufChunk.index++;
bufChunk.count--;
}
if (bufChunk.index == endIndex)
{
// no characters left -> move the firstItem index to exclude it from the Replay
_firstItem++;
}
break;
}
i++;
}
// trim the end of the recorded writer events
i = _lastItem;
while (i == _lastItem && i >= _firstItem)
{
Item item = _items[i];
switch (item.type)
{
case ItemType.Whitespace:
_lastItem--;
break;
case ItemType.String:
case ItemType.Raw:
case ItemType.ValueString:
item.data = XmlConvert.TrimStringEnd((string)item.data);
if (((string)item.data).Length == 0)
{
// no characters left -> move the lastItem index to exclude it from the Replay
_lastItem--;
}
break;
case ItemType.StringChars:
case ItemType.RawChars:
BufferChunk bufChunk = (BufferChunk)item.data;
while (bufChunk.count > 0 && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index + bufChunk.count - 1]))
{
bufChunk.count--;
}
if (bufChunk.count == 0)
{
// no characters left -> move the lastItem index to exclude it from the Replay
_lastItem--;
}
break;
}
i--;
}
}
internal void Clear()
{
_singleStringValue = null;
_lastItem = -1;
_firstItem = 0;
_stringValue.Length = 0;
}
private void StartComplexValue()
{
Debug.Assert(_singleStringValue != null);
Debug.Assert(_lastItem == -1);
_stringValue.Append(_singleStringValue);
AddItem(ItemType.String, _singleStringValue);
_singleStringValue = null;
}
private void AddItem(ItemType type, object data)
{
int newItemIndex = _lastItem + 1;
if (_items == null)
{
_items = new Item[4];
}
else if (_items.Length == newItemIndex)
{
Item[] newItems = new Item[newItemIndex * 2];
Array.Copy(_items, newItems, newItemIndex);
_items = newItems;
}
if (_items[newItemIndex] == null)
{
_items[newItemIndex] = new Item();
}
_items[newItemIndex].Set(type, data);
_lastItem = newItemIndex;
}
}
}
}
| |
// <copyright file="ZipfTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2014 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace MathNet.Numerics.UnitTests.DistributionTests.Discrete
{
using System;
using System.Linq;
using Distributions;
using NUnit.Framework;
/// <summary>
/// Zipf law tests.
/// </summary>
[TestFixture, Category("Distributions")]
public class ZipfTests
{
/// <summary>
/// Can create zipf.
/// </summary>
/// <param name="s">S parameter.</param>
/// <param name="n">N parameter.</param>
[TestCase(0.1, 1)]
[TestCase(1, 20)]
[TestCase(1, 50)]
public void CanCreateZipf(double s, int n)
{
var d = new Zipf(s, n);
Assert.AreEqual(s, d.S);
Assert.AreEqual(n, d.N);
}
/// <summary>
/// Zipf create fails with bad parameters.
/// </summary>
/// <param name="s">S parameter.</param>
/// <param name="n">N parameter.</param>
[TestCase(0.0, -10)]
[TestCase(0.0, 0)]
public void ZipfCreateFailsWithBadParameters(double s, int n)
{
Assert.That(() => new Zipf(s, n), Throws.ArgumentException);
}
/// <summary>
/// Validate ToString.
/// </summary>
[Test]
public void ValidateToString()
{
var d = new Zipf(1.0, 5);
Assert.AreEqual("Zipf(S = 1, N = 5)", d.ToString());
}
/// <summary>
/// Validate entropy.
/// </summary>
/// <param name="s">S parameter.</param>
/// <param name="n">N parameter.</param>
/// <param name="e">Expected value.</param>
[TestCase(0.1, 1, 0.0)]
[TestCase(0.1, 20, 2.9924075515295949)]
[TestCase(0.1, 50, 3.9078245132371388)]
[TestCase(1.0, 1, 0.0)]
[TestCase(1.0, 20, 2.5279968533953743)]
[TestCase(1.0, 50, 3.1971263138845916)]
public void ValidateEntropy(double s, int n, double e)
{
var d = new Zipf(s, n);
AssertHelpers.AlmostEqualRelative(e, d.Entropy, 15);
}
/// <summary>
/// Validate skewness.
/// </summary>
/// <param name="s">S parameter.</param>
/// <param name="n">N parameter.</param>
[TestCase(5.0, 1)]
[TestCase(10.0, 20)]
[TestCase(10.0, 50)]
public void ValidateSkewness(double s, int n)
{
var d = new Zipf(s, n);
if (s > 4)
{
Assert.AreEqual(((SpecialFunctions.GeneralHarmonic(n, s - 3) * Math.Pow(SpecialFunctions.GeneralHarmonic(n, s), 2)) - (SpecialFunctions.GeneralHarmonic(n, s - 1) * ((3 * SpecialFunctions.GeneralHarmonic(n, s - 2) * SpecialFunctions.GeneralHarmonic(n, s)) - Math.Pow(SpecialFunctions.GeneralHarmonic(n, s - 1), 2)))) / Math.Pow((SpecialFunctions.GeneralHarmonic(n, s - 2) * SpecialFunctions.GeneralHarmonic(n, s)) - Math.Pow(SpecialFunctions.GeneralHarmonic(n, s - 1), 2), 1.5), d.Skewness);
}
}
/// <summary>
/// Validate mode.
/// </summary>
/// <param name="s">S parameter.</param>
/// <param name="n">N parameter.</param>
[TestCase(0.1, 1)]
[TestCase(1, 20)]
[TestCase(1, 50)]
public void ValidateMode(double s, int n)
{
var d = new Zipf(s, n);
Assert.AreEqual(1, d.Mode);
}
/// <summary>
/// Validate median throws <c>NotSupportedException</c>.
/// </summary>
[Test]
public void ValidateMedianThrowsNotSupportedException()
{
var d = new Zipf(1.0, 5);
Assert.Throws<NotSupportedException>(() => { var m = d.Median; });
}
/// <summary>
/// Validate minimum.
/// </summary>
[Test]
public void ValidateMinimum()
{
var d = new Zipf(1.0, 5);
Assert.AreEqual(1, d.Minimum);
}
/// <summary>
/// Validate maximum.
/// </summary>
/// <param name="s">S parameter.</param>
/// <param name="n">N parameter.</param>
[TestCase(0.1, 1)]
[TestCase(1, 20)]
[TestCase(1, 50)]
public void ValidateMaximum(double s, int n)
{
var d = new Zipf(s, n);
Assert.AreEqual(n, d.Maximum);
}
/// <summary>
/// Validate probability.
/// </summary>
/// <param name="s">S parameter.</param>
/// <param name="n">N parameter.</param>
/// <param name="x">Input X value.</param>
[TestCase(0.1, 1, 1)]
[TestCase(1, 20, 15)]
[TestCase(1, 50, 20)]
public void ValidateProbability(double s, int n, int x)
{
var d = new Zipf(s, n);
Assert.AreEqual((1.0 / Math.Pow(x, s)) / SpecialFunctions.GeneralHarmonic(n, s), d.Probability(x));
}
/// <summary>
/// Validate probability log.
/// </summary>
/// <param name="s">S parameter.</param>
/// <param name="n">N parameter.</param>
/// <param name="x">Input X value.</param>
[TestCase(0.1, 1, 1)]
[TestCase(1, 20, 15)]
[TestCase(1, 50, 20)]
public void ValidateProbabilityLn(double s, int n, int x)
{
var d = new Zipf(s, n);
Assert.AreEqual(Math.Log(d.Probability(x)), d.ProbabilityLn(x));
}
/// <summary>
/// Can sample.
/// </summary>
[Test]
public void CanSample()
{
var d = new Zipf(0.7, 5);
var s = d.Sample();
Assert.LessOrEqual(s, 5);
Assert.GreaterOrEqual(s, 0);
}
/// <summary>
/// Can sample sequence.
/// </summary>
[Test]
public void CanSampleSequence()
{
var d = new Zipf(0.7, 5);
var ied = d.Samples();
var e = ied.Take(1000).ToArray();
foreach (var i in e)
{
Assert.LessOrEqual(i, 5);
Assert.GreaterOrEqual(i, 0);
}
}
/// <summary>
/// Validate cumulative distribution.
/// </summary>
/// <param name="s">S parameter.</param>
/// <param name="n">N parameter.</param>
/// <param name="x">Input X value.</param>
[TestCase(0.1, 1, 2)]
[TestCase(1, 20, 15)]
[TestCase(1, 50, 20)]
public void ValidateCumulativeDistribution(double s, int n, int x)
{
var d = new Zipf(s, n);
var cdf = SpecialFunctions.GeneralHarmonic(x, s) / SpecialFunctions.GeneralHarmonic(n, s);
AssertHelpers.AlmostEqualRelative(cdf, d.CumulativeDistribution(x), 14);
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon 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.Collections.Generic;
using System.Linq;
using System.Text;
using OpenSim.Framework;
using OpenMetaverse;
using System.Net;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using Nini.Config;
using System.Xml;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Region.Framework;
using OpenSim.Data;
using System.Text.RegularExpressions;
using System.Threading;
namespace OpenSim.Region.CoreModules.Agent.BotManager
{
public class BotManager : IRegionModule, IBotManager
{
#region Declares
private Scene m_scene;
private Dictionary<UUID, IBot> m_bots = new Dictionary<UUID, IBot>();
private int m_maxNumberOfBots = 40;
private int m_maxLandImpactAllowedByOutfitAttachments = 5000;
#endregion
#region IRegionModule Members
public void Initialize(Scene scene, IConfigSource source)
{
scene.RegisterModuleInterface<IBotManager>(this);
m_scene = scene;
IConfig conf = source.Configs["BotSettings"];
if (conf != null)
{
m_maxNumberOfBots = conf.GetInt("MaximumNumberOfBots", m_maxNumberOfBots);
m_maxLandImpactAllowedByOutfitAttachments = conf.GetInt("MaxLandImpactAllowedByBotOutfitAttachments", m_maxLandImpactAllowedByOutfitAttachments);
}
}
public void PostInitialize()
{
}
public void Close()
{
}
public string Name
{
get { return "BotManager"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
#region Bot Management
public UUID CreateBot(string firstName, string lastName, Vector3 startPos, string outfitName, UUID itemID, UUID owner, out string reason)
{
try
{
// do simple limit/string tests first before profile lookups
if ((firstName.Trim() == String.Empty) || (lastName.Trim() == String.Empty))
{
reason = "Invalid name: Bots require both first and last name.";
return UUID.Zero;
}
if (lastName.ToLower().Contains("inworldz") || firstName.ToLower().Contains("inworldz"))
{
reason = "Invalid name: This name has already been taken.";
return UUID.Zero;//You cannot put inworldz in the name
}
var regex = new Regex(@"\s");
if (regex.IsMatch(firstName) || regex.IsMatch(lastName))
{
reason = "Invalid name: The name cannot contain whitespace.";
return UUID.Zero;
}
lock (m_bots)
{
if (m_bots.Count + 1 > m_maxNumberOfBots)
{
reason = "The maximum number of bots has been reached.";
return UUID.Zero;
}
}
UserProfileData userCheckData = m_scene.CommsManager.UserService.GetUserProfile(firstName, lastName);
if (userCheckData != null)
{
reason = "Invalid name: This name has already been taken.";
return UUID.Zero;//You cannot use the same name as another user.
}
if (!m_scene.Permissions.CanRezObject(0, owner, UUID.Zero, startPos, false))
{
//Cannot create bot on a parcel that does not allow for rezzing an object
reason = "You do not have permissions to create a bot on this parcel.";
return UUID.Zero;
}
ILandObject parcel = m_scene.LandChannel.GetLandObject(startPos.X, startPos.Y);
if (parcel == null)
{
reason = "Land parcel could not be found at "+ ((int)startPos.X).ToString() + "," + ((int)startPos.Y).ToString();
return UUID.Zero;
}
ParcelPropertiesStatus status;
if (parcel.DenyParcelAccess(owner, out status))
{
reason = "You do not have permissions to create a bot on this parcel.";
return UUID.Zero;
}
AvatarAppearance appearance;
UUID originalOwner = UUID.Zero;
string ownerName = String.Empty;
bool isSavedOutfit = !string.IsNullOrEmpty(outfitName);
if (!isSavedOutfit)
{
ScenePresence ownerSP = m_scene.GetScenePresence(owner);
if (ownerSP == null)
{
appearance = m_scene.CommsManager.AvatarService.GetUserAppearance(owner);
if (appearance == null)
{
reason = "No appearance could be found for the owner.";
return UUID.Zero;
}
ownerName = m_scene.CommsManager.UserService.Key2Name(owner,false);
if (String.IsNullOrEmpty(ownerName))
{
reason = "Owner could not be found.";
return UUID.Zero;
}
}
else
{
//Do checks here to see whether the appearance can be saved
if (!CheckAppearanceForAttachmentCount(ownerSP))
{
reason = "The outfit has too many attachments and cannot be used.";
return UUID.Zero;
}
appearance = new AvatarAppearance(ownerSP.Appearance);
ownerName = ownerSP.Name;
}
}
else
{
appearance = m_scene.CommsManager.AvatarService.GetBotOutfit(owner, outfitName);
if (appearance == null)
{
reason = "No such outfit could be found.";
return UUID.Zero;
}
ownerName = m_scene.CommsManager.UserService.Key2Name(owner, false);
if (String.IsNullOrEmpty(ownerName))
{
reason = "Owner could not be found.";
return UUID.Zero;
}
}
BotClient client = new BotClient(firstName, lastName, m_scene, startPos, owner);
// Replace all wearables and attachments item IDs with new ones so that they cannot be found in the
// owner's avatar appearance in case the user is in the same region, wearing some of the same items.
RemapWornItems(client.AgentID, appearance);
if (!CheckAttachmentCount(client.AgentID, appearance, parcel, appearance.Owner, out reason))
{
//Too many objects already on this parcel/region
return UUID.Zero;
}
originalOwner = appearance.Owner;
appearance.Owner = client.AgentID;
appearance.IsBotAppearance = true;
string defaultAbout = "I am a 'bot' (a scripted avatar), owned by " + ownerName + ".";
AgentCircuitData data = new AgentCircuitData()
{
AgentID = client.AgentId,
Appearance = appearance,
BaseFolder = UUID.Zero,
child = false,
CircuitCode = client.CircuitCode,
ClientVersion = String.Empty,
FirstName = client.FirstName,
InventoryFolder = UUID.Zero,
LastName = client.LastName,
SecureSessionID = client.SecureSessionId,
SessionID = client.SessionId,
startpos = startPos
};
// Now that we're ready to add this bot, one last name check inside the lock.
lock (m_bots)
{
if (GetBot(firstName, lastName) != null)
{
reason = "Invalid name: A bot with this name already exists.";
return UUID.Zero;//You cannot use the same name as another bot.
}
m_bots.Add(client.AgentId, client);
}
m_scene.ConnectionManager.NewConnection(data, Region.Framework.Connection.EstablishedBy.Login);
m_scene.AddNewClient(client, true);
m_scene.ConnectionManager.TryAttachUdpCircuit(client);
ScenePresence sp;
if (m_scene.TryGetAvatar(client.AgentId, out sp))
{
sp.IsBot = true;
sp.OwnerID = owner;
m_scene.CommsManager.UserService.AddTemporaryUserProfile(new UserProfileData()
{
AboutText = defaultAbout,
Created = Util.ToUnixTime(client.TimeCreated),
CustomType = "Bot",
Email = String.Empty,
FirstLifeAboutText = defaultAbout,
FirstLifeImage = UUID.Zero,
FirstName = client.FirstName,
GodLevel = 0,
ID = client.AgentID,
Image = UUID.Zero,
ProfileURL = String.Empty,
SurName = client.LastName,
});
sp.CompleteMovement();
new Thread(() =>
{
InitialAttachmentRez(sp, appearance.GetAttachments(), originalOwner, isSavedOutfit);
}).Start();
BotRegisterForPathUpdateEvents(client.AgentID, itemID, owner);
reason = null;
return client.AgentId;
}
reason = "Something went wrong.";
}
catch (Exception ex)
{
reason = "Something went wrong: " + ex.ToString();
}
return UUID.Zero;
}
private void RemapWornItems(UUID botID, AvatarAppearance appearance)
{
// save before Clear calls
List<AvatarWearable> wearables = appearance.GetWearables();
List<AvatarAttachment> attachments = appearance.GetAttachments();
appearance.ClearWearables();
appearance.ClearAttachments();
// Remap bot outfit with new item IDs
foreach (AvatarWearable w in wearables)
{
AvatarWearable newWearable = new AvatarWearable(w);
// store a reversible back-link to the original inventory item ID.
newWearable.ItemID = w.ItemID ^ botID;
appearance.SetWearable(newWearable);
}
foreach (AvatarAttachment a in attachments)
{
// store a reversible back-link to the original inventory item ID.
UUID itemID = a.ItemID ^ botID;
appearance.SetAttachment(a.AttachPoint, true, itemID, a.AssetID);
}
}
public bool CheckAttachmentCount(UUID botID, AvatarAppearance appearance, ILandObject parcel, UUID originalOwner, out string reason)
{
int landImpact = 0;
foreach (AvatarAttachment attachment in appearance.GetAttachments())
{
// get original itemID
UUID origItemID = attachment.ItemID ^ botID;
if (origItemID == UUID.Zero)
continue;
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
var provider = inventorySelect.GetProvider(originalOwner);
InventoryItemBase item = provider.GetItem(origItemID, UUID.Zero);
SceneObjectGroup grp = m_scene.GetObjectFromItem(item);
if (grp != null)
{
if ((grp.GetEffectivePermissions(true) & (uint)PermissionMask.Copy) != (uint)PermissionMask.Copy)
continue;//No copy objects cannot be attached
landImpact += grp.LandImpact;
}
}
if (!m_scene.CheckLandImpact(parcel, landImpact, out reason))
{
//Cannot create bot on a parcel that does not allow for rezzing an object
reason = "Attachments exceed the land impact limit for this " + reason + ".";
return false;
}
reason = null;
return true;
}
public void InitialAttachmentRez(ScenePresence sp, List<AvatarAttachment> attachments, UUID originalOwner, bool isSavedOutfit)
{
ScenePresence ownerSP = null;
//retrieve all attachments
sp.Appearance.ClearAttachments();
foreach (AvatarAttachment attachment in attachments)
{
UUID origItemID = attachment.ItemID ^ sp.UUID;
if (origItemID == UUID.Zero)
continue;
// Are we already attached?
if (sp.Appearance.GetAttachmentForItem(origItemID) == null)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
var provider = inventorySelect.GetProvider(originalOwner);
InventoryItemBase item = provider.GetItem(origItemID, UUID.Zero);
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) != (uint)PermissionMask.Copy)
{
if (ownerSP == null)
ownerSP = m_scene.GetScenePresence(originalOwner);
if (ownerSP != null)
ownerSP.ControllingClient.SendAgentAlertMessage("Bot cannot wear no-copy attachment: '" + item.Name + "'.", true);
continue;//No copy objects cannot be attached
}
// sp.ControllingClient can go null on botRemoveBot from another script
IClientAPI remoteClient = sp.ControllingClient; // take a reference and use
if (remoteClient == null)
return;
SceneObjectGroup grp = m_scene.RezObject(remoteClient, remoteClient.ActiveGroupId,
origItemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
false, false, sp.UUID, true, (uint)attachment.AttachPoint, 0, null, item, false);
if (grp != null)
{
grp.OwnerID = sp.UUID; //Force UUID to botID, this should probably update the parts too, but right now they are separate
grp.SetOwnerId(grp.OwnerID); // let's do this for safety and consistency. In case childpart.OwnerID is referenced, or rootpart.OwnerID
bool tainted = false;
if (attachment.AttachPoint != 0 && attachment.AttachPoint != grp.GetBestAttachmentPoint())
tainted = true;
m_scene.SceneGraph.AttachObject(remoteClient, grp.LocalId, (uint)attachment.AttachPoint, true, false, AttachFlags.None);
if (tainted)
grp.HasGroupChanged = true;
// Fire after attach, so we don't get messy perms dialogs
//
grp.CreateScriptInstances(0, ScriptStartFlags.PostOnRez, m_scene.DefaultScriptEngine, (int)ScriptStateSource.PrimData, null);
attachment.AttachPoint = grp.RootPart.AttachmentPoint;
UUID assetId = grp.UUID;
sp.Appearance.SetAttachment((int)attachment.AttachPoint, true, attachment.ItemID, assetId);
grp.DisableUpdates = false;
grp.ScheduleGroupForFullUpdate(PrimUpdateFlags.ForcedFullUpdate);
}
}
}
}
private IBot GetBot(UUID botID)
{
IBot bot;
lock (m_bots)
{
if (!m_bots.TryGetValue(botID, out bot))
return null;
return bot;
}
}
public IBot GetBot(string first, string last)
{
string testName = String.Format("{0} {1}", first, last).ToLower();
List<UUID> ownedBots = new List<UUID>();
lock (m_bots)
{
foreach (IBot bot in m_bots.Values)
{
if (bot.Name.ToLower() == testName)
return bot;
}
}
return null;
}
private IBot GetBotWithPermission(UUID botID, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBot(botID)) == null || !CheckPermission(bot, attemptingUser))
return null;
return bot;
}
public bool RemoveBot(UUID botID, UUID attemptingUser)
{
lock (m_bots)
{
if (GetBotWithPermission(botID, attemptingUser) == null)
return false;
m_bots.Remove(botID);
}
m_scene.IncomingCloseAgent(botID);
m_scene.CommsManager.UserService.RemoveTemporaryUserProfile(botID);
return true;
}
public UUID GetBotOwner(UUID botID)
{
IBot bot;
if ((bot = GetBot(botID)) == null)
return UUID.Zero;
return bot.OwnerID;
}
public bool IsBot(UUID userID)
{
return GetBot(userID) != null;
}
public string GetBotName(UUID botID)
{
IBot bot;
if ((bot = GetBot(botID)) == null)
return String.Empty;
return bot.Name;
}
public bool ChangeBotOwner(UUID botID, UUID newOwnerID, UUID attemptingUser)
{
//This method is now unsupported
return false;
/*IBot bot;
if (!m_bots.TryGetValue(botID, out bot) || !CheckPermission(bot, attemptingUser))
return false;
bot.OwnerID = newOwnerID;
return true;*/
}
public bool SetBotProfile(UUID botID, string aboutText, string email, UUID? imageUUID, string profileURL, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
UserProfileData profile = m_scene.CommsManager.UserService.GetUserProfile(botID);
if (profile == null)
return false;
m_scene.CommsManager.UserService.AddTemporaryUserProfile(new UserProfileData()
{
AboutText = aboutText ?? profile.AboutText,
Created = Util.ToUnixTime(bot.TimeCreated),
CustomType = "Bot",
Email = email ?? profile.Email,
FirstLifeAboutText = profile.FirstLifeAboutText,
FirstLifeImage = UUID.Zero,
FirstName = bot.FirstName,
GodLevel = 0,
ID = botID,
Image = imageUUID.HasValue ? imageUUID.Value : profile.Image,
ProfileURL = profileURL ?? profile.ProfileURL,
SurName = bot.LastName,
});
return true;
}
public List<UUID> GetAllBots()
{
lock (m_bots)
return m_bots.Values.Select((b) => b.AgentID).ToList();
}
public List<UUID> GetAllOwnedBots(UUID attemptingUser)
{
List<UUID> ownedBots = new List<UUID>();
lock (m_bots)
{
foreach (IBot bot in m_bots.Values)
{
if (CheckPermission(bot, attemptingUser))
ownedBots.Add(bot.AgentID);
}
}
return ownedBots;
}
#endregion
#region Bot Outfit Management
public bool SaveOutfitToDatabase(UUID userID, string outfitName, out string reason)
{
ScenePresence sp = m_scene.GetScenePresence(userID);
if (sp == null)
{
reason = "The owner of this script must be in the sim to create an outfit.";
return false;
}
//Do checks here to see whether the appearance can be saved
if (!CheckAppearanceForAttachmentCount(sp))
{
reason = "The outfit has too many attachments and cannot be saved.";
return false;
}
reason = null;
m_scene.CommsManager.AvatarService.AddOrUpdateBotOutfit(userID, outfitName, sp.Appearance);
return true;
}
/// <summary>
/// Check whether the attachments of the given presence are too heavy
/// to be allowed to be used in an outfit
/// </summary>
/// <param name="presence"></param>
/// <returns></returns>
private bool CheckAppearanceForAttachmentCount(ScenePresence presence)
{
int totalAttachmentLandImpact = 0;
foreach(SceneObjectGroup grp in presence.GetAttachments())
{
totalAttachmentLandImpact += grp.LandImpact;
}
return totalAttachmentLandImpact < m_maxLandImpactAllowedByOutfitAttachments;
}
public void RemoveOutfitFromDatabase(UUID userID, string outfitName)
{
m_scene.CommsManager.AvatarService.RemoveBotOutfit(userID, outfitName);
}
public bool ChangeBotOutfit(UUID botID, string outfitName, UUID attemptingUser, out string reason)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
{
reason = "Could not find bot with the given UUID.";
return false;
}
ScenePresence sp;
if (m_scene.TryGetAvatar(bot.AgentID, out sp))
{
AvatarAppearance appearance;
UUID originalOwner = UUID.Zero;
if (string.IsNullOrEmpty(outfitName))
{
ScenePresence ownerSP = m_scene.GetScenePresence(attemptingUser);
if (ownerSP == null)
{
reason = "No appearance could be found for the owner.";
return false;
}
//Do checks here to see whether the appearance can be saved
if (!CheckAppearanceForAttachmentCount(ownerSP))
{
reason = "The outfit has too many attachments and cannot be used.";
return false;
}
appearance = new AvatarAppearance(ownerSP.Appearance);
}
else
{
appearance = m_scene.CommsManager.AvatarService.GetBotOutfit(attemptingUser, outfitName);
if (appearance == null)
{
reason = "No such outfit could be found.";
return false;
}
}
Vector3 pos = sp.AbsolutePosition;
ILandObject parcel = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
if (parcel == null)
{
reason = "Land parcel could not be found at " + ((int)pos.X).ToString() + "," + ((int)pos.Y).ToString();
return false;
}
// Replace all wearables and attachments item IDs with new ones so that they cannot be found in the
// owner's avatar appearance in case the user is in the same region, wearing some of the same items.
RemapWornItems(bot.AgentID, appearance); // allocate temp IDs for the new outfit.
if (!CheckAttachmentCount(bot.AgentID, appearance, parcel, appearance.Owner, out reason))
{
//Too many objects already on this parcel/region
return false;
}
reason = null;
originalOwner = appearance.Owner;
appearance.Owner = bot.AgentID;
appearance.IsBotAppearance = true;
sp.Appearance = appearance;
if (appearance.AvatarHeight > 0)
sp.SetHeight(appearance.AvatarHeight);
sp.SendInitialData();
List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
foreach (SceneObjectGroup group in sp.GetAttachments())
{
sp.Appearance.DetachAttachment(group.GetFromItemID());
group.DetachToInventoryPrep();
m_scene.DeleteSceneObject(group, false);
}
new Thread(() =>
{
InitialAttachmentRez(sp, attachments, originalOwner, true);
}).Start();
return true;
}
reason = "Could not find bot with the given UUID.";
return false;
}
public List<string> GetBotOutfitsByOwner(UUID userID)
{
return m_scene.CommsManager.AvatarService.GetBotOutfitsByOwner(userID);
}
#endregion
#region Bot Movement
public BotMovementResult StartFollowingAvatar(UUID botID, UUID avatarID, Dictionary<int, object> options, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return BotMovementResult.BotNotFound;
if (m_scene.GetScenePresence(avatarID) == null)
return BotMovementResult.UserNotFound;
bot.MovementController.StartFollowingAvatar(avatarID, options);
return BotMovementResult.Success;
}
public BotMovementResult SetBotNavigationPoints(UUID botID, List<Vector3> positions, List<TravelMode> modes, Dictionary<int, object> options, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return BotMovementResult.BotNotFound;
bot.MovementController.StartNavigationPath(positions, modes, options);
return BotMovementResult.Success;
}
public BotMovementResult WanderWithin(UUID botID, Vector3 origin, Vector3 distances, Dictionary<int, object> options, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return BotMovementResult.BotNotFound;
bot.MovementController.StartWandering(origin, distances, options);
return BotMovementResult.Success;
}
public bool StopMovement(UUID botID, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
if (!bot.MovementController.MovementInProgress)
return false;
bot.MovementController.StopMovement();
return true;
}
public bool PauseBotMovement(UUID botID, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
if (!bot.MovementController.MovementInProgress)
return false;
bot.MovementController.PauseMovement();
return true;
}
public bool ResumeBotMovement(UUID botID, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
if (!bot.MovementController.MovementInProgress)
return false;
bot.MovementController.ResumeMovement();
return true;
}
public bool SetBotSpeed(UUID botID, float speed, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
return bot.SetSpeed(speed);
}
public Vector3 GetBotPosition(UUID botID, UUID attemptingUser)
{
if (GetBot(botID) == null)
return Vector3.Zero;
ScenePresence sp = m_scene.GetScenePresence(botID);
if (sp == null)
return Vector3.Zero;
return sp.AbsolutePosition;
}
public bool SetBotPosition(UUID botID, Vector3 position, UUID attemptingUser)
{
if (GetBotWithPermission(botID, attemptingUser) == null)
return false;
ScenePresence sp = m_scene.GetScenePresence(botID);
if (sp == null)
return false;
sp.StandUp(false, true);
sp.Teleport(position);
return true;
}
public bool SetBotRotation(UUID botID, Quaternion rotation, UUID attemptingUser)
{
if (GetBotWithPermission(botID, attemptingUser) == null)
return false;
ScenePresence sp = m_scene.GetScenePresence(botID);
if (sp == null)
return false;
if (sp.PhysicsActor != null)
{
EntityBase.PositionInfo posInfo = sp.GetPosInfo();
posInfo.m_pos.Z += 0.001f;
sp.SetAgentPositionInfo(null, false, posInfo.m_pos, posInfo.m_parent, Vector3.Zero, sp.Velocity);
}
sp.Rotation = rotation;
sp.SendTerseUpdateToAllClients();
return true;
}
#endregion
#region Tag/Remove bots
private readonly Dictionary<string, List<UUID>> m_botTags = new Dictionary<string, List<UUID>>();
public bool AddTagToBot(UUID botID, string tag, UUID attemptingUser)
{
if (GetBotWithPermission(botID, attemptingUser) == null)
return false;
if (!m_botTags.ContainsKey(tag))
m_botTags.Add(tag, new List<UUID>());
m_botTags[tag].Add(botID);
return true;
}
public bool BotHasTag(UUID botID, string tag)
{
if (m_botTags.ContainsKey(tag))
return m_botTags[tag].Contains(botID);
return false;
}
public List<string> GetBotTags(UUID botID)
{
List<string> ret = new List<string>();
foreach (KeyValuePair<string, List<UUID>> tag in m_botTags)
if (tag.Value.Contains(botID))
ret.Add(tag.Key);
return ret;
}
public List<UUID> GetBotsWithTag(string tag)
{
if (!m_botTags.ContainsKey(tag))
return new List<UUID>();
return new List<UUID>(m_botTags[tag]);
}
public bool RemoveBotsWithTag(string tag, UUID attemptingUser)
{
List<UUID> bots = GetBotsWithTag(tag);
bool success = true;
foreach (UUID botID in bots)
{
if (GetBotWithPermission(botID, attemptingUser) == null)
{
success = false;
continue;
}
RemoveTagFromBot(botID, tag, attemptingUser);
RemoveBot(botID, attemptingUser);
}
return success;
}
public bool RemoveTagFromBot(UUID botID, string tag, UUID attemptingUser)
{
if (GetBotWithPermission(botID, attemptingUser) == null)
return false;
if (m_botTags.ContainsKey(tag))
m_botTags[tag].Remove(botID);
return true;
}
public bool RemoveAllTagsFromBot(UUID botID, UUID attemptingUser)
{
if (GetBotWithPermission(botID, attemptingUser) == null)
return false;
List<string> tagsToRemove = new List<string>();
foreach (KeyValuePair<string, List<UUID>> kvp in m_botTags)
{
if (kvp.Value.Contains(botID))
tagsToRemove.Add(kvp.Key);
}
foreach (string tag in tagsToRemove)
m_botTags[tag].Remove(botID);
return true;
}
#endregion
#region Region Interaction Methods
public bool SitBotOnObject(UUID botID, UUID objectID, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
return bot.SitOnObject(objectID);
}
public bool StandBotUp(UUID botID, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
return bot.StandUp();
}
public bool BotTouchObject(UUID botID, UUID objectID, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
return bot.TouchObject(objectID);
}
public bool GiveInventoryObject(UUID botID, SceneObjectPart part, string objName, UUID objId, byte assetType, UUID destId, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
bot.GiveInventoryObject(part, objName, objId, assetType, destId);
return true;
}
#endregion
#region Bot Animation
public bool StartBotAnimation(UUID botID, UUID animID, string anim, UUID objectID, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
return bot.StartAnimation(animID, anim, objectID);
}
public bool StopBotAnimation(UUID botID, UUID animID, string animation, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
return bot.StopAnimation(animID, animation);
}
#endregion
#region Event Registration Methods
public bool BotRegisterForPathUpdateEvents(UUID botID, UUID itemID, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
lock (bot.RegisteredScriptsForPathUpdateEvents)
{
if (!bot.RegisteredScriptsForPathUpdateEvents.Contains(itemID))
{
bot.RegisteredScriptsForPathUpdateEvents.Add(itemID);
return true;
}
}
return false;
}
public bool BotDeregisterFromPathUpdateEvents(UUID botID, UUID itemID, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
lock (bot.RegisteredScriptsForPathUpdateEvents)
{
if (bot.RegisteredScriptsForPathUpdateEvents.Contains(itemID))
{
bot.RegisteredScriptsForPathUpdateEvents.Remove(itemID);
return true;
}
}
return false;
}
public bool BotRegisterForCollisionEvents(UUID botID, SceneObjectGroup group, UUID attemptingUser)
{
if (GetBotWithPermission(botID, attemptingUser) == null)
return false;
ScenePresence botSP = m_scene.GetScenePresence(botID);
if (botSP == null || group == null)
return false;
botSP.RegisterGroupToCollisionUpdates(group);
return true;
}
public bool BotDeregisterFromCollisionEvents(UUID botID, SceneObjectGroup group, UUID attemptingUser)
{
if (GetBotWithPermission(botID, attemptingUser) == null)
return false;
ScenePresence botSP = m_scene.GetScenePresence(botID);
if (botSP == null || group == null)
return false;
botSP.DeregisterGroupFromCollisionUpdates(group);
return true;
}
#endregion
#region Chat Methods
public bool BotChat(UUID botID, int channel, string message, ChatTypeEnum sourceType, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
bot.Say(channel, message, sourceType);
return true;
}
public bool SendInstantMessageForBot(UUID botID, UUID userID, string message, UUID attemptingUser)
{
IBot bot;
if ((bot = GetBotWithPermission(botID, attemptingUser)) == null)
return false;
bot.SendInstantMessage(userID, message);
return true;
}
#endregion
#region Permissions Check
public bool CheckPermission(UUID botID, UUID attemptingUser)
{
if (GetBotWithPermission(botID, attemptingUser) == null)
return false;
return true;
}
private bool CheckPermission(IBot bot, UUID attemptingUser)
{
if (attemptingUser == UUID.Zero)
return true; //Forced override
if (bot != null)
{
if (bot.OwnerID == attemptingUser || bot.OwnerID == UUID.Zero)
return true;
}
return false;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Globalization.Tests
{
public class PersianCalendarTests : CalendarTestBase
{
public override Calendar Calendar => new PersianCalendar();
public override DateTime MinSupportedDateTime => new DateTime(0622, 03, 22);
[Fact]
public void CalendarConversion()
{
PersianCalendar calendar = new PersianCalendar();
for (int i = 0; i < s_dates.Length; i+= 6)
{
DateTime date = new DateTime(s_dates[i + 3], s_dates[i + 4], s_dates[i + 5]);
Assert.Equal(s_dates[i], calendar.GetYear(date));
Assert.Equal(s_dates[i + 1], calendar.GetMonth(date));
Assert.Equal(s_dates[i + 2], calendar.GetDayOfMonth(date));
DateTime result = calendar.ToDateTime(s_dates[i], s_dates[i + 1], s_dates[i + 2], 0, 0, 0, 0);
Assert.Equal(s_dates[i + 3], result.Year);
Assert.Equal(s_dates[i + 4], result.Month);
Assert.Equal(s_dates[i + 5], result.Day);
}
}
[Fact]
public void IsLeapYear()
{
PersianCalendar calendar = new PersianCalendar();
int lastNonLeap = 1;
foreach (int year in s_leapYears)
{
Assert.True(calendar.IsLeapYear(year), string.Format("Year {0} is not recognized as leap year", year));
Assert.False(calendar.IsLeapYear(lastNonLeap), string.Format("Year {0} is recognized as leap year", lastNonLeap));
lastNonLeap = year - 1;
}
Assert.False(calendar.IsLeapYear(9378));
}
[Theory]
[InlineData(9378, 10)]
[InlineData(1, 2)]
[InlineData(5, 2)]
public void IsLeapMonth(int year, int month)
{
PersianCalendar calendar = new PersianCalendar();
Assert.False(calendar.IsLeapMonth(year, month));
Assert.False(calendar.IsLeapMonth(year, month, 0));
Assert.False(calendar.IsLeapMonth(year, month, 1));
}
[Theory]
[InlineData(9378, 10, 1, false)]
[InlineData(1, 2, 28, false)]
[InlineData(5, 12, 30, true)]
public void IsLeapDay(int year, int month, int day, bool expected)
{
PersianCalendar calendar = new PersianCalendar();
Assert.Equal(expected, calendar.IsLeapDay(year, month, day));
Assert.Equal(expected, calendar.IsLeapDay(year, month, day, 0));
Assert.Equal(expected, calendar.IsLeapDay(year, month, day, 1));
}
[Theory]
[InlineData(9378)]
[InlineData(1)]
[InlineData(5)]
public void GetLeapMonth(int year)
{
PersianCalendar calendar = new PersianCalendar();
int expected = 0;
Assert.Equal(expected, calendar.GetLeapMonth(year, 0));
Assert.Equal(expected, calendar.GetLeapMonth(year, 1));
}
[Theory]
[InlineData(9378, 289)]
[InlineData(1, 365)]
[InlineData(5, 366)]
public void GetDaysInYear(int year, int expected)
{
PersianCalendar calendar = new PersianCalendar();
Assert.Equal(expected, calendar.GetDaysInYear(year));
Assert.Equal(expected, calendar.GetDaysInYear(year, 0));
Assert.Equal(expected, calendar.GetDaysInYear(year, 1));
}
[Theory]
[InlineData(9378, 10)]
[InlineData(1, 12)]
[InlineData(5, 12)]
public void GetMonthsInYear(int year, int expected)
{
PersianCalendar calendar = new PersianCalendar();
Assert.Equal(expected, calendar.GetMonthsInYear(year));
Assert.Equal(expected, calendar.GetMonthsInYear(year, 0));
Assert.Equal(expected, calendar.GetMonthsInYear(year, 1));
}
public static IEnumerable<object[]> GetDayOfWeek_TestData()
{
yield return new object[] { DateTime.MinValue };
yield return new object[] { new DateTime(5, 12, 30) };
yield return new object[] { DateTime.MaxValue };
}
[Theory]
[MemberData(nameof(GetDayOfWeek_TestData))]
public void GetDayOfWeek(DateTime time)
{
Assert.Equal(time.DayOfWeek, new PersianCalendar().GetDayOfWeek(time));
}
[Theory]
[InlineData(99)]
[InlineData(2016)]
[InlineData(9378)]
public void TwoDigitYearMax_Set(int newTwoDigitYearMax)
{
PersianCalendar calendar = new PersianCalendar();
calendar.TwoDigitYearMax = newTwoDigitYearMax;
Assert.Equal(newTwoDigitYearMax, calendar.TwoDigitYearMax);
}
[Theory]
[InlineData(99, 1399)]
[InlineData(100, 100)]
[InlineData(2016, 2016)]
public void ToFourDigitYear(int year, int expected)
{
PersianCalendar calendar = new PersianCalendar();
calendar.TwoDigitYearMax = 1410; // Set to the default
Assert.Equal(expected, calendar.ToFourDigitYear(year));
}
private static int[] s_dates = new int[]
{
// Persian year, Persian Month, Persian Day, Gregorian Year, Gregorian Month, Gregorian Day
1, 1, 1, 622, 3, 22,
101, 2, 2, 722, 4, 23,
201, 3, 3, 822, 5, 24,
301, 4, 4, 922, 6, 25,
401, 5, 5, 1022, 7, 27,
501, 6, 6, 1122, 8, 29,
601, 7, 7, 1222, 9, 29,
701, 8, 8, 1322, 10, 30,
801, 9, 9, 1422, 11, 30,
901, 10, 10, 1523, 1, 1,
1001, 11, 11, 1623, 1, 31,
1101, 12, 12, 1723, 3, 3,
1202, 1, 13, 1823, 4, 3,
1302, 2, 14, 1923, 5, 5,
1402, 3, 15, 2023, 6, 5,
1502, 4, 16, 2123, 7, 7,
1602, 5, 17, 2223, 8, 8,
1702, 6, 18, 2323, 9, 10,
1802, 7, 19, 2423, 10, 11,
1902, 8, 20, 2523, 11, 11,
2002, 9, 21, 2623, 12, 12,
2102, 10, 22, 2724, 1, 13,
2202, 11, 23, 2824, 2, 12,
2302, 12, 24, 2924, 3, 14,
2403, 1, 25, 3024, 4, 14,
2503, 2, 26, 3124, 5, 16,
2603, 3, 27, 3224, 6, 16,
2703, 4, 28, 3324, 7, 18,
2803, 5, 29, 3424, 8, 20,
2903, 6, 30, 3524, 9, 21,
3003, 8, 1, 3624, 10, 22,
3103, 9, 2, 3724, 11, 22,
3203, 10, 3, 3824, 12, 24,
3303, 11, 4, 3925, 1, 24,
3403, 12, 5, 4025, 2, 23,
3504, 1, 6, 4125, 3, 25,
3604, 2, 7, 4225, 4, 27,
3704, 3, 8, 4325, 5, 29,
3804, 4, 9, 4425, 6, 29,
3904, 5, 10, 4525, 7, 31,
4004, 6, 11, 4625, 9, 2,
4104, 7, 12, 4725, 10, 4,
4204, 8, 13, 4825, 11, 3,
4304, 9, 14, 4925, 12, 4,
4404, 10, 15, 5026, 1, 5,
4504, 11, 16, 5126, 2, 5,
4604, 12, 17, 5226, 3, 7,
4705, 1, 18, 5326, 4, 6,
4805, 2, 19, 5426, 5, 9,
4905, 3, 20, 5526, 6, 10,
5005, 4, 21, 5626, 7, 11,
5105, 5, 22, 5726, 8, 12,
5205, 6, 23, 5826, 9, 14,
5305, 7, 24, 5926, 10, 16,
5405, 8, 25, 6026, 11, 15,
5505, 9, 26, 6126, 12, 16,
5605, 10, 27, 6227, 1, 16,
5705, 11, 28, 6327, 2, 17,
5805, 12, 29, 6427, 3, 19,
5906, 1, 30, 6527, 4, 18,
6006, 2, 31, 6627, 5, 21,
6106, 4, 1, 6727, 6, 22,
6206, 5, 2, 6827, 7, 23,
6306, 6, 3, 6927, 8, 24,
6406, 7, 4, 7027, 9, 25,
6506, 8, 5, 7127, 10, 27,
6606, 9, 6, 7227, 11, 26,
6706, 10, 7, 7327, 12, 27,
6806, 11, 8, 7428, 1, 27,
6906, 12, 9, 7528, 2, 27,
7007, 1, 10, 7628, 3, 28,
7107, 2, 11, 7728, 4, 29,
7207, 3, 12, 7828, 5, 31,
7307, 4, 13, 7928, 7, 2,
7407, 5, 14, 8028, 8, 3,
7507, 6, 15, 8128, 9, 4,
7607, 7, 16, 8228, 10, 6,
7707, 8, 17, 8328, 11, 6,
7807, 9, 18, 8428, 12, 6,
7907, 10, 19, 8529, 1, 6,
8007, 11, 20, 8629, 2, 7,
8107, 12, 21, 8729, 3, 10,
8208, 1, 22, 8829, 4, 8,
8308, 2, 23, 8929, 5, 10,
8408, 3, 24, 9029, 6, 11,
8508, 4, 25, 9129, 7, 14,
8608, 5, 26, 9229, 8, 14,
8708, 6, 27, 9329, 9, 15,
8808, 7, 28, 9429, 10, 17,
8908, 8, 29, 9529, 11, 17,
9008, 9, 30, 9629, 12, 17,
9108, 11, 1, 9730, 1, 18,
9208, 12, 2, 9830, 2, 18,
9309, 1, 3, 9930, 3, 20,
9378, 10, 13, 9999, 12, 31,
};
private static int[] s_leapYears = new int[]
{
5, 9, 13, 17, 21, 25, 29, 33, 38, 42, 46, 50, 54, 58, 62, 66, 71, 75, 79, 83, 87, 91, 95, 99, 104, 108, 112, 116, 120, 124, 128, 132, 137, 141, 145, 149, 153, 157, 161, 166, 170, 174,
178, 182, 186, 190, 194, 199, 203, 207, 211, 215, 219, 223, 227, 232, 236, 240, 244, 248, 252, 256, 260, 265, 269, 273, 277, 281, 285, 289, 293, 298, 302, 306, 310, 314, 318, 322, 327,
331, 335, 339, 343, 347, 351, 355, 359, 364, 368, 372, 376, 380, 384, 388, 392, 397, 401, 405, 409, 413, 417, 421, 426, 430, 434, 438, 442, 446, 450, 454, 459, 463, 467, 471, 475, 479,
483, 487, 492, 496, 500, 504, 508, 512, 516, 520, 525, 529, 533, 537, 541, 545, 549, 553, 558, 562, 566, 570, 574, 578, 582, 586, 591, 595, 599, 603, 607, 611, 615, 619, 624, 628, 632,
636, 640, 644, 648, 652, 657, 661, 665, 669, 673, 677, 681, 686, 690, 694, 698, 702, 706, 710, 714, 719, 723, 727, 731, 735, 739, 743, 747, 752, 756, 760, 764, 768, 772, 776, 780, 785,
789, 793, 797, 801, 805, 809, 813, 818, 822, 826, 830, 834, 838, 842, 846, 851, 855, 859, 863, 867, 871, 875, 879, 884, 888, 892, 896, 900, 904, 908, 912, 917, 921, 925, 929, 933, 937,
941, 945, 950, 954, 958, 962, 966, 970, 974, 978, 983, 987, 991, 995, 999, 1003, 1007, 1011, 1016, 1020, 1024, 1028, 1032, 1036, 1040, 1044, 1049, 1053, 1057, 1061, 1065, 1069, 1073, 1077,
1082, 1086, 1090, 1094, 1098, 1102, 1106, 1111, 1115, 1119, 1123, 1127, 1131, 1135, 1139, 1144, 1148, 1152, 1156, 1160, 1164, 1168, 1172, 1176, 1181, 1185, 1189, 1193, 1197, 1201, 1205,
1210, 1214, 1218, 1222, 1226, 1230, 1234, 1238, 1243, 1247, 1251, 1255, 1259, 1263, 1267, 1271, 1276, 1280, 1284, 1288, 1292, 1296, 1300, 1304, 1309, 1313, 1317, 1321, 1325, 1329, 1333,
1337, 1342, 1346, 1350, 1354, 1358, 1362, 1366, 1370, 1375, 1379, 1383, 1387, 1391, 1395, 1399, 1403, 1408, 1412, 1416, 1420, 1424, 1428, 1432, 1436, 1441, 1445, 1449, 1453, 1457, 1461,
1465, 1469, 1474, 1478, 1482, 1486, 1490, 1494, 1498, 1503, 1507, 1511, 1515, 1519, 1523, 1527, 1531, 1536, 1540, 1544, 1548, 1552, 1556, 1560, 1564, 1568, 1573, 1577, 1581, 1585, 1589,
1593, 1597, 1602, 1606, 1610, 1614, 1618, 1622, 1626, 1630, 1635, 1639, 1643, 1647, 1651, 1655, 1659, 1663, 1668, 1672, 1676, 1680, 1684, 1688, 1692, 1696, 1701, 1705, 1709, 1713, 1717,
1721, 1725, 1729, 1734, 1738, 1742, 1746, 1750, 1754, 1758, 1762, 1767, 1771, 1775, 1779, 1783, 1787, 1791, 1795, 1800, 1804, 1808, 1812, 1816, 1820, 1824, 1828, 1833, 1837, 1841, 1845,
1849, 1853, 1857, 1861, 1866, 1870, 1874, 1878, 1882, 1886, 1890, 1894, 1899, 1903, 1907, 1911, 1915, 1919, 1923, 1927, 1932, 1936, 1940, 1944, 1948, 1952, 1956, 1960, 1965, 1969, 1973,
1977, 1981, 1985, 1989, 1993, 1998, 2002, 2006, 2010, 2014, 2018, 2022, 2027, 2031, 2035, 2039, 2043, 2047, 2051, 2055, 2060, 2064, 2068, 2072, 2076, 2080, 2084, 2088, 2093, 2097, 2101,
2105, 2109, 2113, 2117, 2121, 2125, 2130, 2134, 2138, 2142, 2146, 2150, 2154, 2159, 2163, 2167, 2171, 2175, 2179, 2183, 2187, 2192, 2196, 2200, 2204, 2208, 2212, 2216, 2220, 2225, 2229,
2233, 2237, 2241, 2245, 2249, 2253, 2258, 2262, 2266, 2270, 2274, 2278, 2282, 2286, 2291, 2295, 2299, 2303, 2307, 2311, 2315, 2319, 2324, 2328, 2332, 2336, 2340, 2344, 2348, 2352, 2357,
2361, 2365, 2369, 2373, 2377, 2381, 2385, 2390, 2394, 2398, 2402, 2406, 2410, 2414, 2418, 2423, 2427, 2431, 2435, 2439, 2443, 2447, 2451, 2456, 2460, 2464, 2468, 2472, 2476, 2480, 2484,
2489, 2493, 2497, 2501, 2505, 2509, 2513, 2517, 2522, 2526, 2530, 2534, 2538, 2542, 2546, 2550, 2555, 2559, 2563, 2567, 2571, 2575, 2579, 2584, 2588, 2592, 2596, 2600, 2604, 2608, 2612,
2617, 2621, 2625, 2629, 2633, 2637, 2641, 2645, 2649, 2654, 2658, 2662, 2666, 2670, 2674, 2678, 2682, 2687, 2691, 2695, 2699, 2703, 2707, 2711, 2716, 2720, 2724, 2728, 2732, 2736, 2740,
2744, 2749, 2753, 2757, 2761, 2765, 2769, 2773, 2777, 2782, 2786, 2790, 2794, 2798, 2802, 2806, 2810, 2814, 2819, 2823, 2827, 2831, 2835, 2839, 2843, 2848, 2852, 2856, 2860, 2864, 2868,
2872, 2876, 2881, 2885, 2889, 2893, 2897, 2901, 2905, 2909, 2914, 2918, 2922, 2926, 2930, 2934, 2938, 2942, 2947, 2951, 2955, 2959, 2963, 2967, 2971, 2975, 2980, 2984, 2988, 2992, 2996,
3000, 3004, 3008, 3013, 3017, 3021, 3025, 3029, 3033, 3037, 3041, 3046, 3050, 3054, 3058, 3062, 3066, 3070, 3074, 3079, 3083, 3087, 3091, 3095, 3099, 3103, 3107, 3112, 3116, 3120, 3124,
3128, 3132, 3136, 3141, 3145, 3149, 3153, 3157, 3161, 3165, 3169, 3173, 3178, 3182, 3186, 3190, 3194, 3198, 3202, 3206, 3211, 3215, 3219, 3223, 3227, 3231, 3235, 3239, 3244, 3248, 3252,
3256, 3260, 3264, 3268, 3273, 3277, 3281, 3285, 3289, 3293, 3297, 3301, 3306, 3310, 3314, 3318, 3322, 3326, 3330, 3334, 3339, 3343, 3347, 3351, 3355, 3359, 3363, 3367, 3372, 3376, 3380,
3384, 3388, 3392, 3396, 3400, 3405, 3409, 3413, 3417, 3421, 3425, 3429, 3433, 3438, 3442, 3446, 3450, 3454, 3458, 3462, 3466, 3471, 3475, 3479, 3483, 3487, 3491, 3495, 3499, 3504, 3508,
3512, 3516, 3520, 3524, 3528, 3532, 3537, 3541, 3545, 3549, 3553, 3557, 3561, 3565, 3570, 3574, 3578, 3582, 3586, 3590, 3594, 3598, 3603, 3607, 3611, 3615, 3619, 3623, 3627, 3631, 3636,
3640, 3644, 3648, 3652, 3656, 3660, 3665, 3669, 3673, 3677, 3681, 3685, 3689, 3693, 3698, 3702, 3706, 3710, 3714, 3718, 3722, 3726, 3731, 3735, 3739, 3743, 3747, 3751, 3755, 3759, 3764,
3768, 3772, 3776, 3780, 3784, 3788, 3792, 3797, 3801, 3805, 3809, 3813, 3817, 3821, 3825, 3830, 3834, 3838, 3842, 3846, 3850, 3854, 3858, 3863, 3867, 3871, 3875, 3879, 3883, 3887, 3891,
3896, 3900, 3904, 3908, 3912, 3916, 3920, 3925, 3929, 3933, 3937, 3941, 3945, 3949, 3953, 3958, 3962, 3966, 3970, 3974, 3978, 3982, 3986, 3991, 3995, 3999, 4003, 4007, 4011, 4015, 4019,
4024, 4028, 4032, 4036, 4040, 4044, 4048, 4052, 4057, 4061, 4065, 4069, 4073, 4077, 4081, 4085, 4090, 4094, 4098, 4102, 4106, 4110, 4114, 4118, 4123, 4127, 4131, 4135, 4139, 4143, 4147,
4151, 4156, 4160, 4164, 4168, 4172, 4176, 4180, 4185, 4189, 4193, 4197, 4201, 4205, 4209, 4213, 4218, 4222, 4226, 4230, 4234, 4238, 4242, 4246, 4251, 4255, 4259, 4263, 4267, 4271, 4275,
4279, 4284, 4288, 4292, 4296, 4300, 4304, 4308, 4312, 4317, 4321, 4325, 4329, 4333, 4337, 4341, 4345, 4350, 4354, 4358, 4362, 4366, 4370, 4374, 4378, 4383, 4387, 4391, 4395, 4399, 4403,
4407, 4411, 4416, 4420, 4424, 4428, 4432, 4436, 4440, 4445, 4449, 4453, 4457, 4461, 4465, 4469, 4473, 4478, 4482, 4486, 4490, 4494, 4498, 4502, 4506, 4511, 4515, 4519, 4523, 4527, 4531,
4535, 4539, 4544, 4548, 4552, 4556, 4560, 4564, 4568, 4572, 4577, 4581, 4585, 4589, 4593, 4597, 4601, 4605, 4610, 4614, 4618, 4622, 4626, 4630, 4634, 4638, 4643, 4647, 4651, 4655, 4659,
4663, 4667, 4672, 4676, 4680, 4684, 4688, 4692, 4696, 4700, 4705, 4709, 4713, 4717, 4721, 4725, 4729, 4733, 4738, 4742, 4746, 4750, 4754, 4758, 4762, 4766, 4771, 4775, 4779, 4783, 4787,
4791, 4795, 4800, 4804, 4808, 4812, 4816, 4820, 4824, 4828, 4833, 4837, 4841, 4845, 4849, 4853, 4857, 4861, 4866, 4870, 4874, 4878, 4882, 4886, 4890, 4894, 4899, 4903, 4907, 4911, 4915,
4919, 4923, 4927, 4932, 4936, 4940, 4944, 4948, 4952, 4956, 4960, 4965, 4969, 4973, 4977, 4981, 4985, 4989, 4993, 4998, 5002, 5006, 5010, 5014, 5018, 5022, 5027, 5031, 5035, 5039, 5043,
5047, 5051, 5055, 5060, 5064, 5068, 5072, 5076, 5080, 5084, 5088, 5093, 5097, 5101, 5105, 5109, 5113, 5117, 5121, 5126, 5130, 5134, 5138, 5142, 5146, 5150, 5155, 5159, 5163, 5167, 5171,
5175, 5179, 5183, 5188, 5192, 5196, 5200, 5204, 5208, 5212, 5216, 5221, 5225, 5229, 5233, 5237, 5241, 5245, 5249, 5254, 5258, 5262, 5266, 5270, 5274, 5278, 5283, 5287, 5291, 5295, 5299,
5303, 5307, 5311, 5316, 5320, 5324, 5328, 5332, 5336, 5340, 5344, 5349, 5353, 5357, 5361, 5365, 5369, 5373, 5377, 5382, 5386, 5390, 5394, 5398, 5402, 5406, 5411, 5415, 5419, 5423, 5427,
5431, 5435, 5439, 5444, 5448, 5452, 5456, 5460, 5464, 5468, 5472, 5477, 5481, 5485, 5489, 5493, 5497, 5501, 5506, 5510, 5514, 5518, 5522, 5526, 5530, 5534, 5539, 5543, 5547, 5551, 5555,
5559, 5563, 5567, 5572, 5576, 5580, 5584, 5588, 5592, 5596, 5601, 5605, 5609, 5613, 5617, 5621, 5625, 5629, 5634, 5638, 5642, 5646, 5650, 5654, 5658, 5662, 5667, 5671, 5675, 5679, 5683,
5687, 5691, 5695, 5700, 5704, 5708, 5712, 5716, 5720, 5724, 5729, 5733, 5737, 5741, 5745, 5749, 5753, 5757, 5762, 5766, 5770, 5774, 5778, 5782, 5786, 5790, 5795, 5799, 5803, 5807, 5811,
5815, 5819, 5824, 5828, 5832, 5836, 5840, 5844, 5848, 5852, 5857, 5861, 5865, 5869, 5873, 5877, 5881, 5885, 5890, 5894, 5898, 5902, 5906, 5910, 5914, 5919, 5923, 5927, 5931, 5935, 5939,
5943, 5947, 5952, 5956, 5960, 5964, 5968, 5972, 5976, 5980, 5985, 5989, 5993, 5997, 6001, 6005, 6009, 6014, 6018, 6022, 6026, 6030, 6034, 6038, 6042, 6047, 6051, 6055, 6059, 6063, 6067,
6071, 6076, 6080, 6084, 6088, 6092, 6096, 6100, 6104, 6109, 6113, 6117, 6121, 6125, 6129, 6133, 6138, 6142, 6146, 6150, 6154, 6158, 6162, 6166, 6171, 6175, 6179, 6183, 6187, 6191, 6195,
6199, 6204, 6208, 6212, 6216, 6220, 6224, 6228, 6233, 6237, 6241, 6245, 6249, 6253, 6257, 6261, 6266, 6270, 6274, 6278, 6282, 6286, 6290, 6294, 6299, 6303, 6307, 6311, 6315, 6319, 6323,
6328, 6332, 6336, 6340, 6344, 6348, 6352, 6356, 6361, 6365, 6369, 6373, 6377, 6381, 6385, 6389, 6394, 6398, 6402, 6406, 6410, 6414, 6418, 6423, 6427, 6431, 6435, 6439, 6443, 6447, 6452,
6456, 6460, 6464, 6468, 6472, 6476, 6480, 6485, 6489, 6493, 6497, 6501, 6505, 6509, 6513, 6518, 6522, 6526, 6530, 6534, 6538, 6542, 6547, 6551, 6555, 6559, 6563, 6567, 6571, 6575, 6580,
6584, 6588, 6592, 6596, 6600, 6604, 6608, 6613, 6617, 6621, 6625, 6629, 6633, 6637, 6642, 6646, 6650, 6654, 6658, 6662, 6666, 6671, 6675, 6679, 6683, 6687, 6691, 6695, 6699, 6704, 6708,
6712, 6716, 6720, 6724, 6728, 6733, 6737, 6741, 6745, 6749, 6753, 6757, 6761, 6766, 6770, 6774, 6778, 6782, 6786, 6790, 6794, 6799, 6803, 6807, 6811, 6815, 6819, 6823, 6828, 6832, 6836,
6840, 6844, 6848, 6852, 6856, 6861, 6865, 6869, 6873, 6877, 6881, 6885, 6890, 6894, 6898, 6902, 6906, 6910, 6914, 6919, 6923, 6927, 6931, 6935, 6939, 6943, 6947, 6952, 6956, 6960, 6964,
6968, 6972, 6976, 6980, 6985, 6989, 6993, 6997, 7001, 7005, 7009, 7014, 7018, 7022, 7026, 7030, 7034, 7038, 7043, 7047, 7051, 7055, 7059, 7063, 7067, 7071, 7076, 7080, 7084, 7088, 7092,
7096, 7100, 7105, 7109, 7113, 7117, 7121, 7125, 7129, 7133, 7138, 7142, 7146, 7150, 7154, 7158, 7162, 7167, 7171, 7175, 7179, 7183, 7187, 7191, 7196, 7200, 7204, 7208, 7212, 7216, 7220,
7224, 7229, 7233, 7237, 7241, 7245, 7249, 7253, 7258, 7262, 7266, 7270, 7274, 7278, 7282, 7286, 7291, 7295, 7299, 7303, 7307, 7311, 7315, 7320, 7324, 7328, 7332, 7336, 7340, 7344, 7349,
7353, 7357, 7361, 7365, 7369, 7373, 7377, 7382, 7386, 7390, 7394, 7398, 7402, 7406, 7411, 7415, 7419, 7423, 7427, 7431, 7435, 7439, 7444, 7448, 7452, 7456, 7460, 7464, 7468, 7473, 7477,
7481, 7485, 7489, 7493, 7497, 7502, 7506, 7510, 7514, 7518, 7522, 7526, 7531, 7535, 7539, 7543, 7547, 7551, 7555, 7559, 7564, 7568, 7572, 7576, 7580, 7584, 7588, 7593, 7597, 7601, 7605,
7609, 7613, 7617, 7621, 7626, 7630, 7634, 7638, 7642, 7646, 7650, 7655, 7659, 7663, 7667, 7671, 7675, 7679, 7684, 7688, 7692, 7696, 7700, 7704, 7708, 7712, 7717, 7721, 7725, 7729, 7733,
7737, 7741, 7746, 7750, 7754, 7758, 7762, 7766, 7770, 7775, 7779, 7783, 7787, 7791, 7795, 7799, 7803, 7808, 7812, 7816, 7820, 7824, 7828, 7832, 7837, 7841, 7845, 7849, 7853, 7857, 7861,
7866, 7870, 7874, 7878, 7882, 7886, 7890, 7894, 7899, 7903, 7907, 7911, 7915, 7919, 7923, 7928, 7932, 7936, 7940, 7944, 7948, 7952, 7957, 7961, 7965, 7969, 7973, 7977, 7981, 7986, 7990,
7994, 7998, 8002, 8006, 8010, 8015, 8019, 8023, 8027, 8031, 8035, 8039, 8043, 8048, 8052, 8056, 8060, 8064, 8068, 8072, 8077, 8081, 8085, 8089, 8093, 8097, 8101, 8106, 8110, 8114, 8118,
8122, 8126, 8130, 8134, 8139, 8143, 8147, 8151, 8155, 8159, 8163, 8168, 8172, 8176, 8180, 8184, 8188, 8192, 8197, 8201, 8205, 8209, 8213, 8217, 8221, 8226, 8230, 8234, 8238, 8242, 8246,
8250, 8255, 8259, 8263, 8267, 8271, 8275, 8279, 8283, 8288, 8292, 8296, 8300, 8304, 8308, 8312, 8317, 8321, 8325, 8329, 8333, 8337, 8341, 8346, 8350, 8354, 8358, 8362, 8366, 8370, 8375,
8379, 8383, 8387, 8391, 8395, 8399, 8403, 8408, 8412, 8416, 8420, 8424, 8428, 8432, 8437, 8441, 8445, 8449, 8453, 8457, 8461, 8466, 8470, 8474, 8478, 8482, 8486, 8490, 8495, 8499, 8503,
8507, 8511, 8515, 8519, 8524, 8528, 8532, 8536, 8540, 8544, 8548, 8553, 8557, 8561, 8565, 8569, 8573, 8577, 8581, 8586, 8590, 8594, 8598, 8602, 8606, 8610, 8615, 8619, 8623, 8627, 8631,
8635, 8639, 8644, 8648, 8652, 8656, 8660, 8664, 8668, 8673, 8677, 8681, 8685, 8689, 8693, 8697, 8702, 8706, 8710, 8714, 8718, 8722, 8726, 8731, 8735, 8739, 8743, 8747, 8751, 8755, 8760,
8764, 8768, 8772, 8776, 8780, 8784, 8789, 8793, 8797, 8801, 8805, 8809, 8813, 8818, 8822, 8826, 8830, 8834, 8838, 8842, 8846, 8851, 8855, 8859, 8863, 8867, 8871, 8875, 8880, 8884, 8888,
8892, 8896, 8900, 8904, 8909, 8913, 8917, 8921, 8925, 8929, 8933, 8938, 8942, 8946, 8950, 8954, 8958, 8962, 8967, 8971, 8975, 8979, 8983, 8987, 8991, 8996, 9000, 9004, 9008, 9012, 9016,
9020, 9025, 9029, 9033, 9037, 9041, 9045, 9049, 9054, 9058, 9062, 9066, 9070, 9074, 9078, 9083, 9087, 9091, 9095, 9099, 9103, 9107, 9112, 9116, 9120, 9124, 9128, 9132, 9136, 9141, 9145,
9149, 9153, 9157, 9161, 9165, 9170, 9174, 9178, 9182, 9186, 9190, 9194, 9199, 9203, 9207, 9211, 9215, 9219, 9223, 9228, 9232, 9236, 9240, 9244, 9248, 9252, 9257, 9261, 9265, 9269, 9273,
9277, 9281, 9286, 9290, 9294, 9298, 9302, 9306, 9310, 9315, 9319, 9323, 9327, 9331, 9335, 9339, 9344, 9348, 9352, 9356, 9360, 9364, 9368, 9373, 9377
};
}
}
| |
using System;
using System.Data.Entity.Migrations;
using AssemblyLine.DAL;
using AssemblyLine.DAL.Entities;
namespace AssemblyLine.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
context.Employees.AddOrUpdate(
e => new {e.FirstName, e.LastName},
new Employee
{
FirstName = "Alexey",
LastName = "Melnikov",
Post = "CTO",
Created = DateTime.Now.AddDays(-7)
},
new Employee
{
FirstName = "Brogan",
LastName = "Bembrogan",
Post = "Engineer",
Created = DateTime.Now.AddDays(-2)
},
new Employee
{
FirstName = "Bob",
LastName = "Dilan",
Post = "Engineer",
Created = DateTime.Now.AddDays(-3)
},
new Employee
{
FirstName = "Niko",
LastName = "Williams",
Post = "Engineer",
Created = DateTime.Now.AddDays(-4)
},
new Employee
{
FirstName = "James",
LastName = "Moriarty",
Post = "Engineer",
Created = DateTime.Now.AddDays(-2)
},
new Employee
{
FirstName = "Elon",
LastName = "Musk",
Post = "CEO",
Created = DateTime.Now.AddDays(-7)
}
);
context.Vehicles.AddOrUpdate(
v => v.Name,
new Vehicle {Name = "M1135 nuclear"},
new Vehicle {Name = "MEV"},
new Vehicle {Name = "M1126 infantry carrier vehicle"},
new Vehicle {Name = "M1128 mobile gun system"},
new Vehicle {Name = "M1134 anti-tank "}
);
context.Lines.AddOrUpdate(
l => l.Name,
new Line {Name = "Line 1"},
new Line {Name = "Line 2"},
new Line {Name = "Line 3"},
new Line {Name = "Line 4"},
new Line {Name = "Line 5"},
new Line {Name = "Line 6"},
new Line {Name = "Line 7"},
new Line {Name = "Line 8"},
new Line {Name = "Line 9"},
new Line {Name = "Line 10"}
);
context.ProductionCycles.AddOrUpdate(
c => c.Id,
new ProductionCycle
{
Id = 1,
Milestones = new[]
{
new CycleMilestone
{
Id = 1,
Name = "Planning",
Position = 0,
Tasks =
new[]
{
new MilestoneTask
{
Name = "Resources",
CheckPoints = new[]
{
new TaskPoint {Title = "Allocate Financial Resources", Position = 0},
new TaskPoint {Title = "Allocate Human Resources", Position = 1},
new TaskPoint {Title = "Make Working Scheduler", Position = 2}
}
},
new MilestoneTask
{
Name = "Assembly Line",
CheckPoints = new[]
{
new TaskPoint {Title = "Service Maintenance", Position = 0},
new TaskPoint {Title = "Check & Reapair", Position = 1},
new TaskPoint {Title = "Test Run", Position = 2}
}
},
new MilestoneTask
{
Name = "Assets",
CheckPoints = new[]
{
new TaskPoint {Title = "Allocate Assets", Position = 0},
new TaskPoint {Title = "Buy Assets if Required", Position = 1},
new TaskPoint {Title = "Store and Account Resources", Position = 2}
}
}
}
},
new CycleMilestone
{
Id = 2,
Name = "Manufacturing",
Position = 1,
Tasks =
new[]
{
new MilestoneTask
{
Name = "Vehicle",
CheckPoints = new[]
{
new TaskPoint {Title = "Produce Parts", Position = 0},
new TaskPoint {Title = "Put Together", Position = 1},
new TaskPoint {Title = "Smoke Test", Position = 2},
}
},
new MilestoneTask
{
Name = "Body",
CheckPoints = new[]
{
new TaskPoint {Title = "Produce Body", Position = 0},
new TaskPoint {Title = "Put Vehicle", Position = 1},
new TaskPoint {Title = "Add Doors", Position = 2},
new TaskPoint {Title = "Add Interior", Position = 3},
new TaskPoint {Title = "Add Glass", Position = 4}
}
},
new MilestoneTask
{
Name = "Chassis",
CheckPoints = new[]
{
new TaskPoint {Title = "Produce Chassis", Position = 0},
new TaskPoint {Title = "Put to the Body", Position = 1},
new TaskPoint {Title = "Connect with Vehicle", Position = 2},
new TaskPoint {Title = "Test Connection", Position = 3},
new TaskPoint {Title = "Put wheels", Position = 4}
}
}
}
},
new CycleMilestone
{
Id = 3,
Name = "Validating",
Position = 2,
Tasks =
new[]
{
new MilestoneTask
{
Name = "Laboratory Tests",
CheckPoints = new[]
{
new TaskPoint {Title = "Engine Off Test", Position = 0},
new TaskPoint {Title = "Engine Onn Test", Position = 1}
}
},
new MilestoneTask
{
Name = "Test Drive",
CheckPoints = new[]
{
new TaskPoint {Title = "Soft Test", Position = 0},
new TaskPoint {Title = "Normal Test", Position = 1},
new TaskPoint {Title = "Extreme Test", Position = 2}
}
},
new MilestoneTask
{
Name = "Documents",
CheckPoints = new[]
{
new TaskPoint {Title = "Vehicle Registration", Position = 0},
new TaskPoint {Title = "Vehicle Passport", Position = 1}
}
}
}
}
}
}
);
}
}
}
| |
// Copyright Structured Solutions
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using BVSoftware.Bvc5.Core.Catalog;
using BVSoftware.Bvc5.Core.Contacts;
using BVSoftware.Bvc5.Core.Content;
using BVSoftware.Bvc5.Core.Membership;
using BVSoftware.Bvc5.Core.Shipping;
using StructuredSolutions.Bvc5.Shipping.Providers;
using StructuredSolutions.Bvc5.Shipping.Providers.Controls;
using StructuredSolutions.Bvc5.Shipping.Providers.Settings;
using ASPNET = System.Web.UI.WebControls;
using ListItem = System.Web.UI.WebControls.ListItem;
public partial class BVModules_Shipping_Order_Rules_OrderMatchEditor : UserControl
{
#region Properties
public object DataSource
{
get { return ViewState["DataSource"]; }
set { ViewState["DataSource"] = value; }
}
public string Prompt
{
get
{
object value = ViewState["Prompt"];
if (value == null)
return string.Empty;
else
return (string) value;
}
set { ViewState["Prompt"] = value; }
}
public ShippingMethod ShippingMethod
{
get { return ((BVShippingModule) NamingContainer.NamingContainer.NamingContainer.NamingContainer).ShippingMethod; }
}
public string RuleId
{
get
{
object value = ViewState["RuleId"];
if (value == null)
return string.Empty;
else
return (string) value;
}
set { ViewState["RuleId"] = value; }
}
#endregion
#region Event Handlers
protected void LimitItemPropertyField_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null)
{
DropDownList itemPropertyField = (DropDownList) sender;
DropDownList customPropertyField =
(DropDownList) itemPropertyField.NamingContainer.FindControl("LimitCustomPropertyField");
HelpLabel customPropertyLabel =
(HelpLabel) itemPropertyField.NamingContainer.FindControl("LimitCustomPropertyLabel");
Label multiplierLabel = (Label) itemPropertyField.NamingContainer.FindControl("LimitMultiplierLabel");
HelpLabel limitLabel = (HelpLabel) itemPropertyField.NamingContainer.FindControl("LimitLabel");
TextBox limitField = (TextBox) itemPropertyField.NamingContainer.FindControl("LimitField");
BaseValidator limitRequired = (BaseValidator) itemPropertyField.NamingContainer.FindControl("LimitRequired");
BaseValidator limitNumeric = (BaseValidator) itemPropertyField.NamingContainer.FindControl("LimitNumeric");
ItemProperties itemProperty =
(ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue);
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, itemProperty);
}
}
protected void LimitOrderPropertyField_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null)
{
DropDownList orderPropertyField = (DropDownList) sender;
DropDownList itemPropertyField =
(DropDownList) orderPropertyField.NamingContainer.FindControl("LimitItemPropertyField");
DropDownList packagePropertyField =
(DropDownList) orderPropertyField.NamingContainer.FindControl("LimitPackagePropertyField");
DropDownList customPropertyField =
(DropDownList) orderPropertyField.NamingContainer.FindControl("LimitCustomPropertyField");
HelpLabel customPropertyLabel =
(HelpLabel) orderPropertyField.NamingContainer.FindControl("LimitCustomPropertyLabel");
Label multiplierLabel = (Label) orderPropertyField.NamingContainer.FindControl("LimitMultiplierLabel");
HelpLabel limitLabel = (HelpLabel) orderPropertyField.NamingContainer.FindControl("LimitLabel");
TextBox limitField = (TextBox) orderPropertyField.NamingContainer.FindControl("LimitField");
BaseValidator limitRequired =
(BaseValidator) orderPropertyField.NamingContainer.FindControl("LimitRequired");
BaseValidator limitNumeric = (BaseValidator) orderPropertyField.NamingContainer.FindControl("LimitNumeric");
OrderProperties orderProperty =
(OrderProperties) Enum.Parse(typeof (OrderProperties), orderPropertyField.SelectedValue);
ItemProperties itemProperty =
(ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue);
PackageProperties packageProperty =
(PackageProperties) Enum.Parse(typeof (PackageProperties), packagePropertyField.SelectedValue);
if (orderProperty == OrderProperties.ItemProperty)
{
itemPropertyField.Visible = true;
packagePropertyField.Visible = false;
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, itemProperty);
}
else if (orderProperty == OrderProperties.PackageProperty)
{
itemPropertyField.Visible = false;
packagePropertyField.Visible = true;
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, packageProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, packageProperty);
}
else
{
itemPropertyField.Visible = false;
packagePropertyField.Visible = false;
customPropertyField.Visible = false;
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, orderProperty);
Page.Validate("RuleGroup");
if (Page.IsValid)
{
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, orderProperty);
}
}
}
}
protected void LimitPackagePropertyField_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null)
{
DropDownList packagePropertyField = (DropDownList) sender;
DropDownList customPropertyField =
(DropDownList) packagePropertyField.NamingContainer.FindControl("LimitCustomPropertyField");
HelpLabel customPropertyLabel =
(HelpLabel) packagePropertyField.NamingContainer.FindControl("LimitCustomPropertyLabel");
Label multiplierLabel = (Label) packagePropertyField.NamingContainer.FindControl("LimitMultiplierLabel");
HelpLabel limitLabel = (HelpLabel) packagePropertyField.NamingContainer.FindControl("LimitLabel");
TextBox limitField = (TextBox) packagePropertyField.NamingContainer.FindControl("LimitField");
BaseValidator limitRequired =
(BaseValidator) packagePropertyField.NamingContainer.FindControl("LimitRequired");
BaseValidator limitNumeric =
(BaseValidator) packagePropertyField.NamingContainer.FindControl("LimitNumeric");
PackageProperties packageProperty =
(PackageProperties) Enum.Parse(typeof (PackageProperties), packagePropertyField.SelectedValue);
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, packageProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, packageProperty);
}
}
protected void Matches_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "New")
{
OrderMatchList matches = GetMatches();
OrderMatch match = new OrderMatch();
matches.Insert(e.Item.ItemIndex + 1, match);
DataSource = matches;
DataBindChildren();
}
else if (e.CommandName == "Delete")
{
OrderMatchList matches = GetMatches();
matches.RemoveAt(e.Item.ItemIndex);
DataSource = matches;
DataBindChildren();
}
}
protected void Matches_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
OrderMatchList matches = (OrderMatchList) DataSource;
OrderMatch match = matches[e.Item.ItemIndex];
DropDownList orderPropertyList = (DropDownList) e.Item.FindControl("MatchOrderPropertyField");
DropDownList itemPropertyList = (DropDownList) e.Item.FindControl("MatchItemPropertyField");
DropDownList packagePropertyList = (DropDownList) e.Item.FindControl("MatchPackagePropertyField");
DropDownList customPropertyList = (DropDownList) e.Item.FindControl("MatchCustomPropertyField");
DropDownList comparisonList = (DropDownList) e.Item.FindControl("MatchComparisonTypeField");
DropDownList limitOrderPropertyList = (DropDownList) e.Item.FindControl("LimitOrderPropertyField");
DropDownList limitPackagePropertyList = (DropDownList) e.Item.FindControl("LimitPackagePropertyField");
DropDownList limitItemPropertyList = (DropDownList) e.Item.FindControl("LimitItemPropertyField");
DropDownList limitCustomPropertyList = (DropDownList) e.Item.FindControl("LimitCustomPropertyField");
HelpLabel customPropertyLabel = (HelpLabel) e.Item.FindControl("MatchCustomPropertyLabel");
HelpLabel limitCustomPropertyLabel = (HelpLabel) e.Item.FindControl("LimitCustomPropertyLabel");
Label multiplierLabel = (Label) e.Item.FindControl("LimitMultiplierLabel");
HelpLabel limitLabel = (HelpLabel) e.Item.FindControl("LimitLabel");
TextBox limitField = (TextBox) e.Item.FindControl("LimitField");
BaseValidator limitRequired = (BaseValidator) e.Item.FindControl("LimitRequired");
BaseValidator limitNumeric = (BaseValidator) e.Item.FindControl("LimitNumeric");
orderPropertyList.Items.Clear();
orderPropertyList.Items.AddRange(GetMatchOrderProperties());
itemPropertyList.Items.Clear();
itemPropertyList.Items.AddRange(GetItemProperties());
itemPropertyList.Visible = false;
packagePropertyList.Items.Clear();
packagePropertyList.Items.AddRange(GetPackageProperties());
packagePropertyList.Visible = false;
customPropertyList.Visible = false;
if (match.OrderProperty == OrderProperties.ItemProperty)
{
itemPropertyList.Visible = true;
PrepareCustomPropertyField(customPropertyLabel, customPropertyList, match.ItemProperty);
}
else if (match.OrderProperty == OrderProperties.PackageProperty)
{
packagePropertyList.Visible = true;
PrepareCustomPropertyField(customPropertyLabel, customPropertyList, match.PackageProperty);
}
else
{
PrepareCustomPropertyField(customPropertyLabel, customPropertyList, match.OrderProperty);
}
if (customPropertyList.Items.Count == 0)
customPropertyList.Items.Add(new ListItem("", match.CustomProperty));
if (customPropertyList.Items.FindByValue(match.CustomProperty) == null)
match.CustomProperty = customPropertyList.Items[0].Value;
comparisonList.Items.Clear();
comparisonList.Items.AddRange(GetComparisons());
limitOrderPropertyList.Items.Clear();
limitOrderPropertyList.Items.AddRange(GetLimitOrderProperties());
limitItemPropertyList.Items.Clear();
limitItemPropertyList.Items.AddRange(GetItemProperties());
limitItemPropertyList.Visible = false;
limitPackagePropertyList.Items.Clear();
limitPackagePropertyList.Items.AddRange(GetPackageProperties());
limitPackagePropertyList.Visible = false;
limitCustomPropertyList.Visible = false;
multiplierLabel.Visible = match.LimitOrderProperty != OrderProperties.FixedAmountOne;
if (match.LimitOrderProperty == OrderProperties.ItemProperty)
{
limitItemPropertyList.Visible = true;
PrepareCustomPropertyField(limitCustomPropertyLabel, limitCustomPropertyList, match.LimitItemProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric,
match.LimitItemProperty);
}
else if (match.LimitOrderProperty == OrderProperties.PackageProperty)
{
limitPackagePropertyList.Visible = true;
PrepareCustomPropertyField(limitCustomPropertyLabel, limitCustomPropertyList, match.LimitPackageProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric,
match.LimitPackageProperty);
}
else
{
PrepareCustomPropertyField(limitCustomPropertyLabel, limitCustomPropertyList, match.LimitOrderProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric,
match.LimitOrderProperty);
}
if (limitCustomPropertyList.Items.Count == 0)
limitCustomPropertyList.Items.Add(new ListItem("", match.LimitCustomProperty));
if (limitCustomPropertyList.Items.FindByValue(match.LimitCustomProperty) == null)
match.LimitCustomProperty = limitCustomPropertyList.Items[0].Value;
}
}
protected void MatchItemPropertyField_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null)
{
DropDownList itemPropertyField = (DropDownList) sender;
DropDownList customPropertyField =
(DropDownList) itemPropertyField.NamingContainer.FindControl("MatchCustomPropertyField");
HelpLabel customPropertyLabel =
(HelpLabel) itemPropertyField.NamingContainer.FindControl("MatchCustomPropertyLabel");
ItemProperties itemProperty =
(ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue);
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty);
}
}
protected void MatchPackagePropertyField_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null)
{
DropDownList packagePropertyField = (DropDownList) sender;
DropDownList customPropertyField =
(DropDownList) packagePropertyField.NamingContainer.FindControl("MatchCustomPropertyField");
HelpLabel customPropertyLabel =
(HelpLabel) packagePropertyField.NamingContainer.FindControl("MatchCustomPropertyLabel");
PackageProperties packageProperty =
(PackageProperties) Enum.Parse(typeof (PackageProperties), packagePropertyField.SelectedValue);
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, packageProperty);
}
}
protected void MatchOrderPropertyField_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null)
{
DropDownList orderPropertyField = (DropDownList) sender;
DropDownList itemPropertyField =
(DropDownList) orderPropertyField.NamingContainer.FindControl("MatchItemPropertyField");
DropDownList packagePropertyField =
(DropDownList) orderPropertyField.NamingContainer.FindControl("MatchPackagePropertyField");
DropDownList customPropertyField =
(DropDownList) orderPropertyField.NamingContainer.FindControl("MatchCustomPropertyField");
HelpLabel customPropertyLabel =
(HelpLabel) orderPropertyField.NamingContainer.FindControl("MatchCustomPropertyLabel");
OrderProperties orderProperty =
(OrderProperties) Enum.Parse(typeof (OrderProperties), orderPropertyField.SelectedValue);
ItemProperties itemProperty =
(ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue);
PackageProperties packageProperty =
(PackageProperties) Enum.Parse(typeof (PackageProperties), packagePropertyField.SelectedValue);
if (orderProperty == OrderProperties.ItemProperty)
{
itemPropertyField.Visible = true;
packagePropertyField.Visible = false;
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty);
}
else if (orderProperty == OrderProperties.PackageProperty)
{
itemPropertyField.Visible = false;
packagePropertyField.Visible = true;
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, packageProperty);
}
else
{
itemPropertyField.Visible = false;
packagePropertyField.Visible = false;
customPropertyField.Visible = false;
Page.Validate("RuleGroup");
if (Page.IsValid)
{
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, orderProperty);
}
}
}
}
#endregion
#region Methods
private readonly Regex hiddenCustomerProperties =
new Regex("bvin|password|salt|address", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly Regex hiddenItemProperties =
new Regex("FixedAmountOne", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly Regex hiddenLimitOrderProperties =
new Regex("Invisible|PackageProperty", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly Regex hiddenMatchOrderProperties =
new Regex("FixedAmountOne|Invisible|PackageProperty", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly Regex hiddenPackageProperties =
new Regex("FixedAmountOne|Invisible|UseMethod|ItemProperty|Separator0",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly Regex hiddenVendorManufacturerProperties =
new Regex("address|bvin|lastupdated|dropshipemailtemplateid", RegexOptions.IgnoreCase | RegexOptions.Compiled);
protected override void DataBindChildren()
{
Matches.RuleId = RuleId;
Matches.DataSource = DataSource;
base.DataBindChildren();
}
private static ListItem[] GetAddressProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (PropertyInfo property in typeof (Address).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (property.Name.ToLowerInvariant().IndexOf("bvin") == -1)
properties.Add(new ListItem(property.Name, property.Name));
}
properties.Sort(delegate(ListItem item1, ListItem item2) { return string.Compare(item1.Text, item2.Text); });
return properties.ToArray();
}
private static ListItem[] GetComparisons()
{
List<ListItem> comparisons = new List<ListItem>();
foreach (RuleComparisons comparison in Enum.GetValues(typeof(RuleComparisons)))
{
comparisons.Add(new ListItem(RuleComparisonsHelper.GetDisplayName(comparison), comparison.ToString()));
}
return comparisons.ToArray();
}
private ListItem[] GetCustomerProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (
PropertyInfo property in typeof (UserAccount).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (!hiddenCustomerProperties.IsMatch(property.Name))
properties.Add(new ListItem(property.Name, property.Name));
}
properties.Sort(delegate(ListItem item1, ListItem item2) { return string.Compare(item1.Text, item2.Text); });
return properties.ToArray();
}
private ListItem[] GetItemProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (ItemProperties property in Enum.GetValues(typeof (ItemProperties)))
{
if (!hiddenItemProperties.IsMatch(property.ToString()))
{
properties.Add(new ListItem(ItemPropertiesHelper.GetDisplayName(property), property.ToString()));
}
}
return properties.ToArray();
}
public OrderMatchList GetMatches()
{
return Matches.GetMatches();
}
private ListItem[] GetLimitOrderProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (OrderProperties property in Enum.GetValues(typeof (OrderProperties)))
{
if (!hiddenLimitOrderProperties.IsMatch(property.ToString()))
{
properties.Add(new ListItem(OrderPropertiesHelper.GetDisplayName(property), property.ToString()));
}
}
return properties.ToArray();
}
private ListItem[] GetMatchOrderProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (OrderProperties property in Enum.GetValues(typeof (OrderProperties)))
{
if (!hiddenMatchOrderProperties.IsMatch(property.ToString()))
{
properties.Add(new ListItem(OrderPropertiesHelper.GetDisplayName(property), property.ToString()));
}
}
return properties.ToArray();
}
private ListItem[] GetPackageProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (PackageProperties property in Enum.GetValues(typeof (PackageProperties)))
{
if (!hiddenPackageProperties.IsMatch(property.ToString()))
{
properties.Add(new ListItem(PackagePropertiesHelper.GetDisplayName(property), property.ToString()));
}
}
return properties.ToArray();
}
private static ListItem[] GetPropertyTypes()
{
List<ListItem> propertyTypes = new List<ListItem>();
Collection<ProductProperty> properties = ProductProperty.FindAll();
foreach (ProductProperty property in properties)
{
propertyTypes.Add(new ListItem(property.DisplayName, property.Bvin));
}
if (propertyTypes.Count == 0)
{
propertyTypes.Add(new ListItem("- n/a -", string.Empty));
}
return propertyTypes.ToArray();
}
private ListItem[] GetShippingMethods()
{
List<ListItem> methods = new List<ListItem>();
methods.Add(new ListItem("-n/a-", ""));
foreach (ShippingMethod method in ShippingMethod.FindAll())
{
if (String.Compare(method.Bvin, ShippingMethod.Bvin, true) != 0)
{
methods.Add(new ListItem(method.Name, method.Bvin));
}
}
return methods.ToArray();
}
private ListItem[] GetVendorManufacturerProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (
PropertyInfo property in
typeof (VendorManufacturerBase).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (!hiddenVendorManufacturerProperties.IsMatch(property.Name))
properties.Add(new ListItem(property.Name, property.Name));
}
properties.AddRange(GetAddressProperties());
properties.Sort(delegate(ListItem item1, ListItem item2) { return string.Compare(item1.Text, item2.Text); });
return properties.ToArray();
}
private void PrepareCustomPropertyField(WebControl label, ListControl list, ItemProperties property)
{
list.Items.Clear();
if (property == ItemProperties.CustomProperty)
{
label.ToolTip = "<p>Select the custom property to use.</p>";
list.Items.AddRange(GetPropertyTypes());
list.Visible = true;
}
else if (property == ItemProperties.Manufacturer || property == ItemProperties.Vendor)
{
label.ToolTip = string.Format("<p>Select the {0} property to use.</p>", property.ToString().ToLower());
list.Items.AddRange(GetVendorManufacturerProperties());
list.Visible = true;
}
else
{
label.ToolTip = "";
list.Items.Add(new ListItem("n/a", ""));
list.Visible = false;
}
}
private static void PrepareCustomPropertyField(WebControl label, ListControl list, PackageProperties property)
{
list.Items.Clear();
if (property == PackageProperties.DestinationAddress || property == PackageProperties.SourceAddress)
{
label.ToolTip = "<p>Select the address property to use.</p>";
list.Items.AddRange(GetAddressProperties());
list.Visible = true;
}
else
{
label.ToolTip = "";
list.Items.Add(new ListItem("n/a", ""));
list.Visible = false;
}
}
private void PrepareCustomPropertyField(WebControl label, ListControl list, OrderProperties property)
{
list.Items.Clear();
if (property == OrderProperties.BillingAddress || property == OrderProperties.ShippingAddress)
{
label.ToolTip = "<p>Select the address property to use.</p>";
list.Items.AddRange(GetAddressProperties());
list.Visible = true;
}
else if (property == OrderProperties.Customer)
{
label.ToolTip = "<p>Select the customer property to use.</p>";
list.Items.AddRange(GetCustomerProperties());
list.Visible = true;
}
else if (property == OrderProperties.UseMethod)
{
label.ToolTip = "<p>Select the shipping method to use.</p>";
list.Items.AddRange(GetShippingMethods());
list.Visible = true;
}
else
{
label.ToolTip = "";
list.Items.Add(new ListItem("n/a", ""));
list.Visible = false;
}
}
private static void PrepareLimitField(Control multiplier, Label label, Control field, WebControl requiredValidator, WebControl numericValidator, ItemProperties property)
{
PropertyTypes propertyType = ItemPropertiesHelper.GetPropertyType(property);
PrepareLimitField(multiplier, label, field, requiredValidator, numericValidator, propertyType);
}
private static void PrepareLimitField(Control multiplier, Label label, Control field, WebControl requiredValidator, WebControl numericValidator, OrderProperties property)
{
PropertyTypes propertyType = OrderPropertiesHelper.GetPropertyType(property);
PrepareLimitField(multiplier, label, field, requiredValidator, numericValidator, propertyType);
}
private static void PrepareLimitField(Control multiplier, Label label, Control field, WebControl requiredValidator, WebControl numericValidator, PackageProperties property)
{
PropertyTypes propertyType = PackagePropertiesHelper.GetPropertyType(property);
PrepareLimitField(multiplier, label, field, requiredValidator, numericValidator, propertyType);
}
private static void PrepareLimitField(Control multiplier, Label label, Control field, WebControl requiredValidator, WebControl numericValidator, PropertyTypes propertyType)
{
if (propertyType == PropertyTypes.Numeric)
{
multiplier.Visible = true;
field.Visible = true;
label.Text = "Multiplier";
label.ToolTip = "<p>Enter the multiplier.</p>";
requiredValidator.Enabled = true;
numericValidator.Enabled = true;
}
else if (propertyType == PropertyTypes.Fixed)
{
multiplier.Visible = false;
field.Visible = true;
label.Text = "Limit";
label.ToolTip = "<p>Enter the limit used in the comparison.</p>";
requiredValidator.Enabled = false;
numericValidator.Enabled = false;
}
else
{
multiplier.Visible = false;
field.Visible = false;
requiredValidator.Enabled = false;
numericValidator.Enabled = false;
}
}
#endregion
}
| |
//
// ConnectedSeekSlider.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Banshee.Widgets;
using Banshee.MediaEngine;
using Banshee.ServiceStack;
namespace Banshee.Gui.Widgets
{
public enum SeekSliderLayout {
Horizontal,
Vertical
}
public class ConnectedSeekSlider : Alignment
{
private SeekSlider seek_slider;
private StreamPositionLabel stream_position_label;
private Box box;
public ConnectedSeekSlider () : this (SeekSliderLayout.Vertical)
{
}
public ConnectedSeekSlider (SeekSliderLayout layout) : base (0.5f, 0.5f, 1.0f, 0.0f)
{
RightPadding = 10;
LeftPadding = 10;
BuildSeekSlider (layout);
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent,
PlayerEvent.Iterate |
PlayerEvent.Buffering |
PlayerEvent.StartOfStream |
PlayerEvent.StateChange);
ServiceManager.PlayerEngine.TrackIntercept += OnTrackIntercept;
seek_slider.SeekRequested += OnSeekRequested;
// Initialize the display if we're paused since we won't get any
// events or state change until something actually happens (BGO #536564)
if (ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused) {
OnPlayerEngineTick ();
}
}
public void Disconnect ()
{
ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent);
ServiceManager.PlayerEngine.TrackIntercept -= OnTrackIntercept;
seek_slider.SeekRequested -= OnSeekRequested;
base.Dispose ();
}
public StreamPositionLabel StreamPositionLabel {
get { return stream_position_label; }
}
public SeekSlider SeekSlider {
get { return seek_slider; }
}
public int Spacing {
get { return box.Spacing; }
set { box.Spacing = value; }
}
private void BuildSeekSlider (SeekSliderLayout layout)
{
seek_slider = new SeekSlider ();
stream_position_label = new StreamPositionLabel (seek_slider);
if (layout == SeekSliderLayout.Horizontal) {
box = new HBox ();
box.Spacing = 5;
stream_position_label.FormatString = "<b>{0}</b>";
} else {
box = new VBox ();
}
seek_slider.SetSizeRequest (125, -1);
box.PackStart (seek_slider, true, true, 0);
box.PackStart (stream_position_label, false, false, 0);
box.ShowAll ();
Add (box);
}
private bool transitioning = false;
private bool OnTrackIntercept (Banshee.Collection.TrackInfo track)
{
transitioning = true;
return false;
}
private void OnPlayerEvent (PlayerEventArgs args)
{
switch (args.Event) {
case PlayerEvent.Iterate:
OnPlayerEngineTick ();
break;
case PlayerEvent.StartOfStream:
stream_position_label.StreamState = StreamLabelState.Playing;
seek_slider.CanSeek = ServiceManager.PlayerEngine.CanSeek;
break;
case PlayerEvent.Buffering:
PlayerEventBufferingArgs buffering = (PlayerEventBufferingArgs)args;
if (buffering.Progress >= 1.0) {
stream_position_label.StreamState = StreamLabelState.Playing;
break;
}
stream_position_label.StreamState = StreamLabelState.Buffering;
stream_position_label.BufferingProgress = buffering.Progress;
seek_slider.Sensitive = false;
break;
case PlayerEvent.StateChange:
switch (((PlayerEventStateChangeArgs)args).Current) {
case PlayerState.Contacting:
transitioning = false;
stream_position_label.StreamState = StreamLabelState.Contacting;
seek_slider.SetIdle ();
break;
case PlayerState.Loading:
transitioning = false;
if (((PlayerEventStateChangeArgs)args).Previous == PlayerState.Contacting) {
stream_position_label.StreamState = StreamLabelState.Loading;
seek_slider.SetIdle ();
}
break;
case PlayerState.Idle:
seek_slider.CanSeek = false;
if (!transitioning) {
stream_position_label.StreamState = StreamLabelState.Idle;
seek_slider.Duration = 0;
seek_slider.SeekValue = 0;
seek_slider.SetIdle ();
}
break;
default:
transitioning = false;
break;
}
break;
}
}
private void OnPlayerEngineTick ()
{
if (ServiceManager.PlayerEngine == null) {
return;
}
Banshee.Collection.TrackInfo track = ServiceManager.PlayerEngine.CurrentTrack;
stream_position_label.IsLive = track == null ? false : track.IsLive;
seek_slider.Duration = ServiceManager.PlayerEngine.Length;
if (stream_position_label.StreamState != StreamLabelState.Buffering) {
stream_position_label.StreamState = StreamLabelState.Playing;
seek_slider.SeekValue = ServiceManager.PlayerEngine.Position;
}
seek_slider.CanSeek = ServiceManager.PlayerEngine.CanSeek;
}
private void OnSeekRequested (object o, EventArgs args)
{
ServiceManager.PlayerEngine.Position = (uint)seek_slider.Value;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u32 = System.UInt32;
using Pgno = System.UInt32;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
using sqlite3_pcache = Sqlite3.PCache1;
public partial class Sqlite3
{
/*
** 2008 August 05
**
** 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 implements that page cache.
*************************************************************************
** 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
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** A complete page cache is an instance of this structure.
*/
public class PCache
{
public PgHdr pDirty, pDirtyTail; /* List of dirty pages in LRU order */
public PgHdr pSynced; /* Last synced page in dirty page list */
public int nRef; /* Number of referenced pages */
public int nMax; /* Configured cache size */
public int szPage; /* Size of every page in this cache */
public int szExtra; /* Size of extra space for each page */
public bool bPurgeable; /* True if pages are on backing store */
public dxStress xStress; //int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
public object pStress; /* Argument to xStress */
public sqlite3_pcache pCache; /* Pluggable cache module */
public PgHdr pPage1; /* Reference to page 1 */
public void Clear()
{
pDirty = null;
pDirtyTail = null;
pSynced = null;
nRef = 0;
}
};
/*
** Some of the Debug.Assert() macros in this code are too expensive to run
** even during normal debugging. Use them only rarely on long-running
** tests. Enable the expensive asserts using the
** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
*/
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
//# define expensive_assert(X) Debug.Assert(X)
static void expensive_assert( bool x ) { Debug.Assert( x ); }
#else
//# define expensive_assert(X)
#endif
/********************************** Linked List Management ********************/
#if !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT
/*
** Check that the pCache.pSynced variable is set correctly. If it
** is not, either fail an Debug.Assert or return zero. Otherwise, return
** non-zero. This is only used in debugging builds, as follows:
**
** expensive_assert( pcacheCheckSynced(pCache) );
*/
static int pcacheCheckSynced(PCache pCache){
PgHdr p ;
for(p=pCache.pDirtyTail; p!=pCache.pSynced; p=p.pDirtyPrev){
Debug.Assert( p.nRef !=0|| (p.flags&PGHDR_NEED_SYNC) !=0);
}
return (p==null || p.nRef!=0 || (p.flags&PGHDR_NEED_SYNC)==0)?1:0;
}
#endif //* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
/*
** Remove page pPage from the list of dirty pages.
*/
static void pcacheRemoveFromDirtyList( PgHdr pPage )
{
PCache p = pPage.pCache;
Debug.Assert( pPage.pDirtyNext != null || pPage == p.pDirtyTail );
Debug.Assert( pPage.pDirtyPrev != null || pPage == p.pDirty );
/* Update the PCache1.pSynced variable if necessary. */
if ( p.pSynced == pPage )
{
PgHdr pSynced = pPage.pDirtyPrev;
while ( pSynced != null && ( pSynced.flags & PGHDR_NEED_SYNC ) != 0 )
{
pSynced = pSynced.pDirtyPrev;
}
p.pSynced = pSynced;
}
if ( pPage.pDirtyNext != null )
{
pPage.pDirtyNext.pDirtyPrev = pPage.pDirtyPrev;
}
else
{
Debug.Assert( pPage == p.pDirtyTail );
p.pDirtyTail = pPage.pDirtyPrev;
}
if ( pPage.pDirtyPrev != null )
{
pPage.pDirtyPrev.pDirtyNext = pPage.pDirtyNext;
}
else
{
Debug.Assert( pPage == p.pDirty );
p.pDirty = pPage.pDirtyNext;
}
pPage.pDirtyNext = null;
pPage.pDirtyPrev = null;
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(p) );
#endif
}
/*
** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
** pPage).
*/
static void pcacheAddToDirtyList( PgHdr pPage )
{
PCache p = pPage.pCache;
Debug.Assert( pPage.pDirtyNext == null && pPage.pDirtyPrev == null && p.pDirty != pPage );
pPage.pDirtyNext = p.pDirty;
if ( pPage.pDirtyNext != null )
{
Debug.Assert( pPage.pDirtyNext.pDirtyPrev == null );
pPage.pDirtyNext.pDirtyPrev = pPage;
}
p.pDirty = pPage;
if ( null == p.pDirtyTail )
{
p.pDirtyTail = pPage;
}
if ( null == p.pSynced && 0 == ( pPage.flags & PGHDR_NEED_SYNC ) )
{
p.pSynced = pPage;
}
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(p) );
#endif
}
/*
** Wrapper around the pluggable caches xUnpin method. If the cache is
** being used for an in-memory database, this function is a no-op.
*/
static void pcacheUnpin( PgHdr p )
{
PCache pCache = p.pCache;
if ( pCache.bPurgeable )
{
if ( p.pgno == 1 )
{
pCache.pPage1 = null;
}
sqlite3GlobalConfig.pcache.xUnpin( pCache.pCache, p, false );
}
}
/*************************************************** General Interfaces ******
**
** Initialize and shutdown the page cache subsystem. Neither of these
** functions are threadsafe.
*/
static int sqlite3PcacheInitialize()
{
if ( sqlite3GlobalConfig.pcache.xInit == null )
{
/* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
** built-in default page cache is used instead of the application defined
** page cache. */
sqlite3PCacheSetDefault();
}
return sqlite3GlobalConfig.pcache.xInit( sqlite3GlobalConfig.pcache.pArg );
}
static void sqlite3PcacheShutdown()
{
if ( sqlite3GlobalConfig.pcache.xShutdown != null )
{
/* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
sqlite3GlobalConfig.pcache.xShutdown( sqlite3GlobalConfig.pcache.pArg );
}
}
/*
** Return the size in bytes of a PCache object.
*/
static int sqlite3PcacheSize()
{
return 4;
}// sizeof( PCache ); }
/*
** Create a new PCache object. Storage space to hold the object
** has already been allocated and is passed in as the p pointer.
** The caller discovers how much space needs to be allocated by
** calling sqlite3PcacheSize().
*/
static void sqlite3PcacheOpen(
int szPage, /* Size of every page */
int szExtra, /* Extra space associated with each page */
bool bPurgeable, /* True if pages are on backing store */
dxStress xStress,//int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
object pStress, /* Argument to xStress */
PCache p /* Preallocated space for the PCache */
)
{
p.Clear();//memset(p, 0, sizeof(PCache));
p.szPage = szPage;
p.szExtra = szExtra;
p.bPurgeable = bPurgeable;
p.xStress = xStress;
p.pStress = pStress;
p.nMax = 100;
}
/*
** Change the page size for PCache object. The caller must ensure that there
** are no outstanding page references when this function is called.
*/
static void sqlite3PcacheSetPageSize( PCache pCache, int szPage )
{
Debug.Assert( pCache.nRef == 0 && pCache.pDirty == null );
if ( pCache.pCache != null )
{
sqlite3GlobalConfig.pcache.xDestroy( ref pCache.pCache );
pCache.pCache = null;
}
pCache.szPage = szPage;
}
/*
** Try to obtain a page from the cache.
*/
static int sqlite3PcacheFetch(
PCache pCache, /* Obtain the page from this cache */
u32 pgno, /* Page number to obtain */
int createFlag, /* If true, create page if it does not exist already */
ref PgHdr ppPage /* Write the page here */
)
{
PgHdr pPage = null;
int eCreate;
Debug.Assert( pCache != null );
Debug.Assert( createFlag == 1 || createFlag == 0 );
Debug.Assert( pgno > 0 );
/* If the pluggable cache (sqlite3_pcache*) has not been allocated,
** allocate it now.
*/
if ( null == pCache.pCache && createFlag != 0 )
{
sqlite3_pcache p;
int nByte;
nByte = pCache.szPage + pCache.szExtra + 0;// sizeof( PgHdr );
p = sqlite3GlobalConfig.pcache.xCreate( nByte, pCache.bPurgeable );
if ( null == p )
{
return SQLITE_NOMEM;
}
sqlite3GlobalConfig.pcache.xCachesize( p, pCache.nMax );
pCache.pCache = p;
}
eCreate = createFlag * ( 1 + ( ( !pCache.bPurgeable || null == pCache.pDirty ) ? 1 : 0 ) );
if ( pCache.pCache != null )
{
pPage = sqlite3GlobalConfig.pcache.xFetch( pCache.pCache, pgno, eCreate );
}
if ( null == pPage && eCreate == 1 )
{
PgHdr pPg;
/* Find a dirty page to write-out and recycle. First try to find a
** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
** cleared), but if that is not possible settle for any other
** unreferenced dirty page.
*/
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(pCache) );
#endif
for ( pPg = pCache.pSynced;
pPg != null && ( pPg.nRef != 0 || ( pPg.flags & PGHDR_NEED_SYNC ) != 0 );
pPg = pPg.pDirtyPrev
)
;
pCache.pSynced = pPg;
if ( null == pPg )
{
for ( pPg = pCache.pDirtyTail; pPg != null && pPg.nRef != 0; pPg = pPg.pDirtyPrev )
;
}
if ( pPg != null )
{
int rc;
rc = pCache.xStress( pCache.pStress, pPg );
if ( rc != SQLITE_OK && rc != SQLITE_BUSY )
{
return rc;
}
}
pPage = sqlite3GlobalConfig.pcache.xFetch( pCache.pCache, pgno, 2 );
}
if ( pPage != null )
{
if ( null == pPage.pData )
{
// memset(pPage, 0, sizeof(PgHdr));
pPage.pData = sqlite3Malloc( pCache.szPage );// pPage->pData = (void*)&pPage[1];
//pPage->pExtra = (void*)&((char*)pPage->pData)[pCache->szPage];
//memset(pPage->pExtra, 0, pCache->szExtra);
pPage.pCache = pCache;
pPage.pgno = pgno;
}
Debug.Assert( pPage.pCache == pCache );
Debug.Assert( pPage.pgno == pgno );
//assert(pPage->pData == (void*)&pPage[1]);
//assert(pPage->pExtra == (void*)&((char*)&pPage[1])[pCache->szPage]);
if ( 0 == pPage.nRef )
{
pCache.nRef++;
}
pPage.nRef++;
if ( pgno == 1 )
{
pCache.pPage1 = pPage;
}
}
ppPage = pPage;
return ( pPage == null && eCreate != 0 ) ? SQLITE_NOMEM : SQLITE_OK;
}
/*
** Decrement the reference count on a page. If the page is clean and the
** reference count drops to 0, then it is made elible for recycling.
*/
static void sqlite3PcacheRelease( PgHdr p )
{
Debug.Assert( p.nRef > 0 );
p.nRef--;
if ( p.nRef == 0 )
{
PCache pCache = p.pCache;
pCache.nRef--;
if ( ( p.flags & PGHDR_DIRTY ) == 0 )
{
pcacheUnpin( p );
}
else
{
/* Move the page to the head of the dirty list. */
pcacheRemoveFromDirtyList( p );
pcacheAddToDirtyList( p );
}
}
}
/*
** Increase the reference count of a supplied page by 1.
*/
static void sqlite3PcacheRef( PgHdr p )
{
Debug.Assert( p.nRef > 0 );
p.nRef++;
}
/*
** Drop a page from the cache. There must be exactly one reference to the
** page. This function deletes that reference, so after it returns the
** page pointed to by p is invalid.
*/
static void sqlite3PcacheDrop( PgHdr p )
{
PCache pCache;
Debug.Assert( p.nRef == 1 );
if ( ( p.flags & PGHDR_DIRTY ) != 0 )
{
pcacheRemoveFromDirtyList( p );
}
pCache = p.pCache;
pCache.nRef--;
if ( p.pgno == 1 )
{
pCache.pPage1 = null;
}
sqlite3GlobalConfig.pcache.xUnpin( pCache.pCache, p, true );
}
/*
** Make sure the page is marked as dirty. If it isn't dirty already,
** make it so.
*/
static void sqlite3PcacheMakeDirty( PgHdr p )
{
p.flags &= ~PGHDR_DONT_WRITE;
Debug.Assert( p.nRef > 0 );
if ( 0 == ( p.flags & PGHDR_DIRTY ) )
{
p.flags |= PGHDR_DIRTY;
pcacheAddToDirtyList( p );
}
}
/*
** Make sure the page is marked as clean. If it isn't clean already,
** make it so.
*/
static void sqlite3PcacheMakeClean( PgHdr p )
{
if ( ( p.flags & PGHDR_DIRTY ) != 0 )
{
pcacheRemoveFromDirtyList( p );
p.flags &= ~( PGHDR_DIRTY | PGHDR_NEED_SYNC );
if ( p.nRef == 0 )
{
pcacheUnpin( p );
}
}
}
/*
** Make every page in the cache clean.
*/
static void sqlite3PcacheCleanAll( PCache pCache )
{
PgHdr p;
while ( ( p = pCache.pDirty ) != null )
{
sqlite3PcacheMakeClean( p );
}
}
/*
** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
*/
static void sqlite3PcacheClearSyncFlags( PCache pCache )
{
PgHdr p;
for ( p = pCache.pDirty; p != null; p = p.pDirtyNext )
{
p.flags &= ~PGHDR_NEED_SYNC;
}
pCache.pSynced = pCache.pDirtyTail;
}
/*
** Change the page number of page p to newPgno.
*/
static void sqlite3PcacheMove( PgHdr p, Pgno newPgno )
{
PCache pCache = p.pCache;
Debug.Assert( p.nRef > 0 );
Debug.Assert( newPgno > 0 );
sqlite3GlobalConfig.pcache.xRekey( pCache.pCache, p, p.pgno, newPgno );
p.pgno = newPgno;
if ( ( p.flags & PGHDR_DIRTY ) != 0 && ( p.flags & PGHDR_NEED_SYNC ) != 0 )
{
pcacheRemoveFromDirtyList( p );
pcacheAddToDirtyList( p );
}
}
/*
** Drop every cache entry whose page number is greater than "pgno". The
** caller must ensure that there are no outstanding references to any pages
** other than page 1 with a page number greater than pgno.
**
** If there is a reference to page 1 and the pgno parameter passed to this
** function is 0, then the data area associated with page 1 is zeroed, but
** the page object is not dropped.
*/
static void sqlite3PcacheTruncate( PCache pCache, u32 pgno )
{
if ( pCache.pCache != null )
{
PgHdr p;
PgHdr pNext;
for ( p = pCache.pDirty; p != null; p = pNext )
{
pNext = p.pDirtyNext;
/* This routine never gets call with a positive pgno except right
** after sqlite3PcacheCleanAll(). So if there are dirty pages,
** it must be that pgno==0.
*/
Debug.Assert( p.pgno > 0 );
if ( ALWAYS( p.pgno > pgno ) )
{
Debug.Assert( ( p.flags & PGHDR_DIRTY ) != 0 );
sqlite3PcacheMakeClean( p );
}
}
if ( pgno == 0 && pCache.pPage1 != null )
{
// memset( pCache.pPage1.pData, 0, pCache.szPage );
pCache.pPage1.pData = sqlite3Malloc( pCache.szPage );
pgno = 1;
}
sqlite3GlobalConfig.pcache.xTruncate( pCache.pCache, pgno + 1 );
}
}
/*
** Close a cache.
*/
static void sqlite3PcacheClose( PCache pCache )
{
if ( pCache.pCache != null )
{
sqlite3GlobalConfig.pcache.xDestroy( ref pCache.pCache );
}
}
/*
** Discard the contents of the cache.
*/
static void sqlite3PcacheClear( PCache pCache )
{
sqlite3PcacheTruncate( pCache, 0 );
}
/*
** Merge two lists of pages connected by pDirty and in pgno order.
** Do not both fixing the pDirtyPrev pointers.
*/
static PgHdr pcacheMergeDirtyList( PgHdr pA, PgHdr pB )
{
PgHdr result = new PgHdr();
PgHdr pTail = result;
while ( pA != null && pB != null )
{
if ( pA.pgno < pB.pgno )
{
pTail.pDirty = pA;
pTail = pA;
pA = pA.pDirty;
}
else
{
pTail.pDirty = pB;
pTail = pB;
pB = pB.pDirty;
}
}
if ( pA != null )
{
pTail.pDirty = pA;
}
else if ( pB != null )
{
pTail.pDirty = pB;
}
else
{
pTail.pDirty = null;
}
return result.pDirty;
}
/*
** Sort the list of pages in accending order by pgno. Pages are
** connected by pDirty pointers. The pDirtyPrev pointers are
** corrupted by this sort.
**
** Since there cannot be more than 2^31 distinct pages in a database,
** there cannot be more than 31 buckets required by the merge sorter.
** One extra bucket is added to catch overflow in case something
** ever changes to make the previous sentence incorrect.
*/
//#define N_SORT_BUCKET 32
const int N_SORT_BUCKET = 32;
static PgHdr pcacheSortDirtyList( PgHdr pIn )
{
PgHdr[] a;
PgHdr p;//a[N_SORT_BUCKET], p;
int i;
a = new PgHdr[N_SORT_BUCKET];//memset(a, 0, sizeof(a));
while ( pIn != null )
{
p = pIn;
pIn = p.pDirty;
p.pDirty = null;
for ( i = 0; ALWAYS( i < N_SORT_BUCKET - 1 ); i++ )
{
if ( a[i] == null )
{
a[i] = p;
break;
}
else
{
p = pcacheMergeDirtyList( a[i], p );
a[i] = null;
}
}
if ( NEVER( i == N_SORT_BUCKET - 1 ) )
{
/* To get here, there need to be 2^(N_SORT_BUCKET) elements in
** the input list. But that is impossible.
*/
a[i] = pcacheMergeDirtyList( a[i], p );
}
}
p = a[0];
for ( i = 1; i < N_SORT_BUCKET; i++ )
{
p = pcacheMergeDirtyList( p, a[i] );
}
return p;
}
/*
** Return a list of all dirty pages in the cache, sorted by page number.
*/
static PgHdr sqlite3PcacheDirtyList( PCache pCache )
{
PgHdr p;
for ( p = pCache.pDirty; p != null; p = p.pDirtyNext )
{
p.pDirty = p.pDirtyNext;
}
return pcacheSortDirtyList( pCache.pDirty );
}
/*
** Return the total number of referenced pages held by the cache.
*/
static int sqlite3PcacheRefCount( PCache pCache )
{
return pCache.nRef;
}
/*
** Return the number of references to the page supplied as an argument.
*/
static int sqlite3PcachePageRefcount( PgHdr p )
{
return p.nRef;
}
/*
** Return the total number of pages in the cache.
*/
static int sqlite3PcachePagecount( PCache pCache )
{
int nPage = 0;
if ( pCache.pCache != null )
{
nPage = sqlite3GlobalConfig.pcache.xPagecount( pCache.pCache );
}
return nPage;
}
#if SQLITE_TEST
/*
** Get the suggested cache-size value.
*/
static int sqlite3PcacheGetCachesize( PCache pCache )
{
return pCache.nMax;
}
#endif
/*
** Set the suggested cache-size value.
*/
static void sqlite3PcacheSetCachesize( PCache pCache, int mxPage )
{
pCache.nMax = mxPage;
if ( pCache.pCache != null )
{
sqlite3GlobalConfig.pcache.xCachesize( pCache.pCache, mxPage );
}
}
#if SQLITE_CHECK_PAGES || (SQLITE_DEBUG)
/*
** For all dirty pages currently in the cache, invoke the specified
** callback. This is only used if the SQLITE_CHECK_PAGES macro is
** defined.
*/
static void sqlite3PcacheIterateDirty( PCache pCache, dxIter xIter )
{
PgHdr pDirty;
for ( pDirty = pCache.pDirty; pDirty != null; pDirty = pDirty.pDirtyNext )
{
xIter( pDirty );
}
}
#endif
}
}
| |
namespace StripeTests
{
using Newtonsoft.Json;
using Stripe;
using Stripe.Infrastructure;
using Xunit;
public class StripeEntityTest : BaseStripeTest
{
public StripeEntityTest(
StripeMockFixture stripeMockFixture)
: base(stripeMockFixture)
{
}
[Fact]
public void FromJsonAuto()
{
var json = "{\"id\": \"ch_123\", \"object\": \"charge\"}";
var o = StripeEntity.FromJson(json);
Assert.NotNull(o);
Assert.IsType<Charge>(o);
Assert.Equal("ch_123", ((Charge)o).Id);
}
[Fact]
public void FromJsonAutoUnknownObject()
{
var json = "{\"id\": \"ch_123\", \"object\": \"foo\"}";
var o = StripeEntity.FromJson(json);
Assert.Null(o);
}
[Fact]
public void FromJsonAutoNoObject()
{
var json = "{\"id\": \"ch_123\"}";
var o = StripeEntity.FromJson(json);
Assert.Null(o);
}
[Fact]
public void FromJsonOnType()
{
var json = "{\"integer\": 234, \"string\": \"String!\"}";
var o = TestEntity.FromJson(json);
Assert.NotNull(o);
Assert.Equal(234, o.Integer);
Assert.Equal("String!", o.String);
}
[Fact]
public void FromJsonGeneric()
{
var json = "{\"integer\": 234, \"string\": \"String!\"}";
var o = StripeEntity.FromJson<TestEntity>(json);
Assert.NotNull(o);
Assert.Equal(234, o.Integer);
Assert.Equal("String!", o.String);
}
[Fact]
public void ToJson()
{
var o = new TestEntity
{
Integer = 234,
String = "String!",
};
var json = o.ToJson().Replace("\r\n", "\n");
var expectedJson = "{\n \"integer\": 234,\n \"string\": \"String!\",\n \"nested\": null\n}";
Assert.Equal(expectedJson, json);
}
[Fact]
public void ExpandableAccessors_Id()
{
var o = new TestEntity
{
NestedId = "id_unexpanded",
};
Assert.Equal("id_unexpanded", o.NestedId);
Assert.Null(o.Nested);
}
[Fact]
public void ExpandableAccessors_ExpandedObject()
{
var o = new TestEntity
{
Nested = new TestNestedEntity { Id = "id_expanded", Bar = 42 },
};
Assert.Equal("id_expanded", o.NestedId);
Assert.NotNull(o.Nested);
Assert.Equal("id_expanded", o.Nested.Id);
Assert.Equal(42, o.Nested.Bar);
}
[Fact]
public void ExpandableAccessors_Null()
{
var o = new TestEntity();
Assert.Null(o.NestedId);
Assert.Null(o.Nested);
}
[Fact]
public void ExpandableAccessors_Id_ResetsExistingExpandedObjectIfIdIsDifferent()
{
var o = new TestEntity
{
Nested = new TestNestedEntity { Id = "id_expanded", Bar = 42 },
};
o.NestedId = "id_new";
Assert.Equal("id_new", o.NestedId);
Assert.Null(o.Nested);
}
[Fact]
public void ExpandableAccessors_Id_DoesNotResetExistingExpandedObjectIfIdIsSame()
{
var o = new TestEntity
{
Nested = new TestNestedEntity { Id = "id_expanded", Bar = 42 },
};
o.NestedId = "id_expanded";
Assert.Equal("id_expanded", o.NestedId);
Assert.NotNull(o.Nested);
Assert.Equal("id_expanded", o.Nested.Id);
Assert.Equal(42, o.Nested.Bar);
}
[Fact]
public void RawJObject()
{
var service = new SubscriptionService(this.StripeClient);
var subscription = service.Get("sub_123");
Assert.NotNull(subscription);
// Access `id`, a string element
Assert.Equal(subscription.Id, subscription.RawJObject["id"]);
// Access `created`, a number element
Assert.Equal(subscription.Created, subscription.RawJObject["created"]);
// Access `items[data][0][id]`, a deeply nested string element
Assert.Equal(
subscription.Items.Data[0].Id,
subscription.RawJObject["items"]["data"][0]["id"]);
}
private class TestEntity : StripeEntity<TestEntity>
{
[JsonProperty("integer")]
public int Integer { get; set; }
[JsonProperty("string")]
public string String { get; set; }
[JsonIgnore]
public string NestedId
{
get => this.InternalNested?.Id;
set => this.InternalNested = SetExpandableFieldId(value, this.InternalNested);
}
[JsonIgnore]
public TestNestedEntity Nested
{
get => this.InternalNested?.ExpandedObject;
set => this.InternalNested = SetExpandableFieldObject(value, this.InternalNested);
}
[JsonProperty("nested")]
[JsonConverter(typeof(ExpandableFieldConverter<TestNestedEntity>))]
internal ExpandableField<TestNestedEntity> InternalNested { get; set; }
}
private class TestNestedEntity : StripeEntity<TestNestedEntity>, IHasId
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("bar")]
public int Bar { get; set; }
}
}
}
| |
// <copyright file=Scene.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:26:00 PM</date>
using HciLab.Utilities;
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Windows.Forms;
namespace motionEAPAdmin.Scene
{
/// <summary>
/// This class represents a whole scene.
/// A scene is a collection of multiple sceneitems and their assembly
/// </summary>
///
///
[Serializable()]
public class Scene : SceneItem, ISerializable
{
private int m_SerVersion = 1;
private int m_LastSelectedItemIndex = -1;
private CollectionWithItemNotify<SceneItem> m_Items = new CollectionWithItemNotify<SceneItem>();
[Browsable(false)]
public delegate void EditItemChangedHandler(SceneItem item);
[Browsable(false)]
public event EditItemChangedHandler EditItemChanged;
public Scene()
: base(0, 0, 1, 1, 0, 0, 0, 1)
{
init();
}
protected Scene(SerializationInfo pInfo, StreamingContext context)
: base(pInfo, context)
{
int pSerVersion = pInfo.GetInt32("m_SerVersion");
if (pSerVersion < 1)
return;
m_Items = (CollectionWithItemNotify<SceneItem>)pInfo.GetValue("m_Items", typeof(CollectionWithItemNotify<SceneItem>));
init();
}
public static Scene GetFromClipboard()
{
Scene scene = null;
String jsonString = "";
IDataObject dataObject = Clipboard.GetDataObject();
string format = typeof(Scene).FullName;
if (dataObject.GetDataPresent(format))
{
jsonString = dataObject.GetData(format) as String;
UtilitiesIO.GetObjectFromJsonString<Scene>(ref scene, jsonString);
}
scene.Id = new Scene().Id;
return scene;
}
void m_Items_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyPropertyChanged("ItemsChanged");
}
public new void GetObjectData(SerializationInfo pInfo, StreamingContext pContext)
{
base.GetObjectData(pInfo, pContext);
pInfo.AddValue("m_SerVersion", m_SerVersion);
pInfo.AddValue("m_Items", m_Items);
reconstrctDrawable();
}
private void init()
{
m_Items.CollectionChanged += m_Items_CollectionChanged;
reconstrctDrawable();
}
void m_Items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
NotifyPropertyChanged("Items_CollectionChanged");
}
protected override void reconstrctDrawable()
{
this.Visual3DModel = null;
isFlashing();
}
/// <summary>
/// Add SceneItem to List
/// </summary>
/// <param name="item"></param>
public void Add(SceneItem item)
{
m_Items.Add(item);
NotifyPropertyChanged();
}
/// <summary>
/// removes the given item from being rendered
/// </summary>
/// <param name="pItem">item to be removed</param>
///
public void Remove(SceneItem pItem)
{
m_Items.Remove(pItem);
NotifyPropertyChanged("Remove");
}
public override string Name
{
get
{
return "Scene " + this.Id;
}
}
public void Clear()
{
m_Items.Clear();
NotifyPropertyChanged("Clear");
}
public delegate void SelectedItemChangedHandler(object pSource, SceneItem pScene);
public event SelectedItemChangedHandler selectedItemChanged;
public void OnSelectedItemChanged(object pSource, SceneItem pScene)
{
if (this.selectedItemChanged != null)
selectedItemChanged(pSource, pScene);
}
#region getter / setter
[Browsable(false)]
public CollectionWithItemNotify<SceneItem> Items
{
get { return m_Items; }
set
{
m_Items = value;
NotifyPropertyChanged("Items");
}
}
static readonly object _SelectedItemIndexLock = new object();
public SceneItem SelectedItem
{
get {
lock (_SelectedItemIndexLock)
{
if (m_LastSelectedItemIndex >= 0 && m_LastSelectedItemIndex < Items.Count)
{
return Items[m_LastSelectedItemIndex];
}
else
{
return null;
}
}
}
set
{
int i = Items.IndexOf(value);
SelectedItemIndex = i;
}
}
public int SelectedItemIndex
{
get { return m_LastSelectedItemIndex; }
set
{
lock (_SelectedItemIndexLock)
{
m_LastSelectedItemIndex = value;
OnSelectedItemChanged(this, SelectedItem);
NotifyPropertyChanged("EditItem");
}
}
}
#endregion
internal void setShown(bool p_shown)
{
foreach (SceneItem item in m_Items)
{
item.IsShown = p_shown;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
namespace System.Data.Common
{
public abstract class DbDataReader :
IDisposable,
IEnumerable
{
protected DbDataReader() : base()
{
}
abstract public int Depth
{
get;
}
abstract public int FieldCount
{
get;
}
abstract public bool HasRows
{
get;
}
abstract public bool IsClosed
{
get;
}
abstract public int RecordsAffected
{
get;
}
virtual public int VisibleFieldCount
{
get
{
return FieldCount;
}
}
abstract public object this[int ordinal]
{
get;
}
abstract public object this[string name]
{
get;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
}
}
abstract public string GetDataTypeName(int ordinal);
abstract public IEnumerator GetEnumerator();
abstract public Type GetFieldType(int ordinal);
abstract public string GetName(int ordinal);
abstract public int GetOrdinal(string name);
abstract public bool GetBoolean(int ordinal);
abstract public byte GetByte(int ordinal);
abstract public long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length);
abstract public char GetChar(int ordinal);
abstract public long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length);
public DbDataReader GetData(int ordinal)
{
return GetDbDataReader(ordinal);
}
virtual protected DbDataReader GetDbDataReader(int ordinal)
{
throw ADP.NotSupported();
}
abstract public DateTime GetDateTime(int ordinal);
abstract public Decimal GetDecimal(int ordinal);
abstract public double GetDouble(int ordinal);
abstract public float GetFloat(int ordinal);
abstract public Guid GetGuid(int ordinal);
abstract public Int16 GetInt16(int ordinal);
abstract public Int32 GetInt32(int ordinal);
abstract public Int64 GetInt64(int ordinal);
virtual public Type GetProviderSpecificFieldType(int ordinal)
{
return GetFieldType(ordinal);
}
virtual public Object GetProviderSpecificValue(int ordinal)
{
return GetValue(ordinal);
}
virtual public int GetProviderSpecificValues(object[] values)
{
return GetValues(values);
}
abstract public String GetString(int ordinal);
virtual public Stream GetStream(int ordinal)
{
using (MemoryStream bufferStream = new MemoryStream())
{
long bytesRead = 0;
long bytesReadTotal = 0;
byte[] buffer = new byte[4096];
do
{
bytesRead = GetBytes(ordinal, bytesReadTotal, buffer, 0, buffer.Length);
bufferStream.Write(buffer, 0, (int)bytesRead);
bytesReadTotal += bytesRead;
} while (bytesRead > 0);
return new MemoryStream(bufferStream.ToArray(), false);
}
}
virtual public TextReader GetTextReader(int ordinal)
{
if (IsDBNull(ordinal))
{
return new StringReader(String.Empty);
}
else
{
return new StringReader(GetString(ordinal));
}
}
abstract public Object GetValue(int ordinal);
virtual public T GetFieldValue<T>(int ordinal)
{
return (T)GetValue(ordinal);
}
public Task<T> GetFieldValueAsync<T>(int ordinal)
{
return GetFieldValueAsync<T>(ordinal, CancellationToken.None);
}
virtual public Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<T>(cancellationToken);
}
else
{
try
{
return Task.FromResult<T>(GetFieldValue<T>(ordinal));
}
catch (Exception e)
{
return Task.FromException<T>(e);
}
}
}
abstract public int GetValues(object[] values);
abstract public bool IsDBNull(int ordinal);
public Task<bool> IsDBNullAsync(int ordinal)
{
return IsDBNullAsync(ordinal, CancellationToken.None);
}
virtual public Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<bool>(cancellationToken);
}
else
{
try
{
return IsDBNull(ordinal) ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
return Task.FromException<bool>(e);
}
}
}
abstract public bool NextResult();
abstract public bool Read();
public Task<bool> ReadAsync()
{
return ReadAsync(CancellationToken.None);
}
virtual public Task<bool> ReadAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<bool>(cancellationToken);
}
else
{
try
{
return Read() ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
return Task.FromException<bool>(e);
}
}
}
public Task<bool> NextResultAsync()
{
return NextResultAsync(CancellationToken.None);
}
virtual public Task<bool> NextResultAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<bool>(cancellationToken);
}
else
{
try
{
return NextResult() ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
return Task.FromException<bool>(e);
}
}
}
}
}
| |
using Lucene.Net.Search;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
namespace Lucene.Net.Util
{
/*
* 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 IndexReader = Lucene.Net.Index.IndexReader;
/// <summary>
/// <para>
/// Provides methods for sanity checking that entries in the FieldCache
/// are not wasteful or inconsistent.
/// </para>
/// <para>
/// Lucene 2.9 Introduced numerous enhancements into how the FieldCache
/// is used by the low levels of Lucene searching (for Sorting and
/// ValueSourceQueries) to improve both the speed for Sorting, as well
/// as reopening of IndexReaders. But these changes have shifted the
/// usage of FieldCache from "top level" IndexReaders (frequently a
/// MultiReader or DirectoryReader) down to the leaf level SegmentReaders.
/// As a result, existing applications that directly access the FieldCache
/// may find RAM usage increase significantly when upgrading to 2.9 or
/// Later. This class provides an API for these applications (or their
/// Unit tests) to check at run time if the FieldCache contains "insane"
/// usages of the FieldCache.
/// </para>
/// @lucene.experimental
/// </summary>
/// <seealso cref="IFieldCache"/>
/// <seealso cref="FieldCacheSanityChecker.Insanity"/>
/// <seealso cref="FieldCacheSanityChecker.InsanityType"/>
public sealed class FieldCacheSanityChecker
{
private bool estimateRam;
public FieldCacheSanityChecker()
{
/* NOOP */
}
/// <param name="estimateRam">If set, estimate size for all <see cref="FieldCache.CacheEntry"/> objects will be calculated.</param>
// LUCENENET specific - added this constructor overload so we wouldn't need a (ridiculous) SetRamUsageEstimator() method
public FieldCacheSanityChecker(bool estimateRam)
{
this.estimateRam = estimateRam;
}
// LUCENENET specific - using constructor overload to replace this method
///// <summary>
///// If set, estimate size for all CacheEntry objects will be calculateed.
///// </summary>
//public bool SetRamUsageEstimator(bool flag)
//{
// estimateRam = flag;
//}
/// <summary>
/// Quick and dirty convenience method </summary>
/// <seealso cref="Check(FieldCache.CacheEntry[])"/>
public static Insanity[] CheckSanity(IFieldCache cache)
{
return CheckSanity(cache.GetCacheEntries());
}
/// <summary>
/// Quick and dirty convenience method that instantiates an instance with
/// "good defaults" and uses it to test the <see cref="FieldCache.CacheEntry"/>s </summary>
/// <seealso cref="Check(FieldCache.CacheEntry[])"/>
public static Insanity[] CheckSanity(params FieldCache.CacheEntry[] cacheEntries)
{
FieldCacheSanityChecker sanityChecker = new FieldCacheSanityChecker(estimateRam: true);
return sanityChecker.Check(cacheEntries);
}
/// <summary>
/// Tests a CacheEntry[] for indication of "insane" cache usage.
/// <para>
/// <b>NOTE:</b>FieldCache CreationPlaceholder objects are ignored.
/// (:TODO: is this a bad idea? are we masking a real problem?)
/// </para>
/// </summary>
public Insanity[] Check(params FieldCache.CacheEntry[] cacheEntries)
{
if (null == cacheEntries || 0 == cacheEntries.Length)
{
return new Insanity[0];
}
if (estimateRam)
{
for (int i = 0; i < cacheEntries.Length; i++)
{
cacheEntries[i].EstimateSize();
}
}
// the indirect mapping lets MapOfSet dedup identical valIds for us
// maps the (valId) identityhashCode of cache values to
// sets of CacheEntry instances
MapOfSets<int, FieldCache.CacheEntry> valIdToItems = new MapOfSets<int, FieldCache.CacheEntry>(new Dictionary<int, ISet<FieldCache.CacheEntry>>(17));
// maps ReaderField keys to Sets of ValueIds
MapOfSets<ReaderField, int> readerFieldToValIds = new MapOfSets<ReaderField, int>(new Dictionary<ReaderField, ISet<int>>(17));
// any keys that we know result in more then one valId
ISet<ReaderField> valMismatchKeys = new HashSet<ReaderField>();
// iterate over all the cacheEntries to get the mappings we'll need
for (int i = 0; i < cacheEntries.Length; i++)
{
FieldCache.CacheEntry item = cacheEntries[i];
object val = item.Value;
// It's OK to have dup entries, where one is eg
// float[] and the other is the Bits (from
// getDocWithField())
if (val is IBits)
{
continue;
}
if (val is Lucene.Net.Search.FieldCache.CreationPlaceholder)
{
continue;
}
ReaderField rf = new ReaderField(item.ReaderKey, item.FieldName);
int valId = RuntimeHelpers.GetHashCode(val);
// indirect mapping, so the MapOfSet will dedup identical valIds for us
valIdToItems.Put(valId, item);
if (1 < readerFieldToValIds.Put(rf, valId))
{
valMismatchKeys.Add(rf);
}
}
List<Insanity> insanity = new List<Insanity>(valMismatchKeys.Count * 3);
insanity.AddRange(CheckValueMismatch(valIdToItems, readerFieldToValIds, valMismatchKeys));
insanity.AddRange(CheckSubreaders(valIdToItems, readerFieldToValIds));
return insanity.ToArray();
}
/// <summary>
/// Internal helper method used by check that iterates over
/// <paramref name="valMismatchKeys"/> and generates a <see cref="ICollection{T}"/> of <see cref="Insanity"/>
/// instances accordingly. The <see cref="MapOfSets{TKey, TValue}"/> are used to populate
/// the <see cref="Insanity"/> objects. </summary>
/// <seealso cref="InsanityType.VALUEMISMATCH"/>
private ICollection<Insanity> CheckValueMismatch(MapOfSets<int, FieldCache.CacheEntry> valIdToItems, MapOfSets<ReaderField, int> readerFieldToValIds, ISet<ReaderField> valMismatchKeys)
{
List<Insanity> insanity = new List<Insanity>(valMismatchKeys.Count * 3);
if (valMismatchKeys.Count != 0)
{
// we have multiple values for some ReaderFields
IDictionary<ReaderField, ISet<int>> rfMap = readerFieldToValIds.Map;
IDictionary<int, ISet<FieldCache.CacheEntry>> valMap = valIdToItems.Map;
foreach (ReaderField rf in valMismatchKeys)
{
IList<FieldCache.CacheEntry> badEntries = new List<FieldCache.CacheEntry>(valMismatchKeys.Count * 2);
foreach (int value in rfMap[rf])
{
foreach (FieldCache.CacheEntry cacheEntry in valMap[value])
{
badEntries.Add(cacheEntry);
}
}
FieldCache.CacheEntry[] badness = new FieldCache.CacheEntry[badEntries.Count];
badEntries.CopyTo(badness, 0);
insanity.Add(new Insanity(InsanityType.VALUEMISMATCH, "Multiple distinct value objects for " + rf.ToString(), badness));
}
}
return insanity;
}
/// <summary>
/// Internal helper method used by check that iterates over
/// the keys of <paramref name="readerFieldToValIds"/> and generates a <see cref="ICollection{T}"/>
/// of <see cref="Insanity"/> instances whenever two (or more) <see cref="ReaderField"/> instances are
/// found that have an ancestry relationships.
/// </summary>
/// <seealso cref="InsanityType.SUBREADER"/>
private ICollection<Insanity> CheckSubreaders(MapOfSets<int, FieldCache.CacheEntry> valIdToItems, MapOfSets<ReaderField, int> readerFieldToValIds)
{
List<Insanity> insanity = new List<Insanity>(23);
Dictionary<ReaderField, ISet<ReaderField>> badChildren = new Dictionary<ReaderField, ISet<ReaderField>>(17);
MapOfSets<ReaderField, ReaderField> badKids = new MapOfSets<ReaderField, ReaderField>(badChildren); // wrapper
IDictionary<int, ISet<FieldCache.CacheEntry>> viToItemSets = valIdToItems.Map;
IDictionary<ReaderField, ISet<int>> rfToValIdSets = readerFieldToValIds.Map;
HashSet<ReaderField> seen = new HashSet<ReaderField>();
//IDictionary<ReaderField, ISet<int>>.KeyCollection readerFields = rfToValIdSets.Keys;
foreach (ReaderField rf in rfToValIdSets.Keys)
{
if (seen.Contains(rf))
{
continue;
}
IList<object> kids = GetAllDescendantReaderKeys(rf.ReaderKey);
foreach (object kidKey in kids)
{
ReaderField kid = new ReaderField(kidKey, rf.FieldName);
if (badChildren.ContainsKey(kid))
{
// we've already process this kid as RF and found other problems
// track those problems as our own
badKids.Put(rf, kid);
badKids.PutAll(rf, badChildren[kid]);
badChildren.Remove(kid);
}
else if (rfToValIdSets.ContainsKey(kid))
{
// we have cache entries for the kid
badKids.Put(rf, kid);
}
seen.Add(kid);
}
seen.Add(rf);
}
// every mapping in badKids represents an Insanity
foreach (ReaderField parent in badChildren.Keys)
{
ISet<ReaderField> kids = badChildren[parent];
List<FieldCache.CacheEntry> badEntries = new List<FieldCache.CacheEntry>(kids.Count * 2);
// put parent entr(ies) in first
{
foreach (int value in rfToValIdSets[parent])
{
badEntries.AddRange(viToItemSets[value]);
}
}
// now the entries for the descendants
foreach (ReaderField kid in kids)
{
foreach (int value in rfToValIdSets[kid])
{
badEntries.AddRange(viToItemSets[value]);
}
}
FieldCache.CacheEntry[] badness = badEntries.ToArray();
insanity.Add(new Insanity(InsanityType.SUBREADER, "Found caches for descendants of " + parent.ToString(), badness));
}
return insanity;
}
/// <summary>
/// Checks if the <paramref name="seed"/> is an <see cref="IndexReader"/>, and if so will walk
/// the hierarchy of subReaders building up a list of the objects
/// returned by <c>seed.CoreCacheKey</c>
/// </summary>
private IList<object> GetAllDescendantReaderKeys(object seed)
{
var all = new List<object>(17) {seed}; // will grow as we iter
for (var i = 0; i < all.Count; i++)
{
var obj = all[i];
// TODO: We don't check closed readers here (as getTopReaderContext
// throws ObjectDisposedException), what should we do? Reflection?
var reader = obj as IndexReader;
if (reader != null)
{
try
{
var childs = reader.Context.Children;
if (childs != null) // it is composite reader
{
foreach (var ctx in childs)
{
all.Add(ctx.Reader.CoreCacheKey);
}
}
}
catch (System.ObjectDisposedException)
{
// ignore this reader
}
}
}
// need to skip the first, because it was the seed
return all.GetRange(1, all.Count - 1);
}
/// <summary>
/// Simple pair object for using "readerKey + fieldName" a Map key
/// </summary>
private sealed class ReaderField
{
public object ReaderKey
{
get { return readerKey; }
}
private readonly object readerKey;
public string FieldName { get; private set; }
public ReaderField(object readerKey, string fieldName)
{
this.readerKey = readerKey;
this.FieldName = fieldName;
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(readerKey) * FieldName.GetHashCode();
}
public override bool Equals(object that)
{
if (!(that is ReaderField))
{
return false;
}
ReaderField other = (ReaderField)that;
return (object.ReferenceEquals(this.readerKey, other.readerKey)
&& this.FieldName.Equals(other.FieldName, StringComparison.Ordinal));
}
public override string ToString()
{
return readerKey.ToString() + "+" + FieldName;
}
}
/// <summary>
/// Simple container for a collection of related <see cref="FieldCache.CacheEntry"/> objects that
/// in conjunction with each other represent some "insane" usage of the
/// <see cref="IFieldCache"/>.
/// </summary>
public sealed class Insanity
{
private readonly InsanityType type;
private readonly string msg;
private readonly FieldCache.CacheEntry[] entries;
public Insanity(InsanityType type, string msg, params FieldCache.CacheEntry[] entries)
{
if (null == type)
{
throw new System.ArgumentException("Insanity requires non-null InsanityType");
}
if (null == entries || 0 == entries.Length)
{
throw new System.ArgumentException("Insanity requires non-null/non-empty CacheEntry[]");
}
this.type = type;
this.msg = msg;
this.entries = entries;
}
/// <summary>
/// Type of insane behavior this object represents
/// </summary>
public InsanityType Type
{
get
{
return type;
}
}
/// <summary>
/// Description of the insane behavior
/// </summary>
public string Msg
{
get
{
return msg;
}
}
/// <summary>
/// <see cref="FieldCache.CacheEntry"/> objects which suggest a problem
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public FieldCache.CacheEntry[] CacheEntries
{
get { return entries; }
}
/// <summary>
/// Multi-Line representation of this <see cref="Insanity"/> object, starting with
/// the Type and Msg, followed by each CacheEntry.ToString() on it's
/// own line prefaced by a tab character
/// </summary>
public override string ToString()
{
StringBuilder buf = new StringBuilder();
buf.Append(Type).Append(": ");
string m = Msg;
if (null != m)
{
buf.Append(m);
}
buf.Append('\n');
FieldCache.CacheEntry[] ce = CacheEntries;
for (int i = 0; i < ce.Length; i++)
{
buf.Append('\t').Append(ce[i].ToString()).Append('\n');
}
return buf.ToString();
}
}
/// <summary>
/// An Enumeration of the different types of "insane" behavior that
/// may be detected in a <see cref="IFieldCache"/>.
/// </summary>
/// <seealso cref="InsanityType.SUBREADER"/>
/// <seealso cref="InsanityType.VALUEMISMATCH"/>
/// <seealso cref="InsanityType.EXPECTED"/>
public sealed class InsanityType
{
private readonly string label;
private InsanityType(string label)
{
this.label = label;
}
public override string ToString()
{
return label;
}
/// <summary>
/// Indicates an overlap in cache usage on a given field
/// in sub/super readers.
/// </summary>
public static readonly InsanityType SUBREADER = new InsanityType("SUBREADER");
/// <summary>
/// <para>
/// Indicates entries have the same reader+fieldname but
/// different cached values. This can happen if different datatypes,
/// or parsers are used -- and while it's not necessarily a bug
/// it's typically an indication of a possible problem.
/// </para>
/// <para>
/// <b>NOTE:</b> Only the reader, fieldname, and cached value are actually
/// tested -- if two cache entries have different parsers or datatypes but
/// the cached values are the same Object (== not just Equal()) this method
/// does not consider that a red flag. This allows for subtle variations
/// in the way a Parser is specified (null vs DEFAULT_INT64_PARSER, etc...)
/// </para>
/// </summary>
public static readonly InsanityType VALUEMISMATCH = new InsanityType("VALUEMISMATCH");
/// <summary>
/// Indicates an expected bit of "insanity". This may be useful for
/// clients that wish to preserve/log information about insane usage
/// but indicate that it was expected.
/// </summary>
public static readonly InsanityType EXPECTED = new InsanityType("EXPECTED");
}
}
}
| |
// 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.Text;
namespace System.Globalization
{
//
// Property Default Description
// PositiveSign '+' Character used to indicate positive values.
// NegativeSign '-' Character used to indicate negative values.
// NumberDecimalSeparator '.' The character used as the decimal separator.
// NumberGroupSeparator ',' The character used to separate groups of
// digits to the left of the decimal point.
// NumberDecimalDigits 2 The default number of decimal places.
// NumberGroupSizes 3 The number of digits in each group to the
// left of the decimal point.
// NaNSymbol "NaN" The string used to represent NaN values.
// PositiveInfinitySymbol"Infinity" The string used to represent positive
// infinities.
// NegativeInfinitySymbol"-Infinity" The string used to represent negative
// infinities.
//
//
//
// Property Default Description
// CurrencyDecimalSeparator '.' The character used as the decimal
// separator.
// CurrencyGroupSeparator ',' The character used to separate groups
// of digits to the left of the decimal
// point.
// CurrencyDecimalDigits 2 The default number of decimal places.
// CurrencyGroupSizes 3 The number of digits in each group to
// the left of the decimal point.
// CurrencyPositivePattern 0 The format of positive values.
// CurrencyNegativePattern 0 The format of negative values.
// CurrencySymbol "$" String used as local monetary symbol.
//
sealed public class NumberFormatInfo : IFormatProvider, ICloneable
{
// invariantInfo is constant irrespective of your current culture.
private static volatile NumberFormatInfo s_invariantInfo;
// READTHIS READTHIS READTHIS
// This class has an exact mapping onto a native structure defined in COMNumber.cpp
// DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END.
// ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets.
// READTHIS READTHIS READTHIS
internal int[] numberGroupSizes = new int[] { 3 };
internal int[] currencyGroupSizes = new int[] { 3 };
internal int[] percentGroupSizes = new int[] { 3 };
internal string positiveSign = "+";
internal string negativeSign = "-";
internal string numberDecimalSeparator = ".";
internal string numberGroupSeparator = ",";
internal string currencyGroupSeparator = ",";
internal string currencyDecimalSeparator = ".";
internal string currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund.
internal string nanSymbol = "NaN";
internal string positiveInfinitySymbol = "Infinity";
internal string negativeInfinitySymbol = "-Infinity";
internal string percentDecimalSeparator = ".";
internal string percentGroupSeparator = ",";
internal string percentSymbol = "%";
internal string perMilleSymbol = "\u2030";
internal string[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
internal int numberDecimalDigits = 2;
internal int currencyDecimalDigits = 2;
internal int currencyPositivePattern = 0;
internal int currencyNegativePattern = 0;
internal int numberNegativePattern = 1;
internal int percentPositivePattern = 0;
internal int percentNegativePattern = 0;
internal int percentDecimalDigits = 2;
internal int digitSubstitution = (int)DigitShapes.None;
internal bool isReadOnly = false;
// Is this NumberFormatInfo for invariant culture?
internal bool m_isInvariant = false;
public NumberFormatInfo() : this(null)
{
}
private static void VerifyDecimalSeparator(string decSep, string propertyName)
{
if (decSep == null)
{
throw new ArgumentNullException(propertyName,
SR.ArgumentNull_String);
}
if (decSep.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyDecString);
}
}
private static void VerifyGroupSeparator(string groupSep, string propertyName)
{
if (groupSep == null)
{
throw new ArgumentNullException(propertyName,
SR.ArgumentNull_String);
}
}
private static void VerifyNativeDigits(string[] nativeDig, string propertyName)
{
if (nativeDig == null)
{
throw new ArgumentNullException(propertyName, SR.ArgumentNull_Array);
}
if (nativeDig.Length != 10)
{
throw new ArgumentException(SR.Argument_InvalidNativeDigitCount, propertyName);
}
for (int i = 0; i < nativeDig.Length; i++)
{
if (nativeDig[i] == null)
{
throw new ArgumentNullException(propertyName, SR.ArgumentNull_ArrayValue);
}
if (nativeDig[i].Length != 1)
{
if (nativeDig[i].Length != 2)
{
// Not 1 or 2 UTF-16 code points
throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
}
else if (!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1]))
{
// 2 UTF-6 code points, but not a surrogate pair
throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
}
}
if (CharUnicodeInfo.GetDecimalDigitValue(nativeDig[i], 0) != i &&
CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse)
{
// Not the appropriate digit according to the Unicode data properties
// (Digit 0 must be a 0, etc.).
throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
}
}
}
private static void VerifyDigitSubstitution(DigitShapes digitSub, string propertyName)
{
switch (digitSub)
{
case DigitShapes.Context:
case DigitShapes.None:
case DigitShapes.NativeNational:
// Success.
break;
default:
throw new ArgumentException(SR.Argument_InvalidDigitSubstitution, propertyName);
}
}
internal NumberFormatInfo(CultureData cultureData)
{
if (cultureData != null)
{
// We directly use fields here since these data is coming from data table or Win32, so we
// don't need to verify their values (except for invalid parsing situations).
cultureData.GetNFIValues(this);
if (cultureData.IsInvariantCulture)
{
// For invariant culture
this.m_isInvariant = true;
}
}
}
private void VerifyWritable()
{
if (isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
// Returns a default NumberFormatInfo that will be universally
// supported and constant irrespective of the current culture.
// Used by FromString methods.
//
public static NumberFormatInfo InvariantInfo
{
get
{
if (s_invariantInfo == null)
{
// Lazy create the invariant info. This cannot be done in a .cctor because exceptions can
// be thrown out of a .cctor stack that will need this.
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.m_isInvariant = true;
s_invariantInfo = ReadOnly(nfi);
}
return s_invariantInfo;
}
}
public static NumberFormatInfo GetInstance(IFormatProvider formatProvider)
{
return formatProvider == null ?
CurrentInfo : // Fast path for a null provider
GetProviderNonNull(formatProvider);
NumberFormatInfo GetProviderNonNull(IFormatProvider provider)
{
// Fast path for a regular CultureInfo
if (provider is CultureInfo cultureProvider && !cultureProvider._isInherited)
{
return cultureProvider.numInfo ?? cultureProvider.NumberFormat;
}
return
provider as NumberFormatInfo ?? // Fast path for an NFI
provider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo ??
CurrentInfo;
}
}
public object Clone()
{
NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone();
n.isReadOnly = false;
return n;
}
public int CurrencyDecimalDigits
{
get { return currencyDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
nameof(CurrencyDecimalDigits),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
VerifyWritable();
currencyDecimalDigits = value;
}
}
public string CurrencyDecimalSeparator
{
get { return currencyDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, nameof(CurrencyDecimalSeparator));
currencyDecimalSeparator = value;
}
}
public bool IsReadOnly
{
get
{
return isReadOnly;
}
}
//
// Check the values of the groupSize array.
//
// Every element in the groupSize array should be between 1 and 9
// excpet the last element could be zero.
//
internal static void CheckGroupSize(string propName, int[] groupSize)
{
for (int i = 0; i < groupSize.Length; i++)
{
if (groupSize[i] < 1)
{
if (i == groupSize.Length - 1 && groupSize[i] == 0)
return;
throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
}
else if (groupSize[i] > 9)
{
throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
}
}
}
public int[] CurrencyGroupSizes
{
get
{
return ((int[])currencyGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(CurrencyGroupSizes),
SR.ArgumentNull_Obj);
}
VerifyWritable();
int[] inputSizes = (int[])value.Clone();
CheckGroupSize(nameof(CurrencyGroupSizes), inputSizes);
currencyGroupSizes = inputSizes;
}
}
public int[] NumberGroupSizes
{
get
{
return ((int[])numberGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(NumberGroupSizes),
SR.ArgumentNull_Obj);
}
VerifyWritable();
int[] inputSizes = (int[])value.Clone();
CheckGroupSize(nameof(NumberGroupSizes), inputSizes);
numberGroupSizes = inputSizes;
}
}
public int[] PercentGroupSizes
{
get
{
return ((int[])percentGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(PercentGroupSizes),
SR.ArgumentNull_Obj);
}
VerifyWritable();
int[] inputSizes = (int[])value.Clone();
CheckGroupSize(nameof(PercentGroupSizes), inputSizes);
percentGroupSizes = inputSizes;
}
}
public string CurrencyGroupSeparator
{
get { return currencyGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, nameof(CurrencyGroupSeparator));
currencyGroupSeparator = value;
}
}
public string CurrencySymbol
{
get { return currencySymbol; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(CurrencySymbol),
SR.ArgumentNull_String);
}
VerifyWritable();
currencySymbol = value;
}
}
// Returns the current culture's NumberFormatInfo. Used by Parse methods.
//
public static NumberFormatInfo CurrentInfo
{
get
{
System.Globalization.CultureInfo culture = CultureInfo.CurrentCulture;
if (!culture._isInherited)
{
NumberFormatInfo info = culture.numInfo;
if (info != null)
{
return info;
}
}
return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)));
}
}
public string NaNSymbol
{
get
{
return nanSymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(NaNSymbol),
SR.ArgumentNull_String);
}
VerifyWritable();
nanSymbol = value;
}
}
public int CurrencyNegativePattern
{
get { return currencyNegativePattern; }
set
{
if (value < 0 || value > 15)
{
throw new ArgumentOutOfRangeException(
nameof(CurrencyNegativePattern),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
15));
}
VerifyWritable();
currencyNegativePattern = value;
}
}
public int NumberNegativePattern
{
get { return numberNegativePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 4)
{
throw new ArgumentOutOfRangeException(
nameof(NumberNegativePattern),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
4));
}
VerifyWritable();
numberNegativePattern = value;
}
}
public int PercentPositivePattern
{
get { return percentPositivePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 3)
{
throw new ArgumentOutOfRangeException(
nameof(PercentPositivePattern),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
3));
}
VerifyWritable();
percentPositivePattern = value;
}
}
public int PercentNegativePattern
{
get { return percentNegativePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 11)
{
throw new ArgumentOutOfRangeException(
nameof(PercentNegativePattern),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
11));
}
VerifyWritable();
percentNegativePattern = value;
}
}
public string NegativeInfinitySymbol
{
get
{
return negativeInfinitySymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(NegativeInfinitySymbol),
SR.ArgumentNull_String);
}
VerifyWritable();
negativeInfinitySymbol = value;
}
}
public string NegativeSign
{
get { return negativeSign; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(NegativeSign),
SR.ArgumentNull_String);
}
VerifyWritable();
negativeSign = value;
}
}
public int NumberDecimalDigits
{
get { return numberDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
nameof(NumberDecimalDigits),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
VerifyWritable();
numberDecimalDigits = value;
}
}
public string NumberDecimalSeparator
{
get { return numberDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, nameof(NumberDecimalSeparator));
numberDecimalSeparator = value;
}
}
public string NumberGroupSeparator
{
get { return numberGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, nameof(NumberGroupSeparator));
numberGroupSeparator = value;
}
}
public int CurrencyPositivePattern
{
get { return currencyPositivePattern; }
set
{
if (value < 0 || value > 3)
{
throw new ArgumentOutOfRangeException(
nameof(CurrencyPositivePattern),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
3));
}
VerifyWritable();
currencyPositivePattern = value;
}
}
public string PositiveInfinitySymbol
{
get
{
return positiveInfinitySymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(PositiveInfinitySymbol),
SR.ArgumentNull_String);
}
VerifyWritable();
positiveInfinitySymbol = value;
}
}
public string PositiveSign
{
get { return positiveSign; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(PositiveSign),
SR.ArgumentNull_String);
}
VerifyWritable();
positiveSign = value;
}
}
public int PercentDecimalDigits
{
get { return percentDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
nameof(PercentDecimalDigits),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
VerifyWritable();
percentDecimalDigits = value;
}
}
public string PercentDecimalSeparator
{
get { return percentDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, nameof(PercentDecimalSeparator));
percentDecimalSeparator = value;
}
}
public string PercentGroupSeparator
{
get { return percentGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, nameof(PercentGroupSeparator));
percentGroupSeparator = value;
}
}
public string PercentSymbol
{
get
{
return percentSymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(PercentSymbol),
SR.ArgumentNull_String);
}
VerifyWritable();
percentSymbol = value;
}
}
public string PerMilleSymbol
{
get { return perMilleSymbol; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(PerMilleSymbol),
SR.ArgumentNull_String);
}
VerifyWritable();
perMilleSymbol = value;
}
}
public string[] NativeDigits
{
get { return (string[])nativeDigits.Clone(); }
set
{
VerifyWritable();
VerifyNativeDigits(value, nameof(NativeDigits));
nativeDigits = value;
}
}
public DigitShapes DigitSubstitution
{
get { return (DigitShapes)digitSubstitution; }
set
{
VerifyWritable();
VerifyDigitSubstitution(value, nameof(DigitSubstitution));
digitSubstitution = (int)value;
}
}
public object GetFormat(Type formatType)
{
return formatType == typeof(NumberFormatInfo) ? this : null;
}
public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi)
{
if (nfi == null)
{
throw new ArgumentNullException(nameof(nfi));
}
if (nfi.IsReadOnly)
{
return (nfi);
}
NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone());
info.isReadOnly = true;
return info;
}
// private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00);
private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
internal static void ValidateParseStyleInteger(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
}
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
if ((style & ~NumberStyles.HexNumber) != 0)
{
throw new ArgumentException(SR.Arg_InvalidHexStyle);
}
}
}
internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
}
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
throw new ArgumentException(SR.Arg_HexStyleNotSupported);
}
}
} // NumberFormatInfo
}
| |
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using DeOps.Implementation.Protocol;
namespace DeOps.Services.Storage
{
public class StoragePacket
{
public const byte Root = 0x10;
public const byte Folder = 0x20;
public const byte File = 0x30;
public const byte Pack = 0x40;
}
public class StorageRoot : G2Packet
{
const byte Packet_Project = 0x10;
public uint ProjectID;
public StorageRoot() { }
public StorageRoot(uint project) { ProjectID = project; }
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame root = protocol.WritePacket(null, StoragePacket.Root, null);
protocol.WritePacket(root, Packet_Project, BitConverter.GetBytes(ProjectID));
return protocol.WriteFinish();
}
}
public static StorageRoot Decode(G2Header header)
{
StorageRoot root = new StorageRoot();
G2Header child = new G2Header(header.Data);
while (G2Protocol.ReadNextChild(header, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_Project:
root.ProjectID = BitConverter.ToUInt32(child.Data, child.PayloadPos);
break;
}
}
return root;
}
}
[Flags]
public enum StorageFlags : ushort { None = 0, Archived = 1, Unlocked = 2, Modified = 4 }
[Flags]
public enum StorageActions { None = 0, Created = 1, Modified = 2, Renamed = 4, Deleted = 8, Restored = 16, Scoped = 32 }
public class StorageItem : G2Packet
{
public ulong UID;
public string Name;
public DateTime Date;
public ulong IntegratedID;
public StorageFlags Flags;
public string Note;
public byte Revs;
public Dictionary<ulong, short> Scope = new Dictionary<ulong, short>();
public bool IsFlagged(StorageFlags test)
{
return ((Flags & test) != 0);
}
public void RemoveFlag(StorageFlags remove)
{
Flags = Flags & ~remove;
}
public void SetFlag(StorageFlags set)
{
Flags = Flags | set;
}
}
public class StorageFolder : StorageItem
{
const byte Packet_UID = 0x10;
const byte Packet_ParentUID = 0x20;
const byte Packet_Name = 0x30;
const byte Packet_Date = 0x40;
const byte Packet_Flags = 0x50;
const byte Packet_Note = 0x70;
const byte Packet_Revs = 0x90;
const byte Packet_Integrated = 0xA0;
const byte Packet_Scope = 0xB0;
public ulong ParentUID;
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame folder = protocol.WritePacket(null, StoragePacket.Folder, null);
protocol.WritePacket(folder, Packet_UID, BitConverter.GetBytes(UID));
protocol.WritePacket(folder, Packet_ParentUID, BitConverter.GetBytes(ParentUID));
protocol.WritePacket(folder, Packet_Name, UTF8Encoding.UTF8.GetBytes(Name));
protocol.WritePacket(folder, Packet_Date, BitConverter.GetBytes(Date.ToBinary()));
StorageFlags netFlags = Flags & ~(StorageFlags.Modified | StorageFlags.Unlocked);
protocol.WritePacket(folder, Packet_Flags, BitConverter.GetBytes((ushort)netFlags));
if(Note != null)
protocol.WritePacket(folder, Packet_Note, UTF8Encoding.UTF8.GetBytes(Note));
protocol.WritePacket(folder, Packet_Revs, BitConverter.GetBytes(Revs));
protocol.WritePacket(folder, Packet_Integrated, BitConverter.GetBytes(IntegratedID));
byte[] scopefield = new byte[10];
foreach (ulong id in Scope.Keys)
{
BitConverter.GetBytes(id).CopyTo(scopefield, 0);
BitConverter.GetBytes(Scope[id]).CopyTo(scopefield, 8);
protocol.WritePacket(folder, Packet_Scope, scopefield);
}
return protocol.WriteFinish();
}
}
public static StorageFolder Decode(byte[] data)
{
G2Header root = new G2Header(data);
if (!G2Protocol.ReadPacket(root))
return null;
if (root.Name != StoragePacket.Folder)
return null;
return StorageFolder.Decode(root);
}
public static StorageFolder Decode(G2Header root)
{
StorageFolder folder = new StorageFolder();
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_UID:
folder.UID = BitConverter.ToUInt64(child.Data, child.PayloadPos);
break;
case Packet_ParentUID:
folder.ParentUID = BitConverter.ToUInt64(child.Data, child.PayloadPos);
break;
case Packet_Name:
folder.Name = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Date:
folder.Date = DateTime.FromBinary(BitConverter.ToInt64(child.Data, child.PayloadPos));
break;
case Packet_Flags:
folder.Flags = (StorageFlags) BitConverter.ToUInt16(child.Data, child.PayloadPos);
break;
case Packet_Note:
folder.Note = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Revs:
folder.Revs = child.Data[child.PayloadPos];
break;
case Packet_Integrated:
folder.IntegratedID = BitConverter.ToUInt64(child.Data, child.PayloadPos);
break;
case Packet_Scope:
folder.Scope[BitConverter.ToUInt64(child.Data, child.PayloadPos)] = BitConverter.ToInt16(child.Data, child.PayloadPos + 8);
break;
}
}
return folder;
}
public StorageFolder Clone()
{
// clones everything except notes
StorageFolder clone = new StorageFolder();
clone.ParentUID = ParentUID;
clone.UID = UID;
clone.Name = Name;
clone.Date = Date;
clone.Flags = Flags;
clone.Revs = Revs;
return clone;
}
}
public class StorageFile : StorageItem
{
const byte Packet_UID = 0x10;
const byte Packet_Name = 0x20;
const byte Packet_Date = 0x30;
const byte Packet_Flags = 0x40;
const byte Packet_Note = 0x60;
const byte Packet_Size = 0x70;
const byte Packet_Hash = 0x80;
const byte Packet_FileKey = 0x90;
const byte Packet_InternalSize = 0xA0;
const byte Packet_InternalHash = 0xB0;
const byte Packet_Revs = 0xD0;
const byte Packet_Integrated = 0xE0;
const byte Packet_Scope = 0xF0;
public long Size;
public byte[] Hash;
public ulong HashID;
public byte[] FileKey;
// serves as lookup, so multiple files with same hash aren't duplicated,
// especailly since people moving them all around wiould increase the chance of a new key being created for them
public long InternalSize;
public byte[] InternalHash;
public ulong InternalHashID;
public StorageFile()
{
}
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame file = protocol.WritePacket(null, StoragePacket.File, null);
protocol.WritePacket(file, Packet_UID, BitConverter.GetBytes(UID));
protocol.WritePacket(file, Packet_Name, UTF8Encoding.UTF8.GetBytes(Name));
protocol.WritePacket(file, Packet_Date, BitConverter.GetBytes(Date.ToBinary()));
StorageFlags netFlags = Flags & ~(StorageFlags.Unlocked); // allow modified for working
protocol.WritePacket(file, Packet_Flags, BitConverter.GetBytes((ushort)netFlags));
protocol.WritePacket(file, Packet_Revs, BitConverter.GetBytes(Revs));
protocol.WritePacket(file, Packet_Integrated, BitConverter.GetBytes(IntegratedID));
protocol.WritePacket(file, Packet_Size, CompactNum.GetBytes(Size));
protocol.WritePacket(file, Packet_Hash, Hash);
protocol.WritePacket(file, Packet_FileKey, FileKey);
protocol.WritePacket(file, Packet_InternalSize, CompactNum.GetBytes(InternalSize));
protocol.WritePacket(file, Packet_InternalHash, InternalHash);
byte[] scopefield = new byte[10];
foreach (ulong id in Scope.Keys)
{
BitConverter.GetBytes(id).CopyTo(scopefield, 0);
BitConverter.GetBytes(Scope[id]).CopyTo(scopefield, 8);
protocol.WritePacket(file, Packet_Scope, scopefield);
}
if (Note != null)
protocol.WritePacket(file, Packet_Note, UTF8Encoding.UTF8.GetBytes(Note));
return protocol.WriteFinish();
}
}
public static StorageFile Decode(byte[] data)
{
G2Header root = new G2Header(data);
if (!G2Protocol.ReadPacket(root))
return null;
if (root.Name != StoragePacket.File)
return null;
return StorageFile.Decode(root);
}
public static StorageFile Decode(G2Header root)
{
StorageFile file = new StorageFile();
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_UID:
file.UID = BitConverter.ToUInt64(child.Data, child.PayloadPos);
break;
case Packet_Name:
file.Name = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Date:
file.Date = DateTime.FromBinary(BitConverter.ToInt64(child.Data, child.PayloadPos));
break;
case Packet_Flags:
file.Flags = (StorageFlags) BitConverter.ToUInt16(child.Data, child.PayloadPos);
break;
case Packet_Note:
file.Note = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Revs:
file.Revs = child.Data[child.PayloadPos];
break;
case Packet_Size:
file.Size = CompactNum.ToInt64(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Hash:
file.Hash = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
file.HashID = BitConverter.ToUInt64(file.Hash, 0);
break;
case Packet_FileKey:
file.FileKey = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_InternalSize:
file.InternalSize = CompactNum.ToInt64(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_InternalHash:
file.InternalHash = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
file.InternalHashID = BitConverter.ToUInt64(file.InternalHash, 0);
break;
case Packet_Integrated:
file.IntegratedID = BitConverter.ToUInt64(child.Data, child.PayloadPos);
break;
case Packet_Scope:
file.Scope[BitConverter.ToUInt64(child.Data, child.PayloadPos)] = BitConverter.ToInt16(child.Data, child.PayloadPos + 8);
break;
}
}
return file;
}
public StorageFile Clone()
{
// clones everything except notes
StorageFile clone = new StorageFile();
clone.UID = UID;
clone.Name = Name;
clone.Date = Date;
clone.Flags = Flags;
clone.Revs = Revs;
clone.Size = Size;
clone.Hash = Hash;
clone.HashID = HashID;
clone.FileKey = FileKey;
clone.InternalSize = InternalSize;
clone.InternalHash = InternalHash;
clone.InternalHashID = InternalHashID;
return clone;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
namespace Community.CsharpSqlite
{
using sqlite3_callback = Sqlite3.dxCallback;
using sqlite3_stmt = Sqlite3.Vdbe;
public partial class Sqlite3
{
/*
** 2001 September 15
**
** 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.
**
*************************************************************************
** Main file for the SQLite library. The routines in this file
** implement the programmer interface to the library. Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** Execute SQL code. Return one of the SQLITE_ success/failure
** codes. Also write an error message into memory obtained from
** malloc() and make pzErrMsg point to that message.
**
** If the SQL is a query, then for each row in the query result
** the xCallback() function is called. pArg becomes the first
** argument to xCallback(). If xCallback=NULL then no callback
** is invoked, even for queries.
*/
//C# Alias
static public int exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ int NoCallback, int NoArgs, int NoErrors )
{
string Errors = "";
return sqlite3_exec( db, zSql, null, null, ref Errors );
}
static public int exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ int NoErrors )
{
string Errors = "";
return sqlite3_exec( db, zSql, xCallback, pArg, ref Errors );
}
static public int exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ ref string pzErrMsg /* Write error messages here */)
{
return sqlite3_exec( db, zSql, xCallback, pArg, ref pzErrMsg );
}
//OVERLOADS
static public int sqlite3_exec(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
int NoCallback, int NoArgs, int NoErrors
)
{
string Errors = "";
return sqlite3_exec( db, zSql, null, null, ref Errors );
}
static public int sqlite3_exec(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
sqlite3_callback xCallback, /* Invoke this callback routine */
object pArg, /* First argument to xCallback() */
int NoErrors
)
{
string Errors = "";
return sqlite3_exec( db, zSql, xCallback, pArg, ref Errors );
}
static public int sqlite3_exec(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
sqlite3_callback xCallback, /* Invoke this callback routine */
object pArg, /* First argument to xCallback() */
ref string pzErrMsg /* Write error messages here */
)
{
int rc = SQLITE_OK; /* Return code */
string zLeftover = ""; /* Tail of unprocessed SQL */
sqlite3_stmt pStmt = null; /* The current SQL statement */
string[] azCols = null; /* Names of result columns */
int nRetry = 0; /* Number of retry attempts */
int callbackIsInit; /* True if callback data is initialized */
if ( !sqlite3SafetyCheckOk( db ) )
return SQLITE_MISUSE_BKPT();
if ( zSql == null )
zSql = "";
sqlite3_mutex_enter( db.mutex );
sqlite3Error( db, SQLITE_OK, 0 );
while ( ( rc == SQLITE_OK || ( rc == SQLITE_SCHEMA && ( ++nRetry ) < 2 ) ) && zSql != "" )
{
int nCol;
string[] azVals = null;
pStmt = null;
rc = sqlite3_prepare( db, zSql, -1, ref pStmt, ref zLeftover );
Debug.Assert( rc == SQLITE_OK || pStmt == null );
if ( rc != SQLITE_OK )
{
continue;
}
if ( pStmt == null )
{
/* this happens for a comment or white-space */
zSql = zLeftover;
continue;
}
callbackIsInit = 0;
nCol = sqlite3_column_count( pStmt );
while ( true )
{
int i;
rc = sqlite3_step( pStmt );
/* Invoke the callback function if required */
if ( xCallback != null && ( SQLITE_ROW == rc ||
( SQLITE_DONE == rc && callbackIsInit == 0
&& ( db.flags & SQLITE_NullCallback ) != 0 ) ) )
{
if ( 0 == callbackIsInit )
{
azCols = new string[nCol];//sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
//if ( azCols == null )
//{
// goto exec_out;
//}
for ( i = 0; i < nCol; i++ )
{
azCols[i] = sqlite3_column_name( pStmt, i );
/* sqlite3VdbeSetColName() installs column names as UTF8
** strings so there is no way for sqlite3_column_name() to fail. */
Debug.Assert( azCols[i] != null );
}
callbackIsInit = 1;
}
if ( rc == SQLITE_ROW )
{
azVals = new string[nCol];// azCols[nCol];
for ( i = 0; i < nCol; i++ )
{
azVals[i] = sqlite3_column_text( pStmt, i );
if ( azVals[i] == null && sqlite3_column_type( pStmt, i ) != SQLITE_NULL )
{
//db.mallocFailed = 1;
//goto exec_out;
}
}
}
if ( xCallback( pArg, nCol, azVals, azCols ) != 0 )
{
rc = SQLITE_ABORT;
sqlite3VdbeFinalize( ref pStmt );
pStmt = null;
sqlite3Error( db, SQLITE_ABORT, 0 );
goto exec_out;
}
}
if ( rc != SQLITE_ROW )
{
rc = sqlite3VdbeFinalize( ref pStmt );
pStmt = null;
if ( rc != SQLITE_SCHEMA )
{
nRetry = 0;
if ( ( zSql = zLeftover ) != "" )
{
int zindex = 0;
while ( zindex < zSql.Length && sqlite3Isspace( zSql[zindex] ) )
zindex++;
if ( zindex != 0 )
zSql = zindex < zSql.Length ? zSql.Substring( zindex ) : "";
}
}
break;
}
}
sqlite3DbFree( db, ref azCols );
azCols = null;
}
exec_out:
if ( pStmt != null )
sqlite3VdbeFinalize( ref pStmt );
sqlite3DbFree( db, ref azCols );
rc = sqlite3ApiExit( db, rc );
if ( rc != SQLITE_OK && ALWAYS( rc == sqlite3_errcode( db ) ) && pzErrMsg != null )
{
//int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
//pzErrMsg = sqlite3Malloc(nErrMsg);
//if (pzErrMsg)
//{
// memcpy(pzErrMsg, sqlite3_errmsg(db), nErrMsg);
//}else{
//rc = SQLITE_NOMEM;
//sqlite3Error(db, SQLITE_NOMEM, 0);
//}
pzErrMsg = sqlite3_errmsg( db );
}
else if ( pzErrMsg != "" )
{
pzErrMsg = "";
}
Debug.Assert( ( rc & db.errMask ) == rc );
sqlite3_mutex_leave( db.mutex );
return rc;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// SNI Packet
/// </summary>
internal class SNIPacket : IDisposable, IEquatable<SNIPacket>
{
private byte[] _data;
private int _length;
private int _offset;
private string _description;
private SNIAsyncCallback _completionCallback;
/// <summary>
/// Packet description (used for debugging)
/// </summary>
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
/// <summary>
/// Length of data left to process
/// </summary>
public int DataLeft
{
get
{
return _length - _offset;
}
}
/// <summary>
/// Length of data
/// </summary>
public int Length
{
get
{
return _length;
}
}
public bool IsInvalid
{
get
{
return _data == null;
}
}
public void Dispose()
{
_data = null;
Release();
}
/// <summary>
/// Set async completion callback
/// </summary>
/// <param name="completionCallback">Completion callback</param>
public void SetCompletionCallback(SNIAsyncCallback completionCallback)
{
_completionCallback = completionCallback;
}
/// <summary>
/// Invoke the completion callback
/// </summary>
/// <param name="sniErrorCode">SNI error</param>
public void InvokeCompletionCallback(uint sniErrorCode)
{
_completionCallback(this, sniErrorCode);
}
/// <summary>
/// Allocate byte array for data.
/// </summary>
/// <param name="bufferSize">Minimum length of byte array to be allocated</param>
public void Allocate(int bufferSize)
{
if (_data == null || _data.Length != bufferSize)
{
_data = new byte[bufferSize];
}
_length = 0;
_offset = 0;
}
/// <summary>
/// Clone packet
/// </summary>
/// <returns>Cloned packet</returns>
public SNIPacket Clone()
{
SNIPacket packet = new SNIPacket();
packet._data = new byte[_data.Length];
Buffer.BlockCopy(_data, 0, packet._data, 0, _data.Length);
packet._length = _length;
packet._description = _description;
packet._completionCallback = _completionCallback;
return packet;
}
/// <summary>
/// Get packet data
/// </summary>
/// <param name="buffer">Buffer</param>
/// <param name="dataSize">Data in packet</param>
public void GetData(byte[] buffer, ref int dataSize)
{
Buffer.BlockCopy(_data, 0, buffer, 0, _length);
dataSize = _length;
}
/// <summary>
/// Set packet data
/// </summary>
/// <param name="data">Data</param>
/// <param name="length">Length</param>
public void SetData(byte[] data, int length)
{
_data = data;
_length = length;
_offset = 0;
}
/// <summary>
/// Take data from another packet
/// </summary>
/// <param name="packet">Packet</param>
/// <param name="size">Data to take</param>
/// <returns>Amount of data taken</returns>
public int TakeData(SNIPacket packet, int size)
{
int dataSize = TakeData(packet._data, packet._length, size);
packet._length += dataSize;
return dataSize;
}
/// <summary>
/// Append data
/// </summary>
/// <param name="data">Data</param>
/// <param name="size">Size</param>
public void AppendData(byte[] data, int size)
{
Buffer.BlockCopy(data, 0, _data, _length, size);
_length += size;
}
/// <summary>
/// Append another packet
/// </summary>
/// <param name="packet">Packet</param>
public void AppendPacket(SNIPacket packet)
{
Buffer.BlockCopy(packet._data, 0, _data, _length, packet._length);
_length += packet._length;
}
/// <summary>
/// Take data from packet and advance offset
/// </summary>
/// <param name="buffer">Buffer</param>
/// <param name="dataOffset">Data offset</param>
/// <param name="size">Size</param>
/// <returns></returns>
public int TakeData(byte[] buffer, int dataOffset, int size)
{
if (_offset >= _length)
{
return 0;
}
if (_offset + size > _length)
{
size = _length - _offset;
}
Buffer.BlockCopy(_data, _offset, buffer, dataOffset, size);
_offset += size;
return size;
}
/// <summary>
/// Release packet
/// </summary>
public void Release()
{
Reset();
}
/// <summary>
/// Reset packet
/// </summary>
public void Reset()
{
_length = 0;
_offset = 0;
_description = null;
_completionCallback = null;
}
/// <summary>
/// Read data from a stream asynchronously
/// </summary>
/// <param name="stream">Stream to read from</param>
/// <param name="callback">Completion callback</param>
public void ReadFromStreamAsync(Stream stream, SNIAsyncCallback callback, bool isMars)
{
bool error = false;
TaskContinuationOptions options = TaskContinuationOptions.DenyChildAttach;
// MARS operations during Sync ADO.Net API calls are Sync over Async. Each API call can request
// threads to execute the async reads. MARS operations do not get the threads quickly enough leading to timeout
// To fix the MARS thread exhaustion issue LongRunning continuation option is a temporary solution with its own drawbacks,
// and should be removed after evaluating how to fix MARS threading issues efficiently
if (isMars)
{
options |= TaskContinuationOptions.LongRunning;
}
stream.ReadAsync(_data, 0, _data.Length).ContinueWith(t =>
{
Exception e = t.Exception != null ? t.Exception.InnerException : null;
if (e != null)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, e);
error = true;
}
else
{
_length = t.Result;
if (_length == 0)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.ConnTerminatedError, string.Empty);
error = true;
}
}
if (error)
{
Release();
}
callback(this, error ? TdsEnums.SNI_ERROR : TdsEnums.SNI_SUCCESS);
},
CancellationToken.None,
options,
TaskScheduler.Default);
}
/// <summary>
/// Read data from a stream synchronously
/// </summary>
/// <param name="stream">Stream to read from</param>
public void ReadFromStream(Stream stream)
{
_length = stream.Read(_data, 0, _data.Length);
}
/// <summary>
/// Write data to a stream synchronously
/// </summary>
/// <param name="stream">Stream to write to</param>
public void WriteToStream(Stream stream)
{
stream.Write(_data, 0, _length);
}
public Task WriteToStreamAsync(Stream stream)
{
return stream.WriteAsync(_data, 0, _length);
}
/// <summary>
/// Get hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Check packet equality
/// </summary>
/// <param name="obj"></param>
/// <returns>true if equal</returns>
public override bool Equals(object obj)
{
SNIPacket packet = obj as SNIPacket;
if (packet != null)
{
return Equals(packet);
}
return false;
}
/// <summary>
/// Check packet equality
/// </summary>
/// <param name="obj"></param>
/// <returns>true if equal</returns>
public bool Equals(SNIPacket packet)
{
if (packet != null)
{
return object.ReferenceEquals(packet, this);
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// Currently active AudioEvents along with their AudioSource components for instance limiting events
/// </summary>
public class ActiveEvent : IDisposable
{
private AudioSource primarySource = null;
public AudioSource PrimarySource
{
get
{
return primarySource;
}
private set
{
primarySource = value;
if (primarySource != null)
{
primarySource.enabled = true;
}
}
}
private AudioSource secondarySource = null;
public AudioSource SecondarySource
{
get
{
return secondarySource;
}
private set
{
secondarySource = value;
if (secondarySource != null)
{
secondarySource.enabled = true;
}
}
}
public bool IsPlaying
{
get
{
return
(primarySource != null && primarySource.isPlaying) ||
(secondarySource != null && secondarySource.isPlaying);
}
}
public GameObject AudioEmitter
{
get;
private set;
}
public string MessageOnAudioEnd
{
get;
private set;
}
public AudioEvent audioEvent = null;
public bool isStoppable = true;
public float volDest = 1;
public float altVolDest = 1;
public float currentFade = 0;
public bool playingAlt = false;
public bool isActiveTimeComplete = false;
public float activeTime = 0;
public bool cancelEvent = false;
public ActiveEvent(AudioEvent audioEvent, GameObject emitter, AudioSource primarySource, AudioSource secondarySource, string messageOnAudioEnd = null)
{
this.audioEvent = audioEvent;
AudioEmitter = emitter;
PrimarySource = primarySource;
SecondarySource = secondarySource;
MessageOnAudioEnd = messageOnAudioEnd;
SetSourceProperties();
}
public static AnimationCurve SpatialRolloff;
/// <summary>
/// Set the volume, spatialization, etc., on our AudioSources to match the settings on the event to play.
/// </summary>
private void SetSourceProperties()
{
Action<Action<AudioSource>> forEachSource = (action) =>
{
action(PrimarySource);
if (SecondarySource != null)
{
action(SecondarySource);
}
};
AudioEvent audioEvent = this.audioEvent;
switch (audioEvent.spatialization)
{
case SpatialPositioningType.TwoD:
forEachSource((source) =>
{
source.spatialBlend = 0f;
source.spatialize = false;
});
break;
case SpatialPositioningType.ThreeD:
forEachSource((source) =>
{
source.spatialBlend = 1f;
source.spatialize = false;
});
break;
case SpatialPositioningType.SpatialSound:
forEachSource((source) =>
{
source.spatialBlend = 1f;
source.spatialize = true;
});
break;
default:
Debug.LogErrorFormat("Unexpected spatialization type: {0}", audioEvent.spatialization.ToString());
break;
}
if (audioEvent.spatialization == SpatialPositioningType.SpatialSound)
{
CreateFlatSpatialRolloffCurve();
forEachSource((source) =>
{
source.rolloffMode = AudioRolloffMode.Custom;
source.SetCustomCurve(AudioSourceCurveType.CustomRolloff, SpatialRolloff);
SpatialSoundSettings.SetRoomSize(source, audioEvent.roomSize);
SpatialSoundSettings.SetMinGain(source, audioEvent.minGain);
SpatialSoundSettings.SetMaxGain(source, audioEvent.maxGain);
SpatialSoundSettings.SetUnityGainDistance(source, audioEvent.unityGainDistance);
});
}
else
{
forEachSource((source) =>
{
if (audioEvent.spatialization == SpatialPositioningType.ThreeD)
{
source.rolloffMode = AudioRolloffMode.Custom;
source.maxDistance = audioEvent.maxDistanceAttenuation3D;
source.SetCustomCurve(AudioSourceCurveType.CustomRolloff, audioEvent.attenuationCurve);
source.SetCustomCurve(AudioSourceCurveType.SpatialBlend, audioEvent.spatialCurve);
source.SetCustomCurve(AudioSourceCurveType.Spread, audioEvent.spreadCurve);
source.SetCustomCurve(AudioSourceCurveType.ReverbZoneMix, audioEvent.reverbCurve);
}
else
{
source.rolloffMode = AudioRolloffMode.Logarithmic;
}
});
}
if (audioEvent.bus != null)
{
forEachSource((source) => source.outputAudioMixerGroup = audioEvent.bus);
}
float pitch = 1f;
if (audioEvent.pitchRandomization != 0)
{
pitch = UnityEngine.Random.Range(audioEvent.pitchCenter - audioEvent.pitchRandomization, audioEvent.pitchCenter + audioEvent.pitchRandomization);
}
else
{
pitch = audioEvent.pitchCenter;
}
forEachSource((source) => source.pitch = pitch);
float vol = 1f;
if (audioEvent.fadeInTime > 0)
{
forEachSource((source) => source.volume = 0f);
this.currentFade = audioEvent.fadeInTime;
if (audioEvent.volumeRandomization != 0)
{
vol = UnityEngine.Random.Range(audioEvent.volumeCenter - audioEvent.volumeRandomization, audioEvent.volumeCenter + audioEvent.volumeRandomization);
}
else
{
vol = audioEvent.volumeCenter;
}
this.volDest = vol;
}
else
{
if (audioEvent.volumeRandomization != 0)
{
vol = UnityEngine.Random.Range(audioEvent.volumeCenter - audioEvent.volumeRandomization, audioEvent.volumeCenter + audioEvent.volumeRandomization);
}
else
{
vol = audioEvent.volumeCenter;
}
forEachSource((source) => source.volume = vol);
}
float pan = audioEvent.panCenter;
if (audioEvent.panRandomization != 0)
{
pan = UnityEngine.Random.Range(audioEvent.panCenter - audioEvent.panRandomization, audioEvent.panCenter + audioEvent.panRandomization);
}
forEachSource((source) => source.panStereo = pan);
}
/// <summary>
/// Sets the pitch value for the primary source.
/// </summary>
/// <param name="newPitch">The value to set the pitch, between 0 (exclusive) and 3 (inclusive).</param>
public void SetPitch(float newPitch)
{
if (newPitch <= 0 || newPitch > 3)
{
Debug.LogErrorFormat("Invalid pitch {0} set for event", newPitch);
return;
}
this.PrimarySource.pitch = newPitch;
}
public void Dispose()
{
if (this.primarySource != null)
{
this.primarySource.enabled = false;
this.primarySource = null;
}
if (this.secondarySource != null)
{
this.secondarySource.enabled = false;
this.secondarySource = null;
}
}
/// <summary>
/// Creates a flat animation curve to negate Unity's distance attenuation when using Spatial Sound
/// </summary>
public static void CreateFlatSpatialRolloffCurve()
{
if (SpatialRolloff != null)
{
return;
}
SpatialRolloff = new AnimationCurve();
SpatialRolloff.AddKey(0, 1);
SpatialRolloff.AddKey(1, 1);
}
}
}
| |
//
// 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.Collections.Generic;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
//[Cmdlet(VerbsLifecycle.Invoke, "AzureComputeMethod", DefaultParameterSetName = "InvokeByDynamicParameters")]
[OutputType(typeof(object))]
public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet, IDynamicParameters
{
protected RuntimeDefinedParameterDictionary dynamicParameters;
protected object[] argumentList;
protected static object[] ConvertDynamicParameters(RuntimeDefinedParameterDictionary parameters)
{
List<object> paramList = new List<object>();
foreach (var param in parameters)
{
paramList.Add(param.Value.Value);
}
return paramList.ToArray();
}
[Parameter(Mandatory = true, ParameterSetName = "InvokeByDynamicParameters", Position = 0)]
[Parameter(Mandatory = true, ParameterSetName = "InvokeByStaticParameters", Position = 0)]
[ValidateSet(
"AvailabilitySetCreateOrUpdate",
"AvailabilitySetDelete",
"AvailabilitySetGet",
"AvailabilitySetList",
"AvailabilitySetListAvailableSizes",
"ContainerServiceCreateOrUpdate",
"ContainerServiceDelete",
"ContainerServiceGet",
"ContainerServiceList",
"ContainerServiceListByResourceGroup",
"ContainerServiceListByResourceGroupNext",
"ContainerServiceListNext",
"DiskCreateOrUpdate",
"DiskDelete",
"DiskGet",
"DiskGrantAccess",
"DiskList",
"DiskListByResourceGroup",
"DiskListByResourceGroupNext",
"DiskListNext",
"DiskRevokeAccess",
"DiskUpdate",
"ImageCreateOrUpdate",
"ImageDelete",
"ImageGet",
"ImageList",
"ImageListByResourceGroup",
"ImageListByResourceGroupNext",
"ImageListNext",
"ResourceSkuList",
"ResourceSkuListNext",
"SnapshotCreateOrUpdate",
"SnapshotDelete",
"SnapshotGet",
"SnapshotGrantAccess",
"SnapshotList",
"SnapshotListByResourceGroup",
"SnapshotListByResourceGroupNext",
"SnapshotListNext",
"SnapshotRevokeAccess",
"SnapshotUpdate",
"VirtualMachineRunCommandGet",
"VirtualMachineRunCommandList",
"VirtualMachineRunCommandListNext",
"VirtualMachineScaleSetCreateOrUpdate",
"VirtualMachineScaleSetDeallocate",
"VirtualMachineScaleSetDelete",
"VirtualMachineScaleSetDeleteInstances",
"VirtualMachineScaleSetGet",
"VirtualMachineScaleSetGetInstanceView",
"VirtualMachineScaleSetList",
"VirtualMachineScaleSetListAll",
"VirtualMachineScaleSetListAllNext",
"VirtualMachineScaleSetListNext",
"VirtualMachineScaleSetListSkus",
"VirtualMachineScaleSetListSkusNext",
"VirtualMachineScaleSetPowerOff",
"VirtualMachineScaleSetReimage",
"VirtualMachineScaleSetReimageAll",
"VirtualMachineScaleSetRestart",
"VirtualMachineScaleSetStart",
"VirtualMachineScaleSetUpdateInstances",
"VirtualMachineScaleSetVMDeallocate",
"VirtualMachineScaleSetVMDelete",
"VirtualMachineScaleSetVMGet",
"VirtualMachineScaleSetVMGetInstanceView",
"VirtualMachineScaleSetVMList",
"VirtualMachineScaleSetVMListNext",
"VirtualMachineScaleSetVMPowerOff",
"VirtualMachineScaleSetVMReimage",
"VirtualMachineScaleSetVMReimageAll",
"VirtualMachineScaleSetVMRestart",
"VirtualMachineScaleSetVMStart",
"VirtualMachineCapture",
"VirtualMachineConvertToManagedDisks",
"VirtualMachineCreateOrUpdate",
"VirtualMachineDeallocate",
"VirtualMachineDelete",
"VirtualMachineGeneralize",
"VirtualMachineGet",
"VirtualMachineList",
"VirtualMachineListAll",
"VirtualMachineListAllNext",
"VirtualMachineListAvailableSizes",
"VirtualMachineListNext",
"VirtualMachinePerformMaintenance",
"VirtualMachinePowerOff",
"VirtualMachineRedeploy",
"VirtualMachineRestart",
"VirtualMachineRunCommand",
"VirtualMachineStart"
)]
public virtual string MethodName { get; set; }
protected object ParseParameter(object input)
{
if (input is PSObject)
{
return (input as PSObject).BaseObject;
}
else
{
return input;
}
}
protected override void ProcessRecord()
{
base.ProcessRecord();
ExecuteClientAction(() =>
{
if (ParameterSetName.StartsWith("InvokeByDynamicParameters"))
{
argumentList = ConvertDynamicParameters(dynamicParameters);
}
else
{
argumentList = ConvertFromArgumentsToObjects((object[])dynamicParameters["ArgumentList"].Value);
}
switch (MethodName)
{
case "AvailabilitySetCreateOrUpdate":
ExecuteAvailabilitySetCreateOrUpdateMethod(argumentList);
break;
case "AvailabilitySetDelete":
ExecuteAvailabilitySetDeleteMethod(argumentList);
break;
case "AvailabilitySetGet":
ExecuteAvailabilitySetGetMethod(argumentList);
break;
case "AvailabilitySetList":
ExecuteAvailabilitySetListMethod(argumentList);
break;
case "AvailabilitySetListAvailableSizes":
ExecuteAvailabilitySetListAvailableSizesMethod(argumentList);
break;
case "ContainerServiceCreateOrUpdate":
ExecuteContainerServiceCreateOrUpdateMethod(argumentList);
break;
case "ContainerServiceDelete":
ExecuteContainerServiceDeleteMethod(argumentList);
break;
case "ContainerServiceGet":
ExecuteContainerServiceGetMethod(argumentList);
break;
case "ContainerServiceList":
ExecuteContainerServiceListMethod(argumentList);
break;
case "ContainerServiceListByResourceGroup":
ExecuteContainerServiceListByResourceGroupMethod(argumentList);
break;
case "ContainerServiceListByResourceGroupNext":
ExecuteContainerServiceListByResourceGroupNextMethod(argumentList);
break;
case "ContainerServiceListNext":
ExecuteContainerServiceListNextMethod(argumentList);
break;
case "DiskCreateOrUpdate":
ExecuteDiskCreateOrUpdateMethod(argumentList);
break;
case "DiskDelete":
ExecuteDiskDeleteMethod(argumentList);
break;
case "DiskGet":
ExecuteDiskGetMethod(argumentList);
break;
case "DiskGrantAccess":
ExecuteDiskGrantAccessMethod(argumentList);
break;
case "DiskList":
ExecuteDiskListMethod(argumentList);
break;
case "DiskListByResourceGroup":
ExecuteDiskListByResourceGroupMethod(argumentList);
break;
case "DiskListByResourceGroupNext":
ExecuteDiskListByResourceGroupNextMethod(argumentList);
break;
case "DiskListNext":
ExecuteDiskListNextMethod(argumentList);
break;
case "DiskRevokeAccess":
ExecuteDiskRevokeAccessMethod(argumentList);
break;
case "DiskUpdate":
ExecuteDiskUpdateMethod(argumentList);
break;
case "ImageCreateOrUpdate":
ExecuteImageCreateOrUpdateMethod(argumentList);
break;
case "ImageDelete":
ExecuteImageDeleteMethod(argumentList);
break;
case "ImageGet":
ExecuteImageGetMethod(argumentList);
break;
case "ImageList":
ExecuteImageListMethod(argumentList);
break;
case "ImageListByResourceGroup":
ExecuteImageListByResourceGroupMethod(argumentList);
break;
case "ImageListByResourceGroupNext":
ExecuteImageListByResourceGroupNextMethod(argumentList);
break;
case "ImageListNext":
ExecuteImageListNextMethod(argumentList);
break;
case "ResourceSkuList":
ExecuteResourceSkuListMethod(argumentList);
break;
case "ResourceSkuListNext":
ExecuteResourceSkuListNextMethod(argumentList);
break;
case "SnapshotCreateOrUpdate":
ExecuteSnapshotCreateOrUpdateMethod(argumentList);
break;
case "SnapshotDelete":
ExecuteSnapshotDeleteMethod(argumentList);
break;
case "SnapshotGet":
ExecuteSnapshotGetMethod(argumentList);
break;
case "SnapshotGrantAccess":
ExecuteSnapshotGrantAccessMethod(argumentList);
break;
case "SnapshotList":
ExecuteSnapshotListMethod(argumentList);
break;
case "SnapshotListByResourceGroup":
ExecuteSnapshotListByResourceGroupMethod(argumentList);
break;
case "SnapshotListByResourceGroupNext":
ExecuteSnapshotListByResourceGroupNextMethod(argumentList);
break;
case "SnapshotListNext":
ExecuteSnapshotListNextMethod(argumentList);
break;
case "SnapshotRevokeAccess":
ExecuteSnapshotRevokeAccessMethod(argumentList);
break;
case "SnapshotUpdate":
ExecuteSnapshotUpdateMethod(argumentList);
break;
case "VirtualMachineRunCommandGet":
ExecuteVirtualMachineRunCommandGetMethod(argumentList);
break;
case "VirtualMachineRunCommandList":
ExecuteVirtualMachineRunCommandListMethod(argumentList);
break;
case "VirtualMachineRunCommandListNext":
ExecuteVirtualMachineRunCommandListNextMethod(argumentList);
break;
case "VirtualMachineScaleSetCreateOrUpdate":
ExecuteVirtualMachineScaleSetCreateOrUpdateMethod(argumentList);
break;
case "VirtualMachineScaleSetDeallocate":
ExecuteVirtualMachineScaleSetDeallocateMethod(argumentList);
break;
case "VirtualMachineScaleSetDelete":
ExecuteVirtualMachineScaleSetDeleteMethod(argumentList);
break;
case "VirtualMachineScaleSetDeleteInstances":
ExecuteVirtualMachineScaleSetDeleteInstancesMethod(argumentList);
break;
case "VirtualMachineScaleSetGet":
ExecuteVirtualMachineScaleSetGetMethod(argumentList);
break;
case "VirtualMachineScaleSetGetInstanceView":
ExecuteVirtualMachineScaleSetGetInstanceViewMethod(argumentList);
break;
case "VirtualMachineScaleSetList":
ExecuteVirtualMachineScaleSetListMethod(argumentList);
break;
case "VirtualMachineScaleSetListAll":
ExecuteVirtualMachineScaleSetListAllMethod(argumentList);
break;
case "VirtualMachineScaleSetListAllNext":
ExecuteVirtualMachineScaleSetListAllNextMethod(argumentList);
break;
case "VirtualMachineScaleSetListNext":
ExecuteVirtualMachineScaleSetListNextMethod(argumentList);
break;
case "VirtualMachineScaleSetListSkus":
ExecuteVirtualMachineScaleSetListSkusMethod(argumentList);
break;
case "VirtualMachineScaleSetListSkusNext":
ExecuteVirtualMachineScaleSetListSkusNextMethod(argumentList);
break;
case "VirtualMachineScaleSetPowerOff":
ExecuteVirtualMachineScaleSetPowerOffMethod(argumentList);
break;
case "VirtualMachineScaleSetReimage":
ExecuteVirtualMachineScaleSetReimageMethod(argumentList);
break;
case "VirtualMachineScaleSetReimageAll":
ExecuteVirtualMachineScaleSetReimageAllMethod(argumentList);
break;
case "VirtualMachineScaleSetRestart":
ExecuteVirtualMachineScaleSetRestartMethod(argumentList);
break;
case "VirtualMachineScaleSetStart":
ExecuteVirtualMachineScaleSetStartMethod(argumentList);
break;
case "VirtualMachineScaleSetUpdateInstances":
ExecuteVirtualMachineScaleSetUpdateInstancesMethod(argumentList);
break;
case "VirtualMachineScaleSetVMDeallocate":
ExecuteVirtualMachineScaleSetVMDeallocateMethod(argumentList);
break;
case "VirtualMachineScaleSetVMDelete":
ExecuteVirtualMachineScaleSetVMDeleteMethod(argumentList);
break;
case "VirtualMachineScaleSetVMGet":
ExecuteVirtualMachineScaleSetVMGetMethod(argumentList);
break;
case "VirtualMachineScaleSetVMGetInstanceView":
ExecuteVirtualMachineScaleSetVMGetInstanceViewMethod(argumentList);
break;
case "VirtualMachineScaleSetVMList":
ExecuteVirtualMachineScaleSetVMListMethod(argumentList);
break;
case "VirtualMachineScaleSetVMListNext":
ExecuteVirtualMachineScaleSetVMListNextMethod(argumentList);
break;
case "VirtualMachineScaleSetVMPowerOff":
ExecuteVirtualMachineScaleSetVMPowerOffMethod(argumentList);
break;
case "VirtualMachineScaleSetVMReimage":
ExecuteVirtualMachineScaleSetVMReimageMethod(argumentList);
break;
case "VirtualMachineScaleSetVMReimageAll":
ExecuteVirtualMachineScaleSetVMReimageAllMethod(argumentList);
break;
case "VirtualMachineScaleSetVMRestart":
ExecuteVirtualMachineScaleSetVMRestartMethod(argumentList);
break;
case "VirtualMachineScaleSetVMStart":
ExecuteVirtualMachineScaleSetVMStartMethod(argumentList);
break;
case "VirtualMachineCapture":
ExecuteVirtualMachineCaptureMethod(argumentList);
break;
case "VirtualMachineConvertToManagedDisks":
ExecuteVirtualMachineConvertToManagedDisksMethod(argumentList);
break;
case "VirtualMachineCreateOrUpdate":
ExecuteVirtualMachineCreateOrUpdateMethod(argumentList);
break;
case "VirtualMachineDeallocate":
ExecuteVirtualMachineDeallocateMethod(argumentList);
break;
case "VirtualMachineDelete":
ExecuteVirtualMachineDeleteMethod(argumentList);
break;
case "VirtualMachineGeneralize":
ExecuteVirtualMachineGeneralizeMethod(argumentList);
break;
case "VirtualMachineGet":
ExecuteVirtualMachineGetMethod(argumentList);
break;
case "VirtualMachineList":
ExecuteVirtualMachineListMethod(argumentList);
break;
case "VirtualMachineListAll":
ExecuteVirtualMachineListAllMethod(argumentList);
break;
case "VirtualMachineListAllNext":
ExecuteVirtualMachineListAllNextMethod(argumentList);
break;
case "VirtualMachineListAvailableSizes":
ExecuteVirtualMachineListAvailableSizesMethod(argumentList);
break;
case "VirtualMachineListNext":
ExecuteVirtualMachineListNextMethod(argumentList);
break;
case "VirtualMachinePerformMaintenance":
ExecuteVirtualMachinePerformMaintenanceMethod(argumentList);
break;
case "VirtualMachinePowerOff":
ExecuteVirtualMachinePowerOffMethod(argumentList);
break;
case "VirtualMachineRedeploy":
ExecuteVirtualMachineRedeployMethod(argumentList);
break;
case "VirtualMachineRestart":
ExecuteVirtualMachineRestartMethod(argumentList);
break;
case "VirtualMachineRunCommand":
ExecuteVirtualMachineRunCommandMethod(argumentList);
break;
case "VirtualMachineStart":
ExecuteVirtualMachineStartMethod(argumentList);
break;
default: WriteWarning("Cannot find the method by name = '" + MethodName + "'."); break;
}
});
}
public virtual object GetDynamicParameters()
{
switch (MethodName)
{
case "AvailabilitySetCreateOrUpdate": return CreateAvailabilitySetCreateOrUpdateDynamicParameters();
case "AvailabilitySetDelete": return CreateAvailabilitySetDeleteDynamicParameters();
case "AvailabilitySetGet": return CreateAvailabilitySetGetDynamicParameters();
case "AvailabilitySetList": return CreateAvailabilitySetListDynamicParameters();
case "AvailabilitySetListAvailableSizes": return CreateAvailabilitySetListAvailableSizesDynamicParameters();
case "ContainerServiceCreateOrUpdate": return CreateContainerServiceCreateOrUpdateDynamicParameters();
case "ContainerServiceDelete": return CreateContainerServiceDeleteDynamicParameters();
case "ContainerServiceGet": return CreateContainerServiceGetDynamicParameters();
case "ContainerServiceList": return CreateContainerServiceListDynamicParameters();
case "ContainerServiceListByResourceGroup": return CreateContainerServiceListByResourceGroupDynamicParameters();
case "ContainerServiceListByResourceGroupNext": return CreateContainerServiceListByResourceGroupNextDynamicParameters();
case "ContainerServiceListNext": return CreateContainerServiceListNextDynamicParameters();
case "DiskCreateOrUpdate": return CreateDiskCreateOrUpdateDynamicParameters();
case "DiskDelete": return CreateDiskDeleteDynamicParameters();
case "DiskGet": return CreateDiskGetDynamicParameters();
case "DiskGrantAccess": return CreateDiskGrantAccessDynamicParameters();
case "DiskList": return CreateDiskListDynamicParameters();
case "DiskListByResourceGroup": return CreateDiskListByResourceGroupDynamicParameters();
case "DiskListByResourceGroupNext": return CreateDiskListByResourceGroupNextDynamicParameters();
case "DiskListNext": return CreateDiskListNextDynamicParameters();
case "DiskRevokeAccess": return CreateDiskRevokeAccessDynamicParameters();
case "DiskUpdate": return CreateDiskUpdateDynamicParameters();
case "ImageCreateOrUpdate": return CreateImageCreateOrUpdateDynamicParameters();
case "ImageDelete": return CreateImageDeleteDynamicParameters();
case "ImageGet": return CreateImageGetDynamicParameters();
case "ImageList": return CreateImageListDynamicParameters();
case "ImageListByResourceGroup": return CreateImageListByResourceGroupDynamicParameters();
case "ImageListByResourceGroupNext": return CreateImageListByResourceGroupNextDynamicParameters();
case "ImageListNext": return CreateImageListNextDynamicParameters();
case "ResourceSkuList": return CreateResourceSkuListDynamicParameters();
case "ResourceSkuListNext": return CreateResourceSkuListNextDynamicParameters();
case "SnapshotCreateOrUpdate": return CreateSnapshotCreateOrUpdateDynamicParameters();
case "SnapshotDelete": return CreateSnapshotDeleteDynamicParameters();
case "SnapshotGet": return CreateSnapshotGetDynamicParameters();
case "SnapshotGrantAccess": return CreateSnapshotGrantAccessDynamicParameters();
case "SnapshotList": return CreateSnapshotListDynamicParameters();
case "SnapshotListByResourceGroup": return CreateSnapshotListByResourceGroupDynamicParameters();
case "SnapshotListByResourceGroupNext": return CreateSnapshotListByResourceGroupNextDynamicParameters();
case "SnapshotListNext": return CreateSnapshotListNextDynamicParameters();
case "SnapshotRevokeAccess": return CreateSnapshotRevokeAccessDynamicParameters();
case "SnapshotUpdate": return CreateSnapshotUpdateDynamicParameters();
case "VirtualMachineRunCommandGet": return CreateVirtualMachineRunCommandGetDynamicParameters();
case "VirtualMachineRunCommandList": return CreateVirtualMachineRunCommandListDynamicParameters();
case "VirtualMachineRunCommandListNext": return CreateVirtualMachineRunCommandListNextDynamicParameters();
case "VirtualMachineScaleSetCreateOrUpdate": return CreateVirtualMachineScaleSetCreateOrUpdateDynamicParameters();
case "VirtualMachineScaleSetDeallocate": return CreateVirtualMachineScaleSetDeallocateDynamicParameters();
case "VirtualMachineScaleSetDelete": return CreateVirtualMachineScaleSetDeleteDynamicParameters();
case "VirtualMachineScaleSetDeleteInstances": return CreateVirtualMachineScaleSetDeleteInstancesDynamicParameters();
case "VirtualMachineScaleSetGet": return CreateVirtualMachineScaleSetGetDynamicParameters();
case "VirtualMachineScaleSetGetInstanceView": return CreateVirtualMachineScaleSetGetInstanceViewDynamicParameters();
case "VirtualMachineScaleSetList": return CreateVirtualMachineScaleSetListDynamicParameters();
case "VirtualMachineScaleSetListAll": return CreateVirtualMachineScaleSetListAllDynamicParameters();
case "VirtualMachineScaleSetListAllNext": return CreateVirtualMachineScaleSetListAllNextDynamicParameters();
case "VirtualMachineScaleSetListNext": return CreateVirtualMachineScaleSetListNextDynamicParameters();
case "VirtualMachineScaleSetListSkus": return CreateVirtualMachineScaleSetListSkusDynamicParameters();
case "VirtualMachineScaleSetListSkusNext": return CreateVirtualMachineScaleSetListSkusNextDynamicParameters();
case "VirtualMachineScaleSetPowerOff": return CreateVirtualMachineScaleSetPowerOffDynamicParameters();
case "VirtualMachineScaleSetReimage": return CreateVirtualMachineScaleSetReimageDynamicParameters();
case "VirtualMachineScaleSetReimageAll": return CreateVirtualMachineScaleSetReimageAllDynamicParameters();
case "VirtualMachineScaleSetRestart": return CreateVirtualMachineScaleSetRestartDynamicParameters();
case "VirtualMachineScaleSetStart": return CreateVirtualMachineScaleSetStartDynamicParameters();
case "VirtualMachineScaleSetUpdateInstances": return CreateVirtualMachineScaleSetUpdateInstancesDynamicParameters();
case "VirtualMachineScaleSetVMDeallocate": return CreateVirtualMachineScaleSetVMDeallocateDynamicParameters();
case "VirtualMachineScaleSetVMDelete": return CreateVirtualMachineScaleSetVMDeleteDynamicParameters();
case "VirtualMachineScaleSetVMGet": return CreateVirtualMachineScaleSetVMGetDynamicParameters();
case "VirtualMachineScaleSetVMGetInstanceView": return CreateVirtualMachineScaleSetVMGetInstanceViewDynamicParameters();
case "VirtualMachineScaleSetVMList": return CreateVirtualMachineScaleSetVMListDynamicParameters();
case "VirtualMachineScaleSetVMListNext": return CreateVirtualMachineScaleSetVMListNextDynamicParameters();
case "VirtualMachineScaleSetVMPowerOff": return CreateVirtualMachineScaleSetVMPowerOffDynamicParameters();
case "VirtualMachineScaleSetVMReimage": return CreateVirtualMachineScaleSetVMReimageDynamicParameters();
case "VirtualMachineScaleSetVMReimageAll": return CreateVirtualMachineScaleSetVMReimageAllDynamicParameters();
case "VirtualMachineScaleSetVMRestart": return CreateVirtualMachineScaleSetVMRestartDynamicParameters();
case "VirtualMachineScaleSetVMStart": return CreateVirtualMachineScaleSetVMStartDynamicParameters();
case "VirtualMachineCapture": return CreateVirtualMachineCaptureDynamicParameters();
case "VirtualMachineConvertToManagedDisks": return CreateVirtualMachineConvertToManagedDisksDynamicParameters();
case "VirtualMachineCreateOrUpdate": return CreateVirtualMachineCreateOrUpdateDynamicParameters();
case "VirtualMachineDeallocate": return CreateVirtualMachineDeallocateDynamicParameters();
case "VirtualMachineDelete": return CreateVirtualMachineDeleteDynamicParameters();
case "VirtualMachineGeneralize": return CreateVirtualMachineGeneralizeDynamicParameters();
case "VirtualMachineGet": return CreateVirtualMachineGetDynamicParameters();
case "VirtualMachineList": return CreateVirtualMachineListDynamicParameters();
case "VirtualMachineListAll": return CreateVirtualMachineListAllDynamicParameters();
case "VirtualMachineListAllNext": return CreateVirtualMachineListAllNextDynamicParameters();
case "VirtualMachineListAvailableSizes": return CreateVirtualMachineListAvailableSizesDynamicParameters();
case "VirtualMachineListNext": return CreateVirtualMachineListNextDynamicParameters();
case "VirtualMachinePerformMaintenance": return CreateVirtualMachinePerformMaintenanceDynamicParameters();
case "VirtualMachinePowerOff": return CreateVirtualMachinePowerOffDynamicParameters();
case "VirtualMachineRedeploy": return CreateVirtualMachineRedeployDynamicParameters();
case "VirtualMachineRestart": return CreateVirtualMachineRestartDynamicParameters();
case "VirtualMachineRunCommand": return CreateVirtualMachineRunCommandDynamicParameters();
case "VirtualMachineStart": return CreateVirtualMachineStartDynamicParameters();
default: break;
}
return null;
}
}
}
| |
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using Csla;
using System.ComponentModel;
namespace ProjectTracker.Library
{
[Serializable()]
public class ProjectEdit : CslaBaseTypes.BusinessBase<ProjectEdit>
{
public static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(c => c.TimeStamp);
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public byte[] TimeStamp
{
get { return GetProperty(TimeStampProperty); }
set { SetProperty(TimeStampProperty, value); }
}
public static readonly PropertyInfo<int> IdProperty =
RegisterProperty<int>(c => c.Id);
[Display(Name = "Project id")]
public int Id
{
get { return GetProperty(IdProperty); }
private set { LoadProperty(IdProperty, value); }
}
public static readonly PropertyInfo<string> NameProperty =
RegisterProperty<string>(c => c.Name);
[Display(Name = "Project name")]
[Required]
[StringLength(50)]
public string Name
{
get { return GetProperty(NameProperty); }
set { SetProperty(NameProperty, value); }
}
public static readonly PropertyInfo<DateTime?> StartedProperty = RegisterProperty<DateTime?>(c => c.Started);
public DateTime? Started
{
get { return GetProperty(StartedProperty); }
set { SetProperty(StartedProperty, value); }
}
public static readonly PropertyInfo<DateTime?> EndedProperty = RegisterProperty<DateTime?>(c => c.Ended);
public DateTime? Ended
{
get { return GetProperty(EndedProperty); }
set { SetProperty(EndedProperty, value); }
}
public static readonly PropertyInfo<string> DescriptionProperty =
RegisterProperty<string>(c => c.Description);
public string Description
{
get { return GetProperty(DescriptionProperty); }
set { SetProperty(DescriptionProperty, value); }
}
public static readonly PropertyInfo<ProjectResources> ResourcesProperty =
RegisterProperty<ProjectResources>(p => p.Resources);
public ProjectResources Resources
{
get { return LazyGetProperty(ResourcesProperty, DataPortal.CreateChild<ProjectResources>); }
private set { LoadProperty(ResourcesProperty, value); }
}
public override string ToString()
{
return Id.ToString();
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(NameProperty));
BusinessRules.AddRule(
new StartDateGTEndDate {
PrimaryProperty = StartedProperty,
AffectedProperties = { EndedProperty } });
BusinessRules.AddRule(
new StartDateGTEndDate {
PrimaryProperty = EndedProperty,
AffectedProperties = { StartedProperty } });
BusinessRules.AddRule(
new Csla.Rules.CommonRules.IsInRole(
Csla.Rules.AuthorizationActions.WriteProperty,
NameProperty,
"ProjectManager"));
BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, StartedProperty, "ProjectManager"));
BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, EndedProperty, "ProjectManager"));
BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, DescriptionProperty, "ProjectManager"));
BusinessRules.AddRule(new NoDuplicateResource { PrimaryProperty = ResourcesProperty });
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static void AddObjectAuthorizationRules()
{
Csla.Rules.BusinessRules.AddRule(
typeof(ProjectEdit),
new Csla.Rules.CommonRules.IsInRole(
Csla.Rules.AuthorizationActions.CreateObject,
"ProjectManager"));
Csla.Rules.BusinessRules.AddRule(typeof(ProjectEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.EditObject, "ProjectManager"));
Csla.Rules.BusinessRules.AddRule(typeof(ProjectEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.DeleteObject, "ProjectManager", "Administrator"));
}
protected override void OnChildChanged(Csla.Core.ChildChangedEventArgs e)
{
if (e.ChildObject is ProjectResources)
{
BusinessRules.CheckRules(ResourcesProperty);
OnPropertyChanged(ResourcesProperty);
}
base.OnChildChanged(e);
}
private class NoDuplicateResource : Csla.Rules.BusinessRule
{
protected override void Execute(Csla.Rules.RuleContext context)
{
var target = (ProjectEdit)context.Target;
foreach (var item in target.Resources)
{
var count = target.Resources.Count(r => r.ResourceId == item.ResourceId);
if (count > 1)
{
context.AddErrorResult("Duplicate resources not allowed");
return;
}
}
}
}
private class StartDateGTEndDate : Csla.Rules.BusinessRule
{
protected override void Execute(Csla.Rules.RuleContext context)
{
var target = (ProjectEdit)context.Target;
var started = target.ReadProperty(StartedProperty);
var ended = target.ReadProperty(EndedProperty);
if (started.HasValue && ended.HasValue && started > ended || !started.HasValue && ended.HasValue)
context.AddErrorResult("Start date can't be after end date");
}
}
public static void NewProject(EventHandler<DataPortalResult<ProjectEdit>> callback)
{
ProjectGetter.CreateNewProject((o, e) =>
{
callback(o, new DataPortalResult<ProjectEdit>(e.Object.Project, e.Error, null));
});
}
public static void GetProject(int id, EventHandler<DataPortalResult<ProjectEdit>> callback)
{
ProjectGetter.GetExistingProject(id, (o, e) =>
{
callback(o, new DataPortalResult<ProjectEdit>(e.Object.Project, e.Error, null));
});
}
public static void Exists(int id, Action<bool> result)
{
var cmd = new ProjectExistsCommand(id);
DataPortal.BeginExecute<ProjectExistsCommand>(cmd, (o, e) =>
{
if (e.Error != null)
throw e.Error;
else
result(e.Object.ProjectExists);
});
}
public static void DeleteProject(int id, EventHandler<DataPortalResult<ProjectEdit>> callback)
{
DataPortal.BeginDelete<ProjectEdit>(id, callback);
}
public async static System.Threading.Tasks.Task<ProjectEdit> NewProjectAsync()
{
return await DataPortal.CreateAsync<ProjectEdit>();
}
public async static System.Threading.Tasks.Task<ProjectEdit> GetProjectAsync(int id)
{
return await DataPortal.FetchAsync<ProjectEdit>(id);
}
#if FULL_DOTNET
public static ProjectEdit NewProject()
{
return DataPortal.Create<ProjectEdit>();
}
public static ProjectEdit GetProject(int id)
{
return DataPortal.Fetch<ProjectEdit>(id);
}
public static void DeleteProject(int id)
{
DataPortal.Delete<ProjectEdit>(id);
}
public static bool Exists(int id)
{
var cmd = new ProjectExistsCommand(id);
cmd = DataPortal.Execute<ProjectExistsCommand>(cmd);
return cmd.ProjectExists;
}
[RunLocal]
protected override void DataPortal_Create()
{
base.DataPortal_Create();
}
private void DataPortal_Fetch(int id)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>();
var data = dal.Fetch(id);
using (BypassPropertyChecks)
{
Id = data.Id;
Name = data.Name;
Description = data.Description;
Started = data.Started;
Ended = data.Ended;
TimeStamp = data.LastChanged;
Resources = DataPortal.FetchChild<ProjectResources>(id);
}
}
}
protected override void DataPortal_Insert()
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>();
using (BypassPropertyChecks)
{
var item = new ProjectTracker.Dal.ProjectDto
{
Name = this.Name,
Description = this.Description,
Started = this.Started,
Ended = this.Ended
};
dal.Insert(item);
Id = item.Id;
TimeStamp = item.LastChanged;
}
FieldManager.UpdateChildren(this);
}
}
protected override void DataPortal_Update()
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>();
using (BypassPropertyChecks)
{
var item = new ProjectTracker.Dal.ProjectDto
{
Id = this.Id,
Name = this.Name,
Description = this.Description,
Started = this.Started,
Ended = this.Ended,
LastChanged = this.TimeStamp
};
dal.Update(item);
TimeStamp = item.LastChanged;
}
FieldManager.UpdateChildren(this);
}
}
protected override void DataPortal_DeleteSelf()
{
using (BypassPropertyChecks)
DataPortal_Delete(this.Id);
}
private void DataPortal_Delete(int id)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
Resources.Clear();
FieldManager.UpdateChildren(this);
var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>();
dal.Delete(id);
}
}
#endif
}
}
| |
#region Copyright notice and license
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System.IO;
using Microsoft.Build.Framework;
using Moq;
using NUnit.Framework;
namespace Grpc.Tools.Tests
{
public class ProtoCompileCommandLineGeneratorTest : ProtoCompileBasicTest
{
[SetUp]
public new void SetUp()
{
_task.Generator = "csharp";
_task.OutputDir = "outdir";
_task.Protobuf = Utils.MakeSimpleItems("a.proto");
}
void ExecuteExpectSuccess()
{
_mockEngine
.Setup(me => me.LogErrorEvent(It.IsAny<BuildErrorEventArgs>()))
.Callback((BuildErrorEventArgs e) =>
Assert.Fail($"Error logged by build engine:\n{e.Message}"));
bool result = _task.Execute();
Assert.IsTrue(result);
}
[Test]
public void MinimalCompile()
{
ExecuteExpectSuccess();
Assert.That(_task.LastPathToTool, Does.Match(@"protoc(.exe)?$"));
Assert.That(_task.LastResponseFile, Is.EqualTo(new[] {
"--csharp_out=outdir", "--error_format=msvs", "a.proto" }));
}
[Test]
public void CompileTwoFiles()
{
_task.Protobuf = Utils.MakeSimpleItems("a.proto", "foo/b.proto");
ExecuteExpectSuccess();
Assert.That(_task.LastResponseFile, Is.EqualTo(new[] {
"--csharp_out=outdir", "--error_format=msvs", "a.proto", "foo/b.proto" }));
}
[Test]
public void CompileWithProtoPaths()
{
_task.ProtoPath = new[] { "/path1", "/path2" };
ExecuteExpectSuccess();
Assert.That(_task.LastResponseFile, Is.EqualTo(new[] {
"--csharp_out=outdir", "--proto_path=/path1",
"--proto_path=/path2", "--error_format=msvs", "a.proto" }));
}
[TestCase("Cpp")]
[TestCase("CSharp")]
[TestCase("Java")]
[TestCase("Javanano")]
[TestCase("Js")]
[TestCase("Objc")]
[TestCase("Php")]
[TestCase("Python")]
[TestCase("Ruby")]
public void CompileWithOptions(string gen)
{
_task.Generator = gen;
_task.OutputOptions = new[] { "foo", "bar" };
ExecuteExpectSuccess();
gen = gen.ToLowerInvariant();
Assert.That(_task.LastResponseFile, Is.EqualTo(new[] {
$"--{gen}_out=outdir", $"--{gen}_opt=foo,bar", "--error_format=msvs", "a.proto" }));
}
[Test]
public void OutputDependencyFile()
{
_task.DependencyOut = "foo/my.protodep";
// Task fails trying to read the non-generated file; we ignore that.
_task.Execute();
Assert.That(_task.LastResponseFile,
Does.Contain("--dependency_out=foo/my.protodep"));
}
[Test]
public void OutputDependencyWithProtoDepDir()
{
_task.ProtoDepDir = "foo";
// Task fails trying to read the non-generated file; we ignore that.
_task.Execute();
Assert.That(_task.LastResponseFile,
Has.One.Match(@"^--dependency_out=foo[/\\].+_a.protodep$"));
}
[Test]
public void GenerateGrpc()
{
_task.GrpcPluginExe = "/foo/grpcgen";
ExecuteExpectSuccess();
Assert.That(_task.LastResponseFile, Is.SupersetOf(new[] {
"--csharp_out=outdir", "--grpc_out=outdir",
"--plugin=protoc-gen-grpc=/foo/grpcgen" }));
}
[Test]
public void GenerateGrpcWithOutDir()
{
_task.GrpcPluginExe = "/foo/grpcgen";
_task.GrpcOutputDir = "gen-out";
ExecuteExpectSuccess();
Assert.That(_task.LastResponseFile, Is.SupersetOf(new[] {
"--csharp_out=outdir", "--grpc_out=gen-out" }));
}
[Test]
public void GenerateGrpcWithOptions()
{
_task.GrpcPluginExe = "/foo/grpcgen";
_task.GrpcOutputOptions = new[] { "baz", "quux" };
ExecuteExpectSuccess();
Assert.That(_task.LastResponseFile,
Does.Contain("--grpc_opt=baz,quux"));
}
[Test]
public void AdditionalProtocArguments()
{
_task.AdditionalProtocArguments = new[] { "--experimental_allow_proto3_optional" };
ExecuteExpectSuccess();
Assert.That(_task.LastResponseFile,
Does.Contain("--experimental_allow_proto3_optional"));
}
[Test]
public void DirectoryArgumentsSlashTrimmed()
{
_task.GrpcPluginExe = "/foo/grpcgen";
_task.GrpcOutputDir = "gen-out/";
_task.OutputDir = "outdir/";
_task.ProtoPath = new[] { "/path1/", "/path2/" };
ExecuteExpectSuccess();
Assert.That(_task.LastResponseFile, Is.SupersetOf(new[] {
"--proto_path=/path1", "--proto_path=/path2",
"--csharp_out=outdir", "--grpc_out=gen-out" }));
}
[TestCase(".", ".")]
[TestCase("/", "/")]
[TestCase("//", "/")]
[TestCase("/foo/", "/foo")]
[TestCase("/foo", "/foo")]
[TestCase("foo/", "foo")]
[TestCase("foo//", "foo")]
[TestCase("foo/\\", "foo")]
[TestCase("foo\\/", "foo")]
[TestCase("C:\\foo", "C:\\foo")]
[TestCase("C:", "C:")]
[TestCase("C:\\", "C:\\")]
[TestCase("C:\\\\", "C:\\")]
public void DirectorySlashTrimmingCases(string given, string expect)
{
if (Path.DirectorySeparatorChar == '/')
expect = expect.Replace('\\', '/');
_task.OutputDir = given;
ExecuteExpectSuccess();
Assert.That(_task.LastResponseFile,
Does.Contain("--csharp_out=" + expect));
}
[TestCase(
"../Protos/greet.proto(19) : warning in column=5 : warning : When enum name is stripped and label is PascalCased (Zero) this value label conflicts with Zero.",
"../Protos/greet.proto",
19,
5,
"warning : When enum name is stripped and label is PascalCased (Zero) this value label conflicts with Zero.")]
[TestCase(
"../Protos/greet.proto: warning: Import google/protobuf/empty.proto but not used.",
"../Protos/greet.proto",
0,
0,
"Import google/protobuf/empty.proto but not used.")]
[TestCase("../Protos/greet.proto(14) : error in column=10: \"name\" is already defined in \"Greet.HelloRequest\".", null, 0, 0, null)]
[TestCase("../Protos/greet.proto: Import \"google / protobuf / empty.proto\" was listed twice.", null, 0, 0, null)]
public void WarningsParsed(string stderr, string file, int line, int col, string message)
{
_task.StdErrMessages.Add(stderr);
_mockEngine
.Setup(me => me.LogWarningEvent(It.IsAny<BuildWarningEventArgs>()))
.Callback((BuildWarningEventArgs e) => {
if (file != null)
{
Assert.AreEqual(file, e.File);
Assert.AreEqual(line, e.LineNumber);
Assert.AreEqual(col, e.ColumnNumber);
Assert.AreEqual(message, e.Message);
}
else
{
Assert.Fail($"Error logged by build engine:\n{e.Message}");
}
});
bool result = _task.Execute();
Assert.IsFalse(result);
}
[TestCase(
"../Protos/greet.proto(14) : error in column=10: \"name\" is already defined in \"Greet.HelloRequest\".",
"../Protos/greet.proto",
14,
10,
"\"name\" is already defined in \"Greet.HelloRequest\".")]
[TestCase(
"../Protos/greet.proto: Import \"google / protobuf / empty.proto\" was listed twice.",
"../Protos/greet.proto",
0,
0,
"Import \"google / protobuf / empty.proto\" was listed twice.")]
[TestCase("../Protos/greet.proto(19) : warning in column=5 : warning : When enum name is stripped and label is PascalCased (Zero) this value label conflicts with Zero.", null, 0, 0, null)]
[TestCase("../Protos/greet.proto: warning: Import google/protobuf/empty.proto but not used.", null, 0, 0, null)]
public void ErrorsParsed(string stderr, string file, int line, int col, string message)
{
_task.StdErrMessages.Add(stderr);
_mockEngine
.Setup(me => me.LogErrorEvent(It.IsAny<BuildErrorEventArgs>()))
.Callback((BuildErrorEventArgs e) => {
if (file != null)
{
Assert.AreEqual(file, e.File);
Assert.AreEqual(line, e.LineNumber);
Assert.AreEqual(col, e.ColumnNumber);
Assert.AreEqual(message, e.Message);
}
else
{
// Ignore expected error
// "protoc/protoc.exe" existed with code -1.
if (!e.Message.EndsWith("exited with code -1."))
{
Assert.Fail($"Error logged by build engine:\n{e.Message}");
}
}
});
bool result = _task.Execute();
Assert.IsFalse(result);
}
};
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Achartengine {
// Metadata.xml XPath class reference: path="/api/package[@name='org.achartengine']/class[@name='TouchHandler']"
[global::Android.Runtime.Register ("org/achartengine/TouchHandler", DoNotGenerateAcw=true)]
public partial class TouchHandler : global::Java.Lang.Object, global::Org.Achartengine.ITouchHandler {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/achartengine/TouchHandler", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (TouchHandler); }
}
protected TouchHandler (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Lorg_achartengine_GraphicalView_Lorg_achartengine_chart_AbstractChart_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.achartengine']/class[@name='TouchHandler']/constructor[@name='TouchHandler' and count(parameter)=2 and parameter[1][@type='org.achartengine.GraphicalView'] and parameter[2][@type='org.achartengine.chart.AbstractChart']]"
[Register (".ctor", "(Lorg/achartengine/GraphicalView;Lorg/achartengine/chart/AbstractChart;)V", "")]
public TouchHandler (global::Org.Achartengine.GraphicalView p0, global::Org.Achartengine.Chart.AbstractChart p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (TouchHandler)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/achartengine/GraphicalView;Lorg/achartengine/chart/AbstractChart;)V", new JValue (p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/achartengine/GraphicalView;Lorg/achartengine/chart/AbstractChart;)V", new JValue (p0), new JValue (p1));
return;
}
if (id_ctor_Lorg_achartengine_GraphicalView_Lorg_achartengine_chart_AbstractChart_ == IntPtr.Zero)
id_ctor_Lorg_achartengine_GraphicalView_Lorg_achartengine_chart_AbstractChart_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/achartengine/GraphicalView;Lorg/achartengine/chart/AbstractChart;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_achartengine_GraphicalView_Lorg_achartengine_chart_AbstractChart_, new JValue (p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_achartengine_GraphicalView_Lorg_achartengine_chart_AbstractChart_, new JValue (p0), new JValue (p1));
}
static Delegate cb_addPanListener_Lorg_achartengine_tools_PanListener_;
#pragma warning disable 0169
static Delegate GetAddPanListener_Lorg_achartengine_tools_PanListener_Handler ()
{
if (cb_addPanListener_Lorg_achartengine_tools_PanListener_ == null)
cb_addPanListener_Lorg_achartengine_tools_PanListener_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_AddPanListener_Lorg_achartengine_tools_PanListener_);
return cb_addPanListener_Lorg_achartengine_tools_PanListener_;
}
static void n_AddPanListener_Lorg_achartengine_tools_PanListener_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Achartengine.TouchHandler __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.TouchHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Achartengine.Tools.IPanListener p0 = (global::Org.Achartengine.Tools.IPanListener)global::Java.Lang.Object.GetObject<global::Org.Achartengine.Tools.IPanListener> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.AddPanListener (p0);
}
#pragma warning restore 0169
static IntPtr id_addPanListener_Lorg_achartengine_tools_PanListener_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine']/class[@name='TouchHandler']/method[@name='addPanListener' and count(parameter)=1 and parameter[1][@type='org.achartengine.tools.PanListener']]"
[Register ("addPanListener", "(Lorg/achartengine/tools/PanListener;)V", "GetAddPanListener_Lorg_achartengine_tools_PanListener_Handler")]
public virtual void AddPanListener (global::Org.Achartengine.Tools.IPanListener p0)
{
if (id_addPanListener_Lorg_achartengine_tools_PanListener_ == IntPtr.Zero)
id_addPanListener_Lorg_achartengine_tools_PanListener_ = JNIEnv.GetMethodID (class_ref, "addPanListener", "(Lorg/achartengine/tools/PanListener;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_addPanListener_Lorg_achartengine_tools_PanListener_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_addPanListener_Lorg_achartengine_tools_PanListener_, new JValue (p0));
}
static Delegate cb_addZoomListener_Lorg_achartengine_tools_ZoomListener_;
#pragma warning disable 0169
static Delegate GetAddZoomListener_Lorg_achartengine_tools_ZoomListener_Handler ()
{
if (cb_addZoomListener_Lorg_achartengine_tools_ZoomListener_ == null)
cb_addZoomListener_Lorg_achartengine_tools_ZoomListener_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_AddZoomListener_Lorg_achartengine_tools_ZoomListener_);
return cb_addZoomListener_Lorg_achartengine_tools_ZoomListener_;
}
static void n_AddZoomListener_Lorg_achartengine_tools_ZoomListener_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Achartengine.TouchHandler __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.TouchHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Achartengine.Tools.IZoomListener p0 = (global::Org.Achartengine.Tools.IZoomListener)global::Java.Lang.Object.GetObject<global::Org.Achartengine.Tools.IZoomListener> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.AddZoomListener (p0);
}
#pragma warning restore 0169
static IntPtr id_addZoomListener_Lorg_achartengine_tools_ZoomListener_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine']/class[@name='TouchHandler']/method[@name='addZoomListener' and count(parameter)=1 and parameter[1][@type='org.achartengine.tools.ZoomListener']]"
[Register ("addZoomListener", "(Lorg/achartengine/tools/ZoomListener;)V", "GetAddZoomListener_Lorg_achartengine_tools_ZoomListener_Handler")]
public virtual void AddZoomListener (global::Org.Achartengine.Tools.IZoomListener p0)
{
if (id_addZoomListener_Lorg_achartengine_tools_ZoomListener_ == IntPtr.Zero)
id_addZoomListener_Lorg_achartengine_tools_ZoomListener_ = JNIEnv.GetMethodID (class_ref, "addZoomListener", "(Lorg/achartengine/tools/ZoomListener;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_addZoomListener_Lorg_achartengine_tools_ZoomListener_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_addZoomListener_Lorg_achartengine_tools_ZoomListener_, new JValue (p0));
}
static Delegate cb_handleTouch_Landroid_view_MotionEvent_;
#pragma warning disable 0169
static Delegate GetHandleTouch_Landroid_view_MotionEvent_Handler ()
{
if (cb_handleTouch_Landroid_view_MotionEvent_ == null)
cb_handleTouch_Landroid_view_MotionEvent_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool>) n_HandleTouch_Landroid_view_MotionEvent_);
return cb_handleTouch_Landroid_view_MotionEvent_;
}
static bool n_HandleTouch_Landroid_view_MotionEvent_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Achartengine.TouchHandler __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.TouchHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Android.Views.MotionEvent p0 = global::Java.Lang.Object.GetObject<global::Android.Views.MotionEvent> (native_p0, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.HandleTouch (p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_handleTouch_Landroid_view_MotionEvent_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine']/class[@name='TouchHandler']/method[@name='handleTouch' and count(parameter)=1 and parameter[1][@type='android.view.MotionEvent']]"
[Register ("handleTouch", "(Landroid/view/MotionEvent;)Z", "GetHandleTouch_Landroid_view_MotionEvent_Handler")]
public virtual bool HandleTouch (global::Android.Views.MotionEvent p0)
{
if (id_handleTouch_Landroid_view_MotionEvent_ == IntPtr.Zero)
id_handleTouch_Landroid_view_MotionEvent_ = JNIEnv.GetMethodID (class_ref, "handleTouch", "(Landroid/view/MotionEvent;)Z");
bool __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.CallBooleanMethod (Handle, id_handleTouch_Landroid_view_MotionEvent_, new JValue (p0));
else
__ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, id_handleTouch_Landroid_view_MotionEvent_, new JValue (p0));
return __ret;
}
static Delegate cb_removePanListener_Lorg_achartengine_tools_PanListener_;
#pragma warning disable 0169
static Delegate GetRemovePanListener_Lorg_achartengine_tools_PanListener_Handler ()
{
if (cb_removePanListener_Lorg_achartengine_tools_PanListener_ == null)
cb_removePanListener_Lorg_achartengine_tools_PanListener_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_RemovePanListener_Lorg_achartengine_tools_PanListener_);
return cb_removePanListener_Lorg_achartengine_tools_PanListener_;
}
static void n_RemovePanListener_Lorg_achartengine_tools_PanListener_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Achartengine.TouchHandler __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.TouchHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Achartengine.Tools.IPanListener p0 = (global::Org.Achartengine.Tools.IPanListener)global::Java.Lang.Object.GetObject<global::Org.Achartengine.Tools.IPanListener> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.RemovePanListener (p0);
}
#pragma warning restore 0169
static IntPtr id_removePanListener_Lorg_achartengine_tools_PanListener_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine']/class[@name='TouchHandler']/method[@name='removePanListener' and count(parameter)=1 and parameter[1][@type='org.achartengine.tools.PanListener']]"
[Register ("removePanListener", "(Lorg/achartengine/tools/PanListener;)V", "GetRemovePanListener_Lorg_achartengine_tools_PanListener_Handler")]
public virtual void RemovePanListener (global::Org.Achartengine.Tools.IPanListener p0)
{
if (id_removePanListener_Lorg_achartengine_tools_PanListener_ == IntPtr.Zero)
id_removePanListener_Lorg_achartengine_tools_PanListener_ = JNIEnv.GetMethodID (class_ref, "removePanListener", "(Lorg/achartengine/tools/PanListener;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_removePanListener_Lorg_achartengine_tools_PanListener_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_removePanListener_Lorg_achartengine_tools_PanListener_, new JValue (p0));
}
static Delegate cb_removeZoomListener_Lorg_achartengine_tools_ZoomListener_;
#pragma warning disable 0169
static Delegate GetRemoveZoomListener_Lorg_achartengine_tools_ZoomListener_Handler ()
{
if (cb_removeZoomListener_Lorg_achartengine_tools_ZoomListener_ == null)
cb_removeZoomListener_Lorg_achartengine_tools_ZoomListener_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_RemoveZoomListener_Lorg_achartengine_tools_ZoomListener_);
return cb_removeZoomListener_Lorg_achartengine_tools_ZoomListener_;
}
static void n_RemoveZoomListener_Lorg_achartengine_tools_ZoomListener_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Achartengine.TouchHandler __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.TouchHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Achartengine.Tools.IZoomListener p0 = (global::Org.Achartengine.Tools.IZoomListener)global::Java.Lang.Object.GetObject<global::Org.Achartengine.Tools.IZoomListener> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.RemoveZoomListener (p0);
}
#pragma warning restore 0169
static IntPtr id_removeZoomListener_Lorg_achartengine_tools_ZoomListener_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine']/class[@name='TouchHandler']/method[@name='removeZoomListener' and count(parameter)=1 and parameter[1][@type='org.achartengine.tools.ZoomListener']]"
[Register ("removeZoomListener", "(Lorg/achartengine/tools/ZoomListener;)V", "GetRemoveZoomListener_Lorg_achartengine_tools_ZoomListener_Handler")]
public virtual void RemoveZoomListener (global::Org.Achartengine.Tools.IZoomListener p0)
{
if (id_removeZoomListener_Lorg_achartengine_tools_ZoomListener_ == IntPtr.Zero)
id_removeZoomListener_Lorg_achartengine_tools_ZoomListener_ = JNIEnv.GetMethodID (class_ref, "removeZoomListener", "(Lorg/achartengine/tools/ZoomListener;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_removeZoomListener_Lorg_achartengine_tools_ZoomListener_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_removeZoomListener_Lorg_achartengine_tools_ZoomListener_, new JValue (p0));
}
#region "Event implementation for Org.Achartengine.Tools.IPanListener"
public event EventHandler Pan {
add {
global::Java.Interop.EventHelper.AddEventHandler<global::Org.Achartengine.Tools.IPanListener, global::Org.Achartengine.Tools.IPanListenerImplementor>(
ref weak_implementor_AddPanListener,
__CreateIPanListenerImplementor,
AddPanListener,
__h => __h.Handler += value);
}
remove {
global::Java.Interop.EventHelper.RemoveEventHandler<global::Org.Achartengine.Tools.IPanListener, global::Org.Achartengine.Tools.IPanListenerImplementor>(
ref weak_implementor_AddPanListener,
global::Org.Achartengine.Tools.IPanListenerImplementor.__IsEmpty,
RemovePanListener,
__h => __h.Handler -= value);
}
}
WeakReference weak_implementor_AddPanListener;
global::Org.Achartengine.Tools.IPanListenerImplementor __CreateIPanListenerImplementor ()
{
return new global::Org.Achartengine.Tools.IPanListenerImplementor (this);
}
#endregion
#region "Event implementation for Org.Achartengine.Tools.IZoomListener"
public event EventHandler<global::Org.Achartengine.Tools.ZoomAppliedEventArgs> ZoomApplied {
add {
global::Java.Interop.EventHelper.AddEventHandler<global::Org.Achartengine.Tools.IZoomListener, global::Org.Achartengine.Tools.IZoomListenerImplementor>(
ref weak_implementor_AddZoomListener,
__CreateIZoomListenerImplementor,
AddZoomListener,
__h => __h.ZoomAppliedHandler += value);
}
remove {
global::Java.Interop.EventHelper.RemoveEventHandler<global::Org.Achartengine.Tools.IZoomListener, global::Org.Achartengine.Tools.IZoomListenerImplementor>(
ref weak_implementor_AddZoomListener,
global::Org.Achartengine.Tools.IZoomListenerImplementor.__IsEmpty,
RemoveZoomListener,
__h => __h.ZoomAppliedHandler -= value);
}
}
public event EventHandler ZoomReset {
add {
global::Java.Interop.EventHelper.AddEventHandler<global::Org.Achartengine.Tools.IZoomListener, global::Org.Achartengine.Tools.IZoomListenerImplementor>(
ref weak_implementor_AddZoomListener,
__CreateIZoomListenerImplementor,
AddZoomListener,
__h => __h.ZoomResetHandler += value);
}
remove {
global::Java.Interop.EventHelper.RemoveEventHandler<global::Org.Achartengine.Tools.IZoomListener, global::Org.Achartengine.Tools.IZoomListenerImplementor>(
ref weak_implementor_AddZoomListener,
global::Org.Achartengine.Tools.IZoomListenerImplementor.__IsEmpty,
RemoveZoomListener,
__h => __h.ZoomResetHandler -= value);
}
}
WeakReference weak_implementor_AddZoomListener;
global::Org.Achartengine.Tools.IZoomListenerImplementor __CreateIZoomListenerImplementor ()
{
return new global::Org.Achartengine.Tools.IZoomListenerImplementor (this);
}
#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.Diagnostics;
using ILCompiler.DependencyAnalysis.X64;
using Internal.TypeSystem;
namespace ILCompiler.DependencyAnalysis
{
/// <summary>
/// X64 specific portions of ReadyToRunHelperNode
/// </summary>
public partial class ReadyToRunHelperNode
{
protected override void EmitCode(NodeFactory factory, ref X64Emitter encoder, bool relocsOnly)
{
switch (Id)
{
case ReadyToRunHelperId.NewHelper:
{
TypeDesc target = (TypeDesc)Target;
encoder.EmitLEAQ(encoder.TargetRegister.Arg0, factory.ConstructedTypeSymbol(target));
encoder.EmitJMP(factory.ExternSymbol(JitHelper.GetNewObjectHelperForType(target)));
}
break;
case ReadyToRunHelperId.VirtualCall:
{
MethodDesc targetMethod = (MethodDesc)Target;
Debug.Assert(!targetMethod.OwningType.IsInterface);
AddrMode loadFromThisPtr = new AddrMode(encoder.TargetRegister.Arg0, null, 0, 0, AddrModeSize.Int64);
encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromThisPtr);
int pointerSize = factory.Target.PointerSize;
int slot = 0;
if (!relocsOnly)
{
slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod);
Debug.Assert(slot != -1);
}
AddrMode jmpAddrMode = new AddrMode(encoder.TargetRegister.Result, null, EETypeNode.GetVTableOffset(pointerSize) + (slot * pointerSize), 0, AddrModeSize.Int64);
encoder.EmitJmpToAddrMode(ref jmpAddrMode);
}
break;
case ReadyToRunHelperId.IsInstanceOf:
{
TypeDesc target = (TypeDesc)Target;
encoder.EmitLEAQ(encoder.TargetRegister.Arg1, factory.NecessaryTypeSymbol(target));
encoder.EmitJMP(factory.ExternSymbol(JitHelper.GetCastingHelperNameForType(target, false)));
}
break;
case ReadyToRunHelperId.CastClass:
{
TypeDesc target = (TypeDesc)Target;
encoder.EmitLEAQ(encoder.TargetRegister.Arg1, factory.NecessaryTypeSymbol(target));
encoder.EmitJMP(factory.ExternSymbol(JitHelper.GetCastingHelperNameForType(target, true)));
}
break;
case ReadyToRunHelperId.NewArr1:
{
TypeDesc target = (TypeDesc)Target;
// TODO: Swap argument order instead
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg0);
encoder.EmitLEAQ(encoder.TargetRegister.Arg0, factory.ConstructedTypeSymbol(target));
encoder.EmitJMP(factory.ExternSymbol(JitHelper.GetNewArrayHelperForType(target)));
}
break;
case ReadyToRunHelperId.GetNonGCStaticBase:
{
MetadataType target = (MetadataType)Target;
bool hasLazyStaticConstructor = factory.TypeSystemContext.HasLazyStaticConstructor(target);
encoder.EmitLEAQ(encoder.TargetRegister.Result, factory.TypeNonGCStaticsSymbol(target));
if (!hasLazyStaticConstructor)
{
encoder.EmitRET();
}
else
{
// We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region.
encoder.EmitLEAQ(encoder.TargetRegister.Arg0, factory.TypeNonGCStaticsSymbol(target), -NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target));
AddrMode initialized = new AddrMode(encoder.TargetRegister.Arg0, null, factory.Target.PointerSize, 0, AddrModeSize.Int32);
encoder.EmitCMP(ref initialized, 1);
encoder.EmitRETIfEqual();
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result);
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnNonGCStaticBase));
}
}
break;
case ReadyToRunHelperId.GetThreadStaticBase:
{
MetadataType target = (MetadataType)Target;
encoder.EmitLEAQ(encoder.TargetRegister.Arg2, factory.TypeThreadStaticIndex(target));
// First arg: address of the TypeManager slot that provides the helper with
// information about module index and the type manager instance (which is used
// for initialization on first access).
AddrMode loadFromArg2 = new AddrMode(encoder.TargetRegister.Arg2, null, 0, 0, AddrModeSize.Int64);
encoder.EmitMOV(encoder.TargetRegister.Arg0, ref loadFromArg2);
// Second arg: index of the type in the ThreadStatic section of the modules
AddrMode loadFromArg2AndDelta = new AddrMode(encoder.TargetRegister.Arg2, null, factory.Target.PointerSize, 0, AddrModeSize.Int64);
encoder.EmitMOV(encoder.TargetRegister.Arg1, ref loadFromArg2AndDelta);
if (!factory.TypeSystemContext.HasLazyStaticConstructor(target))
{
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.GetThreadStaticBaseForType));
}
else
{
encoder.EmitLEAQ(encoder.TargetRegister.Arg2, factory.TypeNonGCStaticsSymbol(target), - NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target));
// TODO: performance optimization - inline the check verifying whether we need to trigger the cctor
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnThreadStaticBase));
}
}
break;
case ReadyToRunHelperId.GetGCStaticBase:
{
MetadataType target = (MetadataType)Target;
encoder.EmitLEAQ(encoder.TargetRegister.Result, factory.TypeGCStaticsSymbol(target));
AddrMode loadFromRax = new AddrMode(encoder.TargetRegister.Result, null, 0, 0, AddrModeSize.Int64);
encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromRax);
encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromRax);
if (!factory.TypeSystemContext.HasLazyStaticConstructor(target))
{
encoder.EmitRET();
}
else
{
// We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region.
encoder.EmitLEAQ(encoder.TargetRegister.Arg0, factory.TypeNonGCStaticsSymbol(target), -NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target));
AddrMode initialized = new AddrMode(encoder.TargetRegister.Arg0, null, factory.Target.PointerSize, 0, AddrModeSize.Int32);
encoder.EmitCMP(ref initialized, 1);
encoder.EmitRETIfEqual();
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result);
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnGCStaticBase));
}
}
break;
case ReadyToRunHelperId.DelegateCtor:
{
DelegateCreationInfo target = (DelegateCreationInfo)Target;
if (target.TargetNeedsVTableLookup)
{
AddrMode loadFromThisPtr = new AddrMode(encoder.TargetRegister.Arg1, null, 0, 0, AddrModeSize.Int64);
encoder.EmitMOV(encoder.TargetRegister.Arg2, ref loadFromThisPtr);
int slot = 0;
if (!relocsOnly)
slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, target.TargetMethod);
Debug.Assert(slot != -1);
AddrMode loadFromSlot = new AddrMode(encoder.TargetRegister.Arg2, null, EETypeNode.GetVTableOffset(factory.Target.PointerSize) + (slot * factory.Target.PointerSize), 0, AddrModeSize.Int64);
encoder.EmitMOV(encoder.TargetRegister.Arg2, ref loadFromSlot);
}
else
{
ISymbolNode targetMethodNode = target.GetTargetNode(factory);
encoder.EmitLEAQ(encoder.TargetRegister.Arg2, target.GetTargetNode(factory));
}
if (target.Thunk != null)
{
Debug.Assert(target.Constructor.Method.Signature.Length == 3);
encoder.EmitLEAQ(encoder.TargetRegister.Arg3, target.Thunk);
}
else
{
Debug.Assert(target.Constructor.Method.Signature.Length == 2);
}
encoder.EmitJMP(target.Constructor);
}
break;
case ReadyToRunHelperId.ResolveVirtualFunction:
{
MethodDesc targetMethod = (MethodDesc)Target;
if (targetMethod.OwningType.IsInterface)
{
encoder.EmitLEAQ(encoder.TargetRegister.Arg1, factory.InterfaceDispatchCell(targetMethod));
encoder.EmitJMP(factory.ExternSymbol("RhpResolveInterfaceMethod"));
}
else
{
if (relocsOnly)
break;
AddrMode loadFromThisPtr = new AddrMode(encoder.TargetRegister.Arg0, null, 0, 0, AddrModeSize.Int64);
encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromThisPtr);
int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod);
Debug.Assert(slot != -1);
AddrMode loadFromSlot = new AddrMode(encoder.TargetRegister.Result, null, EETypeNode.GetVTableOffset(factory.Target.PointerSize) + (slot * factory.Target.PointerSize), 0, AddrModeSize.Int64);
encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromSlot);
encoder.EmitRET();
}
}
break;
default:
throw new NotImplementedException();
}
}
}
}
| |
using System;
using System.Collections;
using System.Data.SqlClient;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.Utils.Win;
using DevExpress.XtraBars.Forms;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Ribbon.Helpers;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Popup;
using bv.common.Core;
using bv.common.Resources;
using bv.winclient.BasePanel;
using bv.winclient.Core;
using bv.winclient.Layout;
using bv.winclient.Localization;
using eidss.gis.Tools.ToolForms;
using eidss.model.Core;
using eidss.model.Core.Security;
using eidss.model.Resources;
namespace eidss.main.Autolock
{
public partial class AutoLockForm
{
private bool m_AllowToClose;
public void btOk_Click(Object sender, EventArgs e)
{
int res;
//If (Me.tbConfPass.Text.Trim() <> EIDSSUser.Current.Password) Then
try
{
var sm = new EidssSecurityManager();
var user = EidssUserContext.User;
res = sm.LogIn(user.Organization, user.LoginName, tbConfPass.Text);
}
catch (Exception ex)
{
string errMessage;
if (SqlExceptionHandler.Handle(ex))
return;
if (ex is SqlException)
{
errMessage = SecurityMessages.GetDBErrorMessage(((SqlException)ex).Number, null, null);
}
else
{
errMessage = SecurityMessages.GetDBErrorMessage(0, null, null);
}
ErrorForm.ShowErrorDirect(errMessage, ex);
return;
}
if (res != 0 && res != 9)
{
ShowError(res);
}
else
{
UnlockProgram();
}
}
public void AutoLockForm_Load(Object sender, EventArgs e)
{
PlaceCenterWindow();
ShowWindows(false);
Application.Idle += UpdateLangIndicators;
tbConfPass.Enter += Control_Enter;
tbConfPass.Leave += Control_Leave;
SystemLanguages.SwitchInputLanguage(m_LastInputLang);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UpdateLangIndicators(object sender, EventArgs e)
{
lbPassLng.Text = Localizer.GetLanguageID(InputLanguage.CurrentInputLanguage.Culture).ToUpperInvariant();
}
private static string m_LastInputLang = "en";
private void Control_Enter(object sender, EventArgs e)
{
SystemLanguages.SwitchInputLanguage(m_LastInputLang);
((TextEdit)sender).SelectAll();
}
private void Control_Leave(object sender, EventArgs e)
{
m_LastInputLang = Localizer.GetLanguageID(InputLanguage.CurrentInputLanguage.Culture);
}
public void ShowError(int res)
{
var err = SecurityMessages.GetLoginErrorMessage(res);
MessageForm.Show(err, BvMessages.Get("Warning"), MessageBoxButtons.OK);
tbConfPass.Text = String.Empty;
tbConfPass.Focus();
}
public void UnlockProgram()
{
ShowWindows(true);
DialogResult = DialogResult.OK;
m_AllowToClose = true;
Close();
}
public void sbLogout_Click(Object sender, EventArgs e)
{
CloseAllWindows();
DialogResult = DialogResult.Cancel;
m_AllowToClose = true;
Close();
}
public void ShowWindows(bool bShow)
{
var formList = new ArrayList(Application.OpenForms);
foreach (Form frm in formList)
{
if (frm is PopupBaseForm
|| frm is GalleryItemImagePopupForm
|| frm is SuperToolTipWindow
|| frm is ToolTipControllerWindow
|| frm is AppMenuForm
|| frm is SubMenuControlForm
|| frm is KeyTipForm
// commented because of bugN 5600
// || frm is DevExpress.XtraPivotGrid.Customization.CustomizationForm
|| frm is InfoForm)
{
if (frm.Visible)
{
frm.Hide();
}
continue;
}
frm.Visible = bShow;
}
}
public void PlaceCenterWindow()
{
Left = (Screen.PrimaryScreen.Bounds.Width - Width) / 2;
Top = (Screen.PrimaryScreen.Bounds.Height - Height) / 2;
}
public void CloseAllWindows()
{
// Close all Detail forms first
for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
{
Form frm = Application.OpenForms[i];
if (frm == null)
{
continue;
}
if (frm.Controls.Count == 0)
{
continue;
}
IApplicationForm ctrl = BaseFormManager.FindChildIApplicationForm(frm);
if (ctrl != null)
{
BaseFormManager.Close(ctrl);
}
}
Application.DoEvents();
BaseFormManager.CloseAll(false);
Application.DoEvents();
}
public void AutoLockForm_FormClosing(Object sender, FormClosingEventArgs e)
{
e.Cancel = Convert.ToBoolean(!m_AllowToClose);
}
public AutoLockForm()
{
// This call is required by the Windows Form Designer.
InitializeComponent();
Icon = BaseFormManager.MainForm.Icon;
LayoutCorrector.ApplySystemFont(this);
lLockMessage.Text = String.Format(EidssMessages.Get("lLockMessage"), EidssUserContext.User.Name);
}
}
}
| |
using System;
using Csla;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERLevel;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C03_Continent_Child (editable child object).<br/>
/// This is a generated base class of <see cref="C03_Continent_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="C02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class C03_Continent_Child : BusinessBase<C03_Continent_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name");
/// <summary>
/// Gets or sets the SubContinents Child Name.
/// </summary>
/// <value>The SubContinents Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
set { SetProperty(Continent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C03_Continent_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C03_Continent_Child"/> object.</returns>
internal static C03_Continent_Child NewC03_Continent_Child()
{
return DataPortal.CreateChild<C03_Continent_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="C03_Continent_Child"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID1">The Continent_ID1 parameter of the C03_Continent_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="C03_Continent_Child"/> object.</returns>
internal static C03_Continent_Child GetC03_Continent_Child(int continent_ID1)
{
return DataPortal.FetchChild<C03_Continent_Child>(continent_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C03_Continent_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C03_Continent_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C03_Continent_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="C03_Continent_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="continent_ID1">The Continent ID1.</param>
protected void Child_Fetch(int continent_ID1)
{
var args = new DataPortalHookArgs(continent_ID1);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var dal = dalManager.GetProvider<IC03_Continent_ChildDal>();
var data = dal.Fetch(continent_ID1);
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads a <see cref="C03_Continent_Child"/> object from the given <see cref="C03_Continent_ChildDto"/>.
/// </summary>
/// <param name="data">The C03_Continent_ChildDto to use.</param>
private void Fetch(C03_Continent_ChildDto data)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, data.Continent_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="C03_Continent_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(C02_Continent parent)
{
var dto = new C03_Continent_ChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IC03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C03_Continent_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(C02_Continent parent)
{
if (!IsDirty)
return;
var dto = new C03_Continent_ChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IC03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="C03_Continent_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(C02_Continent parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IC03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Continent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.EMBinding", Namespace="urn:iControl")]
public partial class ManagementEM : iControlInterface {
public ManagementEM() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// delete_devices
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/EM",
RequestNamespace="urn:iControl:Management/EM", ResponseNamespace="urn:iControl:Management/EM")]
public void delete_devices(
string [] devices
) {
this.Invoke("delete_devices", new object [] {
devices});
}
public System.IAsyncResult Begindelete_devices(string [] devices, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_devices", new object[] {
devices}, callback, asyncState);
}
public void Enddelete_devices(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// discover_devices
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/EM",
RequestNamespace="urn:iControl:Management/EM", ResponseNamespace="urn:iControl:Management/EM")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string discover_devices(
string [] addresses,
string [] usernames,
string [] passwords
) {
object [] results = this.Invoke("discover_devices", new object [] {
addresses,
usernames,
passwords});
return ((string)(results[0]));
}
public System.IAsyncResult Begindiscover_devices(string [] addresses,string [] usernames,string [] passwords, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("discover_devices", new object[] {
addresses,
usernames,
passwords}, callback, asyncState);
}
public string Enddiscover_devices(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_context_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/EM",
RequestNamespace="urn:iControl:Management/EM", ResponseNamespace="urn:iControl:Management/EM")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_context_id(
) {
object [] results = this.Invoke("get_context_id", new object [0]);
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_context_id(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_context_id", new object[0], callback, asyncState);
}
public string Endget_context_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_device_proxy_configuration
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/EM",
RequestNamespace="urn:iControl:Management/EM", ResponseNamespace="urn:iControl:Management/EM")]
public void get_device_proxy_configuration(
out string emSslProxyHost,
out short emSslProxyPort,
out string deviceSslProxyHost,
out short deviceSslProxyPort,
out bool useEmSslProxyForDevice,
out bool deviceProxyEnabled
) {
object [] results = this.Invoke("get_device_proxy_configuration", new object [] {
});
emSslProxyHost = ((string)(results[0]));
emSslProxyPort = ((short)(results[1]));
deviceSslProxyHost = ((string)(results[2]));
deviceSslProxyPort = ((short)(results[3]));
useEmSslProxyForDevice = ((bool)(results[4]));
deviceProxyEnabled = ((bool)(results[5]));
}
public System.IAsyncResult Beginget_device_proxy_configuration(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_device_proxy_configuration", new object[] {
}, callback, asyncState);
}
public void Endget_device_proxy_configuration(System.IAsyncResult asyncResult,
out string emSslProxyHost,
out short emSslProxyPort,
out string deviceSslProxyHost,
out short deviceSslProxyPort,
out bool useEmSslProxyForDevice,
out bool deviceProxyEnabled) {
object [] results = this.EndInvoke(asyncResult);
emSslProxyHost = ((string)(results[0]));
emSslProxyPort = ((short)(results[1]));
deviceSslProxyHost = ((string)(results[2]));
deviceSslProxyPort = ((short)(results[3]));
useEmSslProxyForDevice = ((bool)(results[4]));
deviceProxyEnabled = ((bool)(results[5]));
}
//-----------------------------------------------------------------------
// get_device_token
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/EM",
RequestNamespace="urn:iControl:Management/EM", ResponseNamespace="urn:iControl:Management/EM")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_device_token(
string ip_address
) {
object [] results = this.Invoke("get_device_token", new object [] {
ip_address});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_device_token(string ip_address, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_device_token", new object[] {
ip_address}, callback, asyncState);
}
public string Endget_device_token(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_devices
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/EM",
RequestNamespace="urn:iControl:Management/EM", ResponseNamespace="urn:iControl:Management/EM")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_devices(
) {
object [] results = this.Invoke("get_devices", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_devices(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_devices", new object[0], callback, asyncState);
}
public string [] Endget_devices(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_task_status
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/EM",
RequestNamespace="urn:iControl:Management/EM", ResponseNamespace="urn:iControl:Management/EM")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementEMTaskStatus [] get_task_status(
string [] ids
) {
object [] results = this.Invoke("get_task_status", new object [] {
ids});
return ((ManagementEMTaskStatus [])(results[0]));
}
public System.IAsyncResult Beginget_task_status(string [] ids, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_task_status", new object[] {
ids}, callback, asyncState);
}
public ManagementEMTaskStatus [] Endget_task_status(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementEMTaskStatus [])(results[0]));
}
//-----------------------------------------------------------------------
// sendRequest
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/EM",
RequestNamespace="urn:iControl:Management/EM", ResponseNamespace="urn:iControl:Management/EM")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string sendRequest(
string daemon,
string request
) {
object [] results = this.Invoke("sendRequest", new object [] {
daemon,
request});
return ((string)(results[0]));
}
public System.IAsyncResult BeginsendRequest(string daemon,string request, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("sendRequest", new object[] {
daemon,
request}, callback, asyncState);
}
public string EndsendRequest(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// set_device_context
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/EM",
RequestNamespace="urn:iControl:Management/EM", ResponseNamespace="urn:iControl:Management/EM")]
public void set_device_context(
string ip_address
) {
this.Invoke("set_device_context", new object [] {
ip_address});
}
public System.IAsyncResult Beginset_device_context(string ip_address, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_device_context", new object[] {
ip_address}, callback, asyncState);
}
public void Endset_device_context(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.EM.TaskStatus", Namespace = "urn:iControl")]
public enum ManagementEMTaskStatus
{
TASK_STATUS_UNKNOWN,
TASK_STATUS_PENDING,
TASK_STATUS_STARTED,
TASK_STATUS_FAILED,
TASK_STATUS_COMPLETE,
TASK_STATUS_RUNNING,
TASK_STATUS_CANCELING,
TASK_STATUS_CANCELED,
TASK_STATUS_ABANDONED,
TASK_STATUS_TERMINATED,
TASK_STATUS_TIMED_OUT,
TASK_STATUS_RESCHEDULED,
}
//=======================================================================
// Structs
//=======================================================================
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableHashSetBuilderTest : ImmutablesTestBase
{
[Fact]
public void CreateBuilder()
{
var builder = ImmutableHashSet.CreateBuilder<string>();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableHashSet<int>.Empty.ToBuilder();
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set = builder.ToImmutable();
Assert.Equal(builder.Count, set.Count);
Assert.True(builder.Add(8));
Assert.Equal(3, builder.Count);
Assert.Equal(2, set.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
}
[Fact]
public void BuilderFromSet()
{
var set = ImmutableHashSet<int>.Empty.Add(1);
var builder = set.ToBuilder();
Assert.True(builder.Contains(1));
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set2 = builder.ToImmutable();
Assert.Equal(builder.Count, set2.Count);
Assert.True(set2.Contains(1));
Assert.True(builder.Add(8));
Assert.Equal(4, builder.Count);
Assert.Equal(3, set2.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
Assert.False(set2.Contains(8));
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableHashSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder();
CollectionAssertAreEquivalent(Enumerable.Range(1, 10).ToArray(), builder.ToArray());
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray());
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray());
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableHashSet<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void EnumeratorTest()
{
var builder = ImmutableHashSet.Create(1).ToBuilder();
ManuallyEnumerateTest(new[] { 1 }, ((IEnumerable<int>)builder).GetEnumerator());
}
[Fact]
public void Clear()
{
var set = ImmutableHashSet.Create(1);
var builder = set.ToBuilder();
builder.Clear();
Assert.Equal(0, builder.Count);
}
[Fact]
public void KeyComparer()
{
var builder = ImmutableHashSet.Create("a", "B").ToBuilder();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
Assert.True(builder.Contains("a"));
Assert.False(builder.Contains("A"));
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains("a"));
Assert.True(builder.Contains("A"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void KeyComparerCollisions()
{
var builder = ImmutableHashSet.Create("a", "A").ToBuilder();
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Equal(1, builder.Count);
Assert.True(builder.Contains("a"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.Equal(1, set.Count);
Assert.True(set.Contains("a"));
}
[Fact]
public void KeyComparerEmptyCollection()
{
var builder = ImmutableHashSet.Create<string>().ToBuilder();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void UnionWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.UnionWith(null));
builder.UnionWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
}
[Fact]
public void ExceptWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.ExceptWith(null));
builder.ExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1 }, builder);
}
[Fact]
public void SymmetricExceptWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.SymmetricExceptWith(null));
builder.SymmetricExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 4 }, builder);
}
[Fact]
public void IntersectWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IntersectWith(null));
builder.IntersectWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 2, 3 }, builder);
}
[Fact]
public void IsProperSubsetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsProperSubsetOf(null));
Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsProperSupersetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsProperSupersetOf(null));
Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void IsSubsetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsSubsetOf(null));
Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsSupersetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsSupersetOf(null));
Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void Overlaps()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.Overlaps(null));
Assert.True(builder.Overlaps(Enumerable.Range(3, 2)));
Assert.False(builder.Overlaps(Enumerable.Range(4, 3)));
}
[Fact]
public void Remove()
{
var builder = ImmutableHashSet.Create("a").ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.Remove(null));
Assert.False(builder.Remove("b"));
Assert.True(builder.Remove("a"));
}
[Fact]
public void SetEquals()
{
var builder = ImmutableHashSet.Create("a").ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.SetEquals(null));
Assert.False(builder.SetEquals(new[] { "b" }));
Assert.True(builder.SetEquals(new[] { "a" }));
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> builder = ImmutableHashSet.Create("a").ToBuilder();
builder.Add("b");
Assert.True(builder.Contains("b"));
var array = new string[3];
builder.CopyTo(array, 1);
Assert.Null(array[0]);
CollectionAssertAreEquivalent(new[] { null, "a", "b" }, array);
Assert.False(builder.IsReadOnly);
CollectionAssertAreEquivalent(new[] { "a", "b" }, builder.ToArray()); // tests enumerator
}
}
}
| |
#region
using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using LegendaryClient.Logic;
using LegendaryClient.Logic.SQLite;
using LegendaryClient.Windows;
using Newtonsoft.Json;
using PVPNetConnect.RiotObjects.Gameinvite.Contract;
using PVPNetConnect.RiotObjects.Platform.Gameinvite.Contract;
#endregion
namespace LegendaryClient.Controls
{
/// <summary>
/// Interaction logic for AcceptGameInvite.xaml
/// </summary>
public partial class GameInvitePopup
{
private string _gameMetaData;
private string _gameMode,
_gameType;
private int _gameTypeConfigId;
private string _invitationId;
private string _invitationState;
private string _invitationStateAsString;
private string _inviter;
private bool _isRanked;
private int _mapId;
private string _mapName;
private string _mode;
private int _queueId;
private string _rankedTeamName;
private string _type;
public GameInvitePopup(InvitationRequest stats)
{
InitializeComponent();
Client.PVPNet.OnMessageReceived += PVPNet_OnMessageReceived;
try
{
InviteInfo info = Client.InviteData[stats.InvitationId];
Client.Log("Tried to find a popup that existed but should have been blocked. ", "Error");
if (info == null)
throw new NullReferenceException("Tried to find a nonexistant popup");
PVPNet_OnMessageReceived(this, stats);
//This should be hidden
Visibility = Visibility.Hidden;
}
catch
{
LoadGamePopupData(stats);
Unlock();
}
}
private void PVPNet_OnMessageReceived(object sender, object message)
{
if (!(message is InvitationRequest))
return;
var stats = (InvitationRequest) message;
try
{
InviteInfo info = Client.InviteData[stats.InvitationId];
//Data about this popup has changed. We want to set this
if (!Equals(info.popup, this))
return;
switch (stats.InvitationState)
{
case "ON_HOLD":
NotificationTextBox.Text = string.Format("The invite from {0} is now on hold",
info.Inviter);
Lockup();
Visibility = Visibility.Hidden;
break;
case "TERMINATED":
NotificationTextBox.Text = string.Format("The invite from {0} has been terminated",
info.Inviter);
Lockup();
Visibility = Visibility.Hidden;
break;
case "REVOKED":
NotificationTextBox.Text = string.Format("The invite from {0} has timed out", info.Inviter);
Lockup();
Visibility = Visibility.Hidden;
break;
case "ACTIVE":
NotificationTextBox.Text = "";
LoadGamePopupData(stats.Inviter == null ? info.stats : stats);
Visibility = Visibility.Hidden;
RenderNotificationTextBox(_inviter + " has invited you to a game");
RenderNotificationTextBox("");
RenderNotificationTextBox("Mode: " + _mode);
RenderNotificationTextBox("Map: " + _mapName);
RenderNotificationTextBox("Type: " + _type);
Unlock();
break;
default:
NotificationTextBox.Text = string.Format("The invite from {0} is now {1}", info.Inviter,
Client.TitleCaseString(stats.InvitationState));
Lockup();
break;
}
}
catch (Exception)
{
//We do not need this popup. it is a new one. Let it launch
}
}
private void Lockup()
{
AcceptButton.Visibility = Visibility.Hidden;
DeclineButton.Visibility = Visibility.Hidden;
OkayButton.Visibility = Visibility.Visible;
}
private void Unlock()
{
AcceptButton.Visibility = Visibility.Visible;
DeclineButton.Visibility = Visibility.Visible;
OkayButton.Visibility = Visibility.Hidden;
}
private void RenderNotificationTextBox(string s)
{
NotificationTextBox.Text += s + Environment.NewLine;
}
private void LoadGamePopupData(InvitationRequest stats)
{
_invitationStateAsString = stats.InvitationStateAsString;
_gameMetaData = stats.GameMetaData;
_invitationState = stats.InvitationState;
_inviter = stats.Inviter.SummonerName;
_invitationId = stats.InvitationId;
if (_invitationId != null)
{
NoGame.Visibility = Visibility.Hidden;
}
var m = JsonConvert.DeserializeObject<invitationRequest>(stats.GameMetaData);
_queueId = m.queueId;
_isRanked = m.isRanked;
_rankedTeamName = m.rankedTeamName;
_mapId = m.mapId;
_gameTypeConfigId = m.gameTypeConfigId;
_gameMode = m.gameMode;
_gameType = m.gameType;
Client.PVPNet.getLobbyStatusInviteId = _invitationId;
switch (_mapId)
{
case 1:
_mapName = "Summoners Rift";
break;
case 8:
_mapName = "The Crystal Scar";
break;
case 10:
_mapName = "The Twisted Treeline";
break;
case 11:
_mapName = "New Summoners Rift";
break;
case 12:
_mapName = "Howling Abyss";
break;
default:
_mapName = "Unknown Map";
break;
}
string gameModeLower = Client.TitleCaseString(string.Format(_gameMode.ToLower()));
string gameTypeLower = Client.TitleCaseString(string.Format(_gameType.ToLower()));
string gameTypeRemove = gameTypeLower.Replace("_game", "");
string removeAllUnder = gameTypeRemove.Replace("_", " ");
if (String.IsNullOrEmpty(_inviter))
_inviter = "An unknown player";
_mode = gameModeLower;
_type = removeAllUnder;
RenderNotificationTextBox(_inviter + " has invited you to a game");
RenderNotificationTextBox("");
RenderNotificationTextBox("Mode: " + gameModeLower);
RenderNotificationTextBox("Map: " + _mapName);
RenderNotificationTextBox("Type: " + removeAllUnder);
var y = new InviteInfo
{
stats = stats,
popup = this,
Inviter = _inviter
};
Client.InviteData.Add(stats.InvitationId, y);
}
private void Accept_Click(object sender, RoutedEventArgs e)
{
if (_gameType == "PRACTICE_GAME")
{
Client.SwitchPage(new CustomGameLobbyPage());
}
//goddammit teambuilder
else if (_gameType == "NORMAL_GAME" && _queueId != 61)
{
Client.SwitchPage(new TeamQueuePage(_invitationId));
}
else if (_gameType == "NORMAL_GAME" && _queueId == 61)
{
LobbyStatus newLobby = Client.PVPNet.InviteLobby;
Client.SwitchPage(new TeamBuilderPage(false, newLobby));
}
else if (_gameType == "RANKED_GAME")
{
Client.SwitchPage(new TeamQueuePage(_invitationId));
}
Visibility = Visibility.Hidden;
Client.InviteData.Remove(_invitationId);
}
private void Decline_Click(object sender, RoutedEventArgs e)
{
Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { Visibility = Visibility.Hidden; }));
Client.PVPNet.Decline(_invitationId);
Client.InviteData.Remove(_invitationId);
}
private void Hide_Click(object sender, RoutedEventArgs e)
{
Visibility = Visibility.Hidden;
InviteInfo x = Client.InviteData[_invitationId];
x.PopupVisible = false;
}
}
}
| |
//Copyright 2010 Microsoft Corporation
//
//Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
//"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and limitations under the License.
namespace System.Data.Services.Client
{
#region Namespaces.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
#endregion Namespaces.
internal class MemberAssignmentAnalysis : ALinqExpressionVisitor
{
#region Fields.
internal static readonly Expression[] EmptyExpressionArray = new Expression[0];
private readonly Expression entity;
private Exception incompatibleAssignmentsException;
private bool multiplePathsFound;
private List<Expression> pathFromEntity;
#endregion Fields.
#region Constructor.
private MemberAssignmentAnalysis(Expression entity)
{
Debug.Assert(entity != null, "entity != null");
this.entity = entity;
this.pathFromEntity = new List<Expression>();
}
#endregion Constructor.
#region Properties.
internal Exception IncompatibleAssignmentsException
{
get { return this.incompatibleAssignmentsException; }
}
internal bool MultiplePathsFound
{
get { return this.multiplePathsFound; }
}
#endregion Properites.
#region Methods.
internal static MemberAssignmentAnalysis Analyze(Expression entityInScope, Expression assignmentExpression)
{
Debug.Assert(entityInScope != null, "entityInScope != null");
Debug.Assert(assignmentExpression != null, "assignmentExpression != null");
MemberAssignmentAnalysis result = new MemberAssignmentAnalysis(entityInScope);
result.Visit(assignmentExpression);
return result;
}
internal Exception CheckCompatibleAssignments(Type targetType, ref MemberAssignmentAnalysis previous)
{
if (previous == null)
{
previous = this;
return null;
}
Expression[] previousExpressions = previous.GetExpressionsToTargetEntity();
Expression[] candidateExpressions = this.GetExpressionsToTargetEntity();
return CheckCompatibleAssignments(targetType, previousExpressions, candidateExpressions);
}
internal override Expression Visit(Expression expression)
{
if (this.multiplePathsFound || this.incompatibleAssignmentsException != null)
{
return expression;
}
return base.Visit(expression);
}
internal override Expression VisitConditional(ConditionalExpression c)
{
Expression result;
var nullCheck = ResourceBinder.PatternRules.MatchNullCheck(this.entity, c);
if (nullCheck.Match)
{
this.Visit(nullCheck.AssignExpression);
result = c;
}
else
{
result = base.VisitConditional(c);
}
return result;
}
internal override Expression VisitParameter(ParameterExpression p)
{
if (p == this.entity)
{
if (this.pathFromEntity.Count != 0)
{
this.multiplePathsFound = true;
}
else
{
this.pathFromEntity.Add(p);
}
}
return p;
}
internal override Expression VisitMemberInit(MemberInitExpression init)
{
Expression result = init;
MemberAssignmentAnalysis previousNested = null;
foreach (var binding in init.Bindings)
{
MemberAssignment assignment = binding as MemberAssignment;
if (assignment == null)
{
continue;
}
MemberAssignmentAnalysis nested = MemberAssignmentAnalysis.Analyze(this.entity, assignment.Expression);
if (nested.MultiplePathsFound)
{
this.multiplePathsFound = true;
break;
}
Exception incompatibleException = nested.CheckCompatibleAssignments(init.Type, ref previousNested);
if (incompatibleException != null)
{
this.incompatibleAssignmentsException = incompatibleException;
break;
}
if (this.pathFromEntity.Count == 0)
{
this.pathFromEntity.AddRange(nested.GetExpressionsToTargetEntity());
}
}
return result;
}
internal override Expression VisitMemberAccess(MemberExpression m)
{
Expression result = base.VisitMemberAccess(m);
if (this.pathFromEntity.Contains(m.Expression))
{
this.pathFromEntity.Add(m);
}
return result;
}
internal override Expression VisitMethodCall(MethodCallExpression call)
{
if (ReflectionUtil.IsSequenceMethod(call.Method, SequenceMethod.Select))
{
this.Visit(call.Arguments[0]);
return call;
}
return base.VisitMethodCall(call);
}
internal Expression[] GetExpressionsBeyondTargetEntity()
{
Debug.Assert(!this.multiplePathsFound, "this.multiplePathsFound -- otherwise GetExpressionsToTargetEntity won't return reliable (consistent) results");
if (this.pathFromEntity.Count <= 1)
{
return EmptyExpressionArray;
}
Expression[] result = new Expression[1];
result[0] = this.pathFromEntity[this.pathFromEntity.Count - 1];
return result;
}
internal Expression[] GetExpressionsToTargetEntity()
{
Debug.Assert(!this.multiplePathsFound, "this.multiplePathsFound -- otherwise GetExpressionsToTargetEntity won't return reliable (consistent) results");
if (this.pathFromEntity.Count <= 1)
{
return EmptyExpressionArray;
}
Expression[] result = new Expression[this.pathFromEntity.Count - 1];
for (int i = 0; i < result.Length; i++)
{
result[i] = this.pathFromEntity[i];
}
return result;
}
private static Exception CheckCompatibleAssignments(Type targetType, Expression[] previous, Expression[] candidate)
{
Debug.Assert(targetType != null, "targetType != null");
Debug.Assert(previous != null, "previous != null");
Debug.Assert(candidate != null, "candidate != null");
if (previous.Length != candidate.Length)
{
throw CheckCompatibleAssignmentsFail(targetType, previous, candidate);
}
for (int i = 0; i < previous.Length; i++)
{
Expression p = previous[i];
Expression c = candidate[i];
if (p.NodeType != c.NodeType)
{
throw CheckCompatibleAssignmentsFail(targetType, previous, candidate);
}
if (p == c)
{
continue;
}
if (p.NodeType != ExpressionType.MemberAccess)
{
return CheckCompatibleAssignmentsFail(targetType, previous, candidate);
}
if (((MemberExpression)p).Member.Name != ((MemberExpression)c).Member.Name)
{
return CheckCompatibleAssignmentsFail(targetType, previous, candidate);
}
}
return null;
}
private static Exception CheckCompatibleAssignmentsFail(Type targetType, Expression[] previous, Expression[] candidate)
{
Debug.Assert(targetType != null, "targetType != null");
Debug.Assert(previous != null, "previous != null");
Debug.Assert(candidate != null, "candidate != null");
string message = Strings.ALinq_ProjectionMemberAssignmentMismatch(targetType.FullName, previous.LastOrDefault(), candidate.LastOrDefault());
return new NotSupportedException(message);
}
#endregion Methods.
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class NoParameterBlockTests : SharedBlockTests
{
[Theory]
[MemberData(nameof(ConstantValueData))]
public void SingleElementBlock(object value)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile()());
}
[Theory]
[MemberData(nameof(ConstantValueData))]
public void DoubleElementBlock(object value)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile()());
}
[Fact]
public void DoubleElementBlockNullArgument()
{
Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression)));
}
[Fact]
public void DoubleElementBlockUnreadable()
{
Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression));
}
[Theory]
[MemberData(nameof(ConstantValueData))]
public void TripleElementBlock(object value)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile()());
}
[Fact]
public void TripleElementBlockNullArgument()
{
Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void TripleElementBlockUnreadable()
{
Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[MemberData(nameof(ConstantValueData))]
public void QuadrupleElementBlock(object value)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile()());
}
[Fact]
public void QuadrupleElementBlockNullArgument()
{
Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void QuadrupleElementBlockUnreadable()
{
Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[MemberData(nameof(ConstantValueData))]
public void QuintupleElementBlock(object value)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile()());
}
[Fact]
public void QuintupleElementBlockNullArgument()
{
Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg4", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void QuintupleElementBlockUnreadable()
{
Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg4", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[MemberData(nameof(ConstantValueData))]
public void SextupleElementBlock(object value)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile()());
}
[Fact]
public void NullExpicitType()
{
Assert.Throws<ArgumentNullException>("type", () => Expression.Block(default(Type), default(IEnumerable<ParameterExpression>), Expression.Constant(0)));
Assert.Throws<ArgumentNullException>("type", () => Expression.Block(default(Type), null, Enumerable.Repeat(Expression.Constant(0), 1)));
}
[Fact]
public void NullExpressionList()
{
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(default(Expression[])));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(default(IEnumerable<Expression>)));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void NullExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = null;
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(expressions));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(expressions.Skip(0)));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), expressions));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), expressions.Skip(0)));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), null, expressions));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), null, expressions.Skip(0)));
}
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void UnreadableExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = UnreadableExpression;
Assert.Throws<ArgumentException>("expressions", () => Expression.Block(expressions));
Assert.Throws<ArgumentException>("expressions", () => Expression.Block(expressions.Skip(0)));
Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), expressions));
Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), expressions.Skip(0)));
Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), null, expressions));
Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), null, expressions.Skip(0)));
}
}
[Theory]
[MemberData(nameof(ObjectAssignableConstantValuesAndSizes))]
public void BlockExplicitType(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
BlockExpression block = Expression.Block(typeof(object), PadBlock(blockSize - 1, constant));
Assert.Equal(typeof(object), block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile()());
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void BlockInvalidExplicitType(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(string), expressions));
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(string), expressions.ToArray()));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void InvalidExpressionIndex(object value, int blockSize)
{
BlockExpression block = Expression.Block(PadBlock(blockSize - 1, Expression.Constant(value, value.GetType())));
Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]);
}
[Fact]
public void EmptyBlockWithNonVoidTypeNotAllowed()
{
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(int)));
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(int), Enumerable.Empty<Expression>()));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromParams(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions.ToArray());
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromEnumerable(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void VariableCountZeroOnNonVariableAcceptingForms(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Empty(block.Variables);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
[ActiveIssue(3883)]
public void RewriteToSameWithSameValues(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(null, expressions));
Assert.Same(block, block.Update(Enumerable.Empty<ParameterExpression>(), expressions));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void CanFindItems(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(values);
IList<Expression> expressions = block.Expressions;
for (int i = 0; i != values.Length; ++i)
Assert.Equal(i, expressions.IndexOf(values[i]));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long))));
Assert.False(block.Expressions.Contains(null));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ExpressionsEnumerable(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(values);
Assert.True(values.SequenceEqual(block.Expressions));
int index = 0;
foreach (Expression exp in ((IEnumerable)block.Expressions))
Assert.Same(exp, values[index++]);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void UpdateWithExpressionsReturnsSame(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(block.Variables, block.Expressions));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void Visit(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData(nameof(ObjectAssignableConstantValuesAndSizes))]
public void VisitTyped(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(typeof(object), expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Provider;
using Microsoft.PowerShell.Commands;
using System.Runtime.InteropServices;
namespace TestPSSnapIn
{
public class CustomTestClass
{
public string MessageProperty { get; set; }
public string MessageField { get; set; }
public CustomTestClass(string messageProperty, string messageField)
{
SetMessages(messageProperty, messageField);
}
public string Combine()
{
return MessageProperty + MessageField;
}
public void SetMessages(string messageProperty, string messageField)
{
MessageProperty = messageProperty;
MessageField = messageField;
}
}
public class InternalMessageClass
{
private string _msg;
public InternalMessageClass(string msg)
{
_msg = msg;
}
public string GetMessage()
{
return _msg;
}
public static explicit operator InternalMessageClass(FooMessageClass fooObject)
{
return new InternalMessageClass("cast_" + fooObject.GetInternalMessage());
}
}
public class FooMessageClass
{
public string _internalMsg;
public InternalMessageClass Foo;
public FooMessageClass(string msg)
{
Foo = new InternalMessageClass(msg);
}
public string GetInternalMessage()
{
return _internalMsg;
}
}
[Cmdlet(VerbsDiagnostic.Test, "Command")]
public class TestCommand : PSCmdlet
{
public static string OutputString = "works";
protected override void ProcessRecord()
{
WriteObject(OutputString);
}
}
[Cmdlet(VerbsDiagnostic.Test, "WithMandatory")]
public class TestWithMandatoryCommand : PSCmdlet
{
public const string HELP_MSG = "Just provide some Message";
[Parameter(Mandatory = true, HelpMessage = HELP_MSG)]
public string OutputString { get; set; }
public static string Transform(string value)
{
return ">" + value.ToUpper() + "<";
}
protected override void ProcessRecord()
{
WriteObject(Transform(OutputString));
}
}
[Cmdlet(VerbsDiagnostic.Test, "NoMandatories", DefaultParameterSetName = "Reversed")]
public class TestNoMandatoriesCommand : PSCmdlet
{
[Parameter(Position = 0, ParameterSetName = "Correct")]
[Parameter(Position = 2, ParameterSetName = "Reversed")]
public string One { get; set; }
[Parameter(Position = 2, ParameterSetName = "Correct")]
[Parameter(Position = 0, ParameterSetName = "Reversed")]
public string Two { get; set; }
[Parameter(ValueFromPipeline = true, ParameterSetName = "Correct")]
public string RandomString;
[Parameter(ValueFromPipeline = true, ParameterSetName = "Reversed")]
public int RandomInt;
protected override void ProcessRecord()
{
string setName = RandomString != null ? "Correct" : "Reversed";
WriteObject(String.Format("{0}: {1} {2}", setName, One, Two));
}
}
[Cmdlet(VerbsDiagnostic.Test, "MandatoryInOneSet", DefaultParameterSetName = "Default")]
public class TestMandatoryInOneSetCommand : PSCmdlet
{
[Parameter(ParameterSetName = "Default", Position = 1, Mandatory = true)]
[Parameter(ParameterSetName = "Alternative", Position = 1, Mandatory = false)]
[Parameter(ParameterSetName = "Third", Position = 1, Mandatory = true)]
public string TestParam { get; set; }
[Parameter(ParameterSetName = "Third", Position = 2, Mandatory = true)]
public string TestParam2 { get; set; }
[Parameter(Position = 0, ValueFromPipeline = true)]
public string RandomString;
protected override void ProcessRecord()
{
WriteObject(RandomString);
}
}
[Cmdlet(VerbsDiagnostic.Test, "NoDefaultSet")]
public class TestNoDefaultSetCommand : PSCmdlet
{
[Parameter(ParameterSetName = "Default", Position = 1, Mandatory = false)]
[Parameter(ParameterSetName = "Alternative", Position = 1, Mandatory = false)]
public string TestParam { get; set; }
[Parameter(Position = 0, ValueFromPipeline = true)]
public string RandomString;
protected override void ProcessRecord()
{
WriteObject(RandomString);
}
}
[Cmdlet(VerbsDiagnostic.Test, "CmdletPhases")]
public class TestCmdletPhasesCommand : PSCmdlet
{
[Parameter(Position = 0, ValueFromPipeline = true)]
public string RandomString;
protected override void BeginProcessing()
{
WriteObject("Begin");
}
protected override void ProcessRecord()
{
WriteObject("Process");
}
protected override void EndProcessing()
{
WriteObject("End");
}
}
[Cmdlet(VerbsDiagnostic.Test, "ThrowError")]
public class TestThrowErrorCommand : PSCmdlet
{
protected override void ProcessRecord()
{
ThrowTerminatingError(new ErrorRecord(new Exception("testerror"), "TestError",
ErrorCategory.InvalidOperation, null));
}
}
[Cmdlet(VerbsDiagnostic.Test, "Dummy")]
public class TestDummyCommand : PSCmdlet
{
protected override void ProcessRecord()
{
}
}
[Cmdlet(VerbsDiagnostic.Test, "NoParameters")]
public class TestNoParametersCommand : PSCmdlet
{
protected override void ProcessRecord()
{
WriteObject("works");
}
}
[Cmdlet(VerbsDiagnostic.Test, "WriteNullObject")]
public class TestWriteNullCommand : PSCmdlet
{
protected override void ProcessRecord()
{
WriteObject(null);
}
}
[Cmdlet(VerbsDiagnostic.Test, "CountProcessRecord")]
public class TestCountProcessRecordCommand : PSCmdlet
{
private int _invocations = 0;
[Parameter(Position = 0, ValueFromPipeline = true)]
public PSObject RandomObject;
protected override void ProcessRecord()
{
_invocations++;
}
protected override void EndProcessing()
{
WriteObject(_invocations);
}
}
[Cmdlet(VerbsDiagnostic.Test, "SwitchAndPositional")]
public class TestSwitchAndPositionalCommand : PSCmdlet
{
[Parameter]
public SwitchParameter Switch { get; set; }
[Parameter(Position = 0, ValueFromPipeline = true)]
public string RandomString;
protected override void ProcessRecord()
{
WriteObject(RandomString);
}
}
[Cmdlet(VerbsDiagnostic.Test, "WriteTwoMessages")]
public class TestWriteTwoMessagesCommand : PSCmdlet
{
[Parameter]
public string Msg1 { get; set; }
[Parameter]
public string Msg2 { get; set; }
protected override void ProcessRecord()
{
WriteObject("1: " + Msg1 + ", 2: " + Msg2);
}
}
[Cmdlet(VerbsDiagnostic.Test, "SwitchParameter")]
public class TestSwitchParameterCommand : PSCmdlet
{
[Parameter]
public SwitchParameter Switch { get; set; }
protected override void ProcessRecord()
{
WriteObject(Switch.IsPresent);
}
}
[Cmdlet(VerbsDiagnostic.Test, "SameAliases")]
public class TestSameAliasesCommand : PSCmdlet
{
[Parameter(ParameterSetName = "One")]
[Alias("arg")]
public string Arg1 { get; set; }
[Parameter(ParameterSetName = "Two")]
[Alias("ARG")]
public string Arg2 { get; set; }
protected override void ProcessRecord()
{
WriteObject("works");
}
}
[Cmdlet(VerbsDiagnostic.Test, "DefaultParameterSetDoesntExist", DefaultParameterSetName = "DoesntExist")]
public class TestDefaultParameterSetDoesntExistCommand : PSCmdlet
{
[Parameter(ParameterSetName = "One", Mandatory = true)]
public string Arg1 { get; set; }
[Parameter(ParameterSetName = "Two", Mandatory = true)]
public string Arg2 { get; set; }
protected override void ProcessRecord()
{
WriteObject("works");
}
}
[Cmdlet(VerbsDiagnostic.Test, "NoDefaultSetAndTwoPositionals")]
public sealed class TestNoDefaultSetAndTwoPositionalsCommand : PSCmdlet
{
[Parameter(ParameterSetName = "First", Mandatory = true, Position = 0)]
public string Arg1 { get; set; }
[Parameter(ParameterSetName = "Second", Mandatory = true, Position = 0)]
public string Arg2 { get; set; }
protected override void ProcessRecord()
{
WriteObject("1:" + Arg1 + ", 2:" + Arg2);
}
}
[Cmdlet(VerbsDiagnostic.Test, "DefaultSetIsAllParameterSetAndTwoParameterSets",
DefaultParameterSetName = ParameterAttribute.AllParameterSets)]
public sealed class TestDefaultSetIsAllParameterSetAndTwoParameterSetsCommand : PSCmdlet
{
[Parameter(Position = 0)]
[ValidateNotNullOrEmpty]
public string First { get; set; }
protected override void ProcessRecord()
{
if (First == null) {
WriteObject("First: null");
} else {
WriteObject("First:" + First);
}
}
[Parameter(Position = 1, ParameterSetName = "Set1")]
[Parameter(Position = 1, ParameterSetName = "Set2")]
[ValidateNotNullOrEmpty]
public string Second { get; set; }
[Parameter(ParameterSetName = "Set1")]
public SwitchParameter ListAvailable { get; set; }
}
[Cmdlet(VerbsDiagnostic.Test, "TwoAmbiguousParameterSets")]
public sealed class TestTwoAmbiguousParameterSetsCommand : PSCmdlet
{
[Parameter(Position = 0)]
[ValidateNotNullOrEmpty]
public string First { get; set; }
protected override void ProcessRecord()
{
if (First == null) {
WriteObject("First: null");
} else {
WriteObject("First:" + First);
}
}
[Parameter(Position = 1, ParameterSetName = "Set1")]
[Parameter(Position = 1, ParameterSetName = "Set2")]
[ValidateNotNullOrEmpty]
public string Second { get; set; }
[Parameter(ParameterSetName = "Set1")]
public SwitchParameter ListAvailable { get; set; }
}
[Cmdlet(VerbsDiagnostic.Test, "CreateCustomObject")]
public class TestCreateCustomObjectCommand : PSCmdlet
{
[Parameter(Position = 0)]
public string CustomMessageProperty { get; set; }
[Parameter(Position = 1)]
public string CustomMessageField { get; set; }
protected override void ProcessRecord()
{
WriteObject(new CustomTestClass(CustomMessageProperty ?? "", CustomMessageField ?? ""));
}
}
[Cmdlet(VerbsDiagnostic.Test, "ParametersByPipelinePropertyNames")]
public class TestParametersByPipelinePropertyNamesCommand : PSCmdlet
{
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 1)]
[Alias(new string[] { "Baz" })]
public string Foo { get; set; }
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, Position = 0)]
public string Bar { get; set; }
protected override void ProcessRecord()
{
WriteObject(Foo + " " + Bar);
}
}
[Cmdlet(VerbsDiagnostic.Test, "CreateFooMessageObject")]
public class TestCreateFooMessageObjectCommand : PSCmdlet
{
[Parameter(Mandatory = true, Position = 0)]
public string Msg { get; set; }
protected override void ProcessRecord()
{
WriteObject(new FooMessageClass(Msg));
}
}
[Cmdlet(VerbsDiagnostic.Test, "WriteEnumerableToPipeline")]
public sealed class TestWriteEnumerableToPipelineCommand : PSCmdlet
{
[Parameter(Mandatory = true, Position = 0)]
public int Start { get; set; }
[Parameter(Mandatory = true, Position = 1)]
public int End { get; set; }
protected override void EndProcessing()
{
WriteObject(Generate(Start, i => i + 1, End), true);
}
private static IEnumerable<int> Generate(int start, Func<int, int> next, int end)
{
for (var item = start; !object.Equals(item, end); item = next(item))
{
yield return item;
}
yield return end;
}
}
[Cmdlet(VerbsDiagnostic.Test, "ParametersByPipelineWithPropertiesAndConversion")]
public class TestParametersByPipelineWithPropertiesAndConversionCommand : PSCmdlet
{
[Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[Alias(new string[] { "Baz" })]
public InternalMessageClass Foo { get; set; }
protected override void ProcessRecord()
{
WriteObject(Foo.GetMessage());
}
}
[Cmdlet(VerbsDiagnostic.Test, "ParameterUsesCustomTypeWithTypeConverter")]
public sealed class TestParameterUsesCustomTypeWithTypeConverterCommand : PSCmdlet
{
[Parameter(Mandatory = true, Position = 0)]
public Custom CustomTypeParameter { get; set; }
protected override void ProcessRecord()
{
WriteObject(string.Format("CustomType.Id='{0}'", CustomTypeParameter.Id));
}
}
[Cmdlet(VerbsDiagnostic.Test, "ParameterInTwoSetsButNotDefault", DefaultParameterSetName = "Default")]
public sealed class TestParameterInTwoSetsButNotDefaultCommand : PSCmdlet
{
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "Custom1")]
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "Custom2")]
public string Custom { get; set; }
[Parameter(Mandatory = true, Position = 1, ParameterSetName = "Custom2")]
public string Custom2 { get; set; }
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "Default")]
public string DefParam { get; set; }
protected override void ProcessRecord()
{
WriteObject(ParameterSetName);
}
}
[Cmdlet(VerbsDiagnostic.Test, "IntegerArraySum")]
public sealed class TestIntegerArraySumCommand : PSCmdlet
{
[Parameter(Mandatory = true)]
public int[] IntArray { get; set; }
public static string Transform(int[] arr)
{
int s = 0;
foreach (var i in arr)
{
s += i;
}
return "l=" + arr.Length + ",s=" + s;
}
protected override void ProcessRecord()
{
WriteObject(Transform(IntArray));
}
}
[Cmdlet(VerbsDiagnostic.Test, "ParamIsNotMandatoryByDefault")]
public class TestParamIsNotMandatoryByDefaultCommand : PSCmdlet
{
[Parameter]
public string Message { get; set; }
protected override void ProcessRecord()
{
WriteObject(Message);
}
}
[Cmdlet(VerbsDiagnostic.Test, "PrintCredentials")]
public class TestPrintCredentialsCommand : PSCmdlet
{
[Credential, Parameter(Mandatory = true, Position=0)]
public PSCredential Credential { get; set; }
protected override void ProcessRecord()
{
WriteObject("User: " + Credential.UserName);
IntPtr unmanagedString = IntPtr.Zero;
try
{
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(Credential.Password);
WriteObject("Password: " + Marshal.PtrToStringUni(unmanagedString));
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
}
}
}
[Cmdlet(VerbsDiagnostic.Test, "OneMandatoryParamByPipelineSelection", DefaultParameterSetName = "Message")]
public class TestOneMandatoryParamByPipelineSelectionCommand : PSCmdlet
{
[Parameter(Mandatory = true, ParameterSetName = "Message")]
public string Message { get; set; }
[Parameter(Mandatory = true, ParameterSetName = "Integer", ValueFromPipeline = true)]
public int Integer { get; set; }
protected override void BeginProcessing()
{
WriteObject(ParameterSetName);
}
protected override void ProcessRecord()
{
WriteObject(ParameterSetName);
}
}
public class TestMandatoryParamByPipelineSelectionCommandBase : PSCmdlet
{
[Parameter(Mandatory = true, ParameterSetName = "Message", ValueFromPipeline = true)]
public string Message { get; set; }
[Parameter(Mandatory = true, ParameterSetName = "Integer", ValueFromPipeline = true)]
public int Integer { get; set; }
protected override void BeginProcessing()
{
WriteObject(ParameterSetName);
}
protected override void ProcessRecord()
{
WriteObject(ParameterSetName);
}
}
[Cmdlet(VerbsDiagnostic.Test, "MandatoryParamByPipelineSelection", DefaultParameterSetName = "Message")]
public class TestMandatoryParamByPipelineSelectionCommand :
TestMandatoryParamByPipelineSelectionCommandBase {}
[Cmdlet(VerbsDiagnostic.Test, "MandatoryParamByPipelineSelectionWithoutDefault")]
public class TestMandatoryParamByPipelineSelectionWithoutDefaultCommand :
TestMandatoryParamByPipelineSelectionCommandBase {}
[TypeConverter(typeof(CustomTypeConverter))]
public class Custom
{
public string Id { get; set; }
}
public class CustomTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string stringValue = value as string;
return new Custom { Id = stringValue };
}
}
[Cmdlet(VerbsDiagnostic.Test, "ContentWriter", DefaultParameterSetName = "Path")]
public class TestContentWriter : WriteContentCommandBase
{
protected override void ProcessRecord()
{
foreach (string path in Path)
{
using (IContentWriter writer = InvokeProvider.Content.GetWriter(path).Single())
{
IList items = writer.Write(Value);
// Need to close writer before disposing it otherwise Microsoft's
// FileSystemProvider throws an exception.
writer.Close();
}
}
}
}
[Cmdlet(VerbsDiagnostic.Test, "ContentReader", DefaultParameterSetName = "Path")]
public class TestContentReader : ContentCommandBase
{
protected override void ProcessRecord()
{
foreach (string path in Path)
{
using (IContentReader reader = InvokeProvider.Content.GetReader(path).Single())
{
while (true)
{
IList items = reader.Read(1);
if (items.Count > 0)
{
WriteObject(items[0]);
}
else
{
reader.Close();
break;
}
}
}
}
}
}
[Cmdlet(VerbsDiagnostic.Test, "ParametersByPositionWhenOneBoundByName")]
public class TestParametersByPositionWhenOneBoundByName : PSCmdlet
{
[Parameter(
Mandatory = true,
Position = 0)]
public string First { get; set; }
[Parameter(
Position = 1,
Mandatory = true)]
public string Second { get; set; }
[Parameter(
Position = 2,
Mandatory = true)]
public string Third { get; set; }
[Parameter(
Position = 3,
Mandatory = true)]
public string Fourth { get; set; }
protected override void ProcessRecord()
{
WriteObject(string.Format("'{0}', '{1}', '{2}', '{3}'", First, Second, Third, Fourth));
}
}
public class TestDynamicParameters
{
[Parameter(Mandatory=true, Position=0)]
public string MessageOne { get; set; }
[Parameter(ValueFromPipeline=true)]
public string MessageTwo { get; set; }
public TestDynamicParameters()
: this(null, null)
{
}
public TestDynamicParameters(string msg1, string msg2)
{
MessageOne = msg1;
MessageTwo = msg2;
}
public override bool Equals(object obj)
{
var other = obj as TestDynamicParameters;
if (other == null)
{
return false;
}
return String.Equals(MessageOne, other.MessageOne) &&
String.Equals(MessageTwo, other.MessageTwo);
}
public override int GetHashCode()
{
return (MessageOne == null ? 0 : MessageOne.GetHashCode()) +
(MessageTwo == null ? 0 : MessageTwo.GetHashCode());
}
}
[Cmdlet(VerbsDiagnostic.Test, "DynamicParametersConditionally")]
public class TestDynamicParametersConditionally : PSCmdlet, IDynamicParameters
{
private TestDynamicParameters _params;
[Parameter]
public SwitchParameter UseParameters;
[Parameter(Position=5)]
public String DefaultMessage;
public object GetDynamicParameters()
{
if (UseParameters.IsPresent)
{
_params = new TestDynamicParameters();
return _params;
}
return null;
}
protected override void ProcessRecord()
{
WriteObject(UseParameters.IsPresent);
WriteObject(DefaultMessage);
WriteObject(_params);
}
}
}
| |
// 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.
/*
* Ordered String/Object collection of name/value pairs with support for null key
*
* This class is intended to be used as a base class
*
*/
#pragma warning disable 618 // obsolete types, namely IHashCodeProvider
using System.Globalization;
using System.Runtime.Serialization;
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>Provides the <see langword='abstract '/>base class for a sorted collection of associated <see cref='System.String' qualify='true'/> keys
/// and <see cref='System.Object' qualify='true'/> values that can be accessed either with the hash code of
/// the key or with the index.</para>
/// </devdoc>
[Serializable]
public abstract class NameObjectCollectionBase : ICollection, ISerializable, IDeserializationCallback
{
// const names used for serialization
private const String ReadOnlyName = "ReadOnly";
private const String CountName = "Count";
private const String ComparerName = "Comparer";
private const String HashCodeProviderName = "HashProvider";
private const String KeysName = "Keys";
private const String ValuesName = "Values";
private const String KeyComparerName = "KeyComparer";
private const String VersionName = "Version";
private bool _readOnly = false;
private ArrayList _entriesArray;
private IEqualityComparer _keyComparer;
private volatile Hashtable _entriesTable;
private volatile NameObjectEntry _nullKeyEntry;
private KeysCollection _keys;
private int _version;
private SerializationInfo _serializationInfo;
[NonSerialized]
private Object _syncRoot;
private static readonly StringComparer s_defaultComparer = CultureInfo.InvariantCulture.CompareInfo.GetStringComparer(CompareOptions.IgnoreCase);
/// <devdoc>
/// <para> Creates an empty <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance with the default initial capacity and using the default case-insensitive hash
/// code provider and the default case-insensitive comparer.</para>
/// </devdoc>
protected NameObjectCollectionBase() : this(s_defaultComparer)
{
}
protected NameObjectCollectionBase(IEqualityComparer equalityComparer)
{
_keyComparer = (equalityComparer == null) ? s_defaultComparer : equalityComparer;
Reset();
}
protected NameObjectCollectionBase(Int32 capacity, IEqualityComparer equalityComparer) : this(equalityComparer)
{
Reset(capacity);
}
[Obsolete("Please use NameObjectCollectionBase(IEqualityComparer) instead.")]
protected NameObjectCollectionBase(IHashCodeProvider hashProvider, IComparer comparer) {
_keyComparer = new CompatibleComparer(hashProvider, comparer);
Reset();
}
[Obsolete("Please use NameObjectCollectionBase(Int32, IEqualityComparer) instead.")]
protected NameObjectCollectionBase(int capacity, IHashCodeProvider hashProvider, IComparer comparer) {
_keyComparer = new CompatibleComparer(hashProvider, comparer);
Reset(capacity);
}
/// <devdoc>
/// <para>Creates an empty <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance with the specified
/// initial capacity and using the default case-insensitive hash code provider
/// and the default case-insensitive comparer.</para>
/// </devdoc>
protected NameObjectCollectionBase(int capacity)
{
_keyComparer = s_defaultComparer;
Reset(capacity);
}
protected NameObjectCollectionBase(SerializationInfo info, StreamingContext context)
{
_serializationInfo = info;
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue(ReadOnlyName, _readOnly);
// Maintain backward serialization compatibility if new APIs are not used.
if (_keyComparer == s_defaultComparer)
{
info.AddValue(HashCodeProviderName, CaseInsensitiveHashCodeProvider.DefaultInvariant, typeof(IHashCodeProvider));
info.AddValue(ComparerName, CaseInsensitiveComparer.DefaultInvariant, typeof(IComparer));
}
else if (_keyComparer == null)
{
info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider));
info.AddValue(ComparerName, null, typeof(IComparer));
}
else if (_keyComparer is CompatibleComparer)
{
CompatibleComparer c = (CompatibleComparer)_keyComparer;
info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider));
info.AddValue(ComparerName, c.Comparer, typeof(IComparer));
}
else
{
info.AddValue(KeyComparerName, _keyComparer, typeof(IEqualityComparer));
}
int count = _entriesArray.Count;
info.AddValue(CountName, count);
string[] keys = new string[count];
object[] values = new object[count];
for (int i = 0; i < count; i++)
{
NameObjectEntry entry = (NameObjectEntry)_entriesArray[i];
keys[i] = entry.Key;
values[i] = entry.Value;
}
info.AddValue(KeysName, keys, typeof(String[]));
info.AddValue(ValuesName, values, typeof(Object[]));
info.AddValue(VersionName, _version);
}
public virtual void OnDeserialization(object sender)
{
if (_keyComparer != null)
{
//Somebody had a dependency on this and fixed us up before the ObjectManager got to it.
return;
}
if (_serializationInfo == null)
{
throw new SerializationException();
}
SerializationInfo info = _serializationInfo;
_serializationInfo = null;
bool readOnly = false;
int count = 0;
string[] keys = null;
object[] values = null;
IHashCodeProvider hashProvider = null;
IComparer comparer = null;
bool hasVersion = false;
int serializedVersion = 0;
SerializationInfoEnumerator enumerator = info.GetEnumerator();
while (enumerator.MoveNext())
{
switch (enumerator.Name)
{
case ReadOnlyName:
readOnly = info.GetBoolean(ReadOnlyName); ;
break;
case HashCodeProviderName:
hashProvider = (IHashCodeProvider)info.GetValue(HashCodeProviderName, typeof(IHashCodeProvider)); ;
break;
case ComparerName:
comparer = (IComparer)info.GetValue(ComparerName, typeof(IComparer));
break;
case KeyComparerName:
_keyComparer = (IEqualityComparer)info.GetValue(KeyComparerName, typeof(IEqualityComparer));
break;
case CountName:
count = info.GetInt32(CountName);
break;
case KeysName:
keys = (String[])info.GetValue(KeysName, typeof(String[]));
break;
case ValuesName:
values = (Object[])info.GetValue(ValuesName, typeof(Object[]));
break;
case VersionName:
hasVersion = true;
serializedVersion = info.GetInt32(VersionName);
break;
}
}
if (_keyComparer == null)
{
if (comparer == null || hashProvider == null)
{
throw new SerializationException();
}
else
{
// create a new key comparer for V1 Object
_keyComparer = new CompatibleComparer(hashProvider, comparer);
}
}
if (keys == null || values == null)
{
throw new SerializationException();
}
Reset(count);
for (int i = 0; i < count; i++)
{
BaseAdd(keys[i], values[i]);
}
_readOnly = readOnly; // after collection populated
if (hasVersion)
{
_version = serializedVersion;
}
}
//
// Private helpers
//
private void Reset()
{
_entriesArray = new ArrayList();
_entriesTable = new Hashtable(_keyComparer);
_nullKeyEntry = null;
_version++;
}
private void Reset(int capacity)
{
_entriesArray = new ArrayList(capacity);
_entriesTable = new Hashtable(capacity, _keyComparer);
_nullKeyEntry = null;
_version++;
}
private NameObjectEntry FindEntry(String key)
{
if (key != null)
return (NameObjectEntry)_entriesTable[key];
else
return _nullKeyEntry;
}
internal IEqualityComparer Comparer
{
get
{
return _keyComparer;
}
set
{
_keyComparer = value;
}
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance is read-only.</para>
/// </devdoc>
protected bool IsReadOnly
{
get { return _readOnly; }
set { _readOnly = value; }
}
/// <devdoc>
/// <para>Gets a value indicating whether the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance contains entries whose
/// keys are not <see langword='null'/>.</para>
/// </devdoc>
protected bool BaseHasKeys()
{
return (_entriesTable.Count > 0); // any entries with keys?
}
//
// Methods to add / remove entries
//
/// <devdoc>
/// <para>Adds an entry with the specified key and value into the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected void BaseAdd(String name, Object value)
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
NameObjectEntry entry = new NameObjectEntry(name, value);
// insert entry into hashtable
if (name != null)
{
if (_entriesTable[name] == null)
_entriesTable.Add(name, entry);
}
else
{ // null key -- special case -- hashtable doesn't like null keys
if (_nullKeyEntry == null)
_nullKeyEntry = entry;
}
// add entry to the list
_entriesArray.Add(entry);
_version++;
}
/// <devdoc>
/// <para>Removes the entries with the specified key from the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected void BaseRemove(String name)
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
if (name != null)
{
// remove from hashtable
_entriesTable.Remove(name);
// remove from array
for (int i = _entriesArray.Count - 1; i >= 0; i--)
{
if (_keyComparer.Equals(name, BaseGetKey(i)))
_entriesArray.RemoveAt(i);
}
}
else
{ // null key -- special case
// null out special 'null key' entry
_nullKeyEntry = null;
// remove from array
for (int i = _entriesArray.Count - 1; i >= 0; i--)
{
if (BaseGetKey(i) == null)
_entriesArray.RemoveAt(i);
}
}
_version++;
}
/// <devdoc>
/// <para> Removes the entry at the specified index of the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected void BaseRemoveAt(int index)
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
String key = BaseGetKey(index);
if (key != null)
{
// remove from hashtable
_entriesTable.Remove(key);
}
else
{ // null key -- special case
// null out special 'null key' entry
_nullKeyEntry = null;
}
// remove from array
_entriesArray.RemoveAt(index);
_version++;
}
/// <devdoc>
/// <para>Removes all entries from the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected void BaseClear()
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
Reset();
}
//
// Access by name
//
/// <devdoc>
/// <para>Gets the value of the first entry with the specified key from
/// the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected Object BaseGet(String name)
{
NameObjectEntry e = FindEntry(name);
return (e != null) ? e.Value : null;
}
/// <devdoc>
/// <para>Sets the value of the first entry with the specified key in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/>
/// instance, if found; otherwise, adds an entry with the specified key and value
/// into the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/>
/// instance.</para>
/// </devdoc>
protected void BaseSet(String name, Object value)
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
NameObjectEntry entry = FindEntry(name);
if (entry != null)
{
entry.Value = value;
_version++;
}
else
{
BaseAdd(name, value);
}
}
//
// Access by index
//
/// <devdoc>
/// <para>Gets the value of the entry at the specified index of
/// the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected Object BaseGet(int index)
{
NameObjectEntry entry = (NameObjectEntry)_entriesArray[index];
return entry.Value;
}
/// <devdoc>
/// <para>Gets the key of the entry at the specified index of the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/>
/// instance.</para>
/// </devdoc>
protected String BaseGetKey(int index)
{
NameObjectEntry entry = (NameObjectEntry)_entriesArray[index];
return entry.Key;
}
/// <devdoc>
/// <para>Sets the value of the entry at the specified index of
/// the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected void BaseSet(int index, Object value)
{
if (_readOnly)
throw new NotSupportedException(SR.CollectionReadOnly);
NameObjectEntry entry = (NameObjectEntry)_entriesArray[index];
entry.Value = value;
_version++;
}
//
// ICollection implementation
//
/// <devdoc>
/// <para>Returns an enumerator that can iterate through the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/>.</para>
/// </devdoc>
public virtual IEnumerator GetEnumerator()
{
return new NameObjectKeysEnumerator(this);
}
/// <devdoc>
/// <para>Gets the number of key-and-value pairs in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
public virtual int Count
{
get
{
return _entriesArray.Count;
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_MultiRank, nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < _entriesArray.Count)
{
throw new ArgumentException(SR.Arg_InsufficientSpace);
}
for (IEnumerator e = this.GetEnumerator(); e.MoveNext();)
array.SetValue(e.Current, index++);
}
Object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
//
// Helper methods to get arrays of keys and values
//
/// <devdoc>
/// <para>Returns a <see cref='System.String' qualify='true'/> array containing all the keys in the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected String[] BaseGetAllKeys()
{
int n = _entriesArray.Count;
String[] allKeys = new String[n];
for (int i = 0; i < n; i++)
allKeys[i] = BaseGetKey(i);
return allKeys;
}
/// <devdoc>
/// <para>Returns an <see cref='System.Object' qualify='true'/> array containing all the values in the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected Object[] BaseGetAllValues()
{
int n = _entriesArray.Count;
Object[] allValues = new Object[n];
for (int i = 0; i < n; i++)
allValues[i] = BaseGet(i);
return allValues;
}
/// <devdoc>
/// <para>Returns an array of the specified type containing
/// all the values in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
protected object[] BaseGetAllValues(Type type)
{
int n = _entriesArray.Count;
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
object[] allValues = (object[])Array.CreateInstance(type, n);
for (int i = 0; i < n; i++)
{
allValues[i] = BaseGet(i);
}
return allValues;
}
//
// Keys property
//
/// <devdoc>
/// <para>Returns a <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/> instance containing
/// all the keys in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
public virtual KeysCollection Keys
{
get
{
if (_keys == null)
_keys = new KeysCollection(this);
return _keys;
}
}
//
// Simple entry class to allow substitution of values and indexed access to keys
//
internal class NameObjectEntry
{
internal NameObjectEntry(String name, Object value)
{
Key = name;
Value = value;
}
internal String Key;
internal Object Value;
}
//
// Enumerator over keys of NameObjectCollection
//
internal class NameObjectKeysEnumerator : IEnumerator
{
private int _pos;
private NameObjectCollectionBase _coll;
private int _version;
internal NameObjectKeysEnumerator(NameObjectCollectionBase coll)
{
_coll = coll;
_version = _coll._version;
_pos = -1;
}
public bool MoveNext()
{
if (_version != _coll._version)
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_pos < _coll.Count - 1)
{
_pos++;
return true;
}
else
{
_pos = _coll.Count;
return false;
}
}
public void Reset()
{
if (_version != _coll._version)
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_pos = -1;
}
public Object Current
{
get
{
if (_pos >= 0 && _pos < _coll.Count)
{
return _coll.BaseGetKey(_pos);
}
else
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
}
}
}
//
// Keys collection
//
/// <devdoc>
/// <para>Represents a collection of the <see cref='System.String' qualify='true'/> keys of a collection.</para>
/// </devdoc>
public class KeysCollection : ICollection
{
private NameObjectCollectionBase _coll;
internal KeysCollection(NameObjectCollectionBase coll)
{
_coll = coll;
}
// Indexed access
/// <devdoc>
/// <para> Gets the key at the specified index of the collection.</para>
/// </devdoc>
public virtual String Get(int index)
{
return _coll.BaseGetKey(index);
}
/// <devdoc>
/// <para>Represents the entry at the specified index of the collection.</para>
/// </devdoc>
public String this[int index]
{
get
{
return Get(index);
}
}
// ICollection implementation
/// <devdoc>
/// <para>Returns an enumerator that can iterate through the
/// <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/>.</para>
/// </devdoc>
public IEnumerator GetEnumerator()
{
return new NameObjectKeysEnumerator(_coll);
}
/// <devdoc>
/// <para>Gets the number of keys in the <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/>.</para>
/// </devdoc>
public int Count
{
get
{
return _coll.Count;
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_MultiRank, nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < _coll.Count)
{
throw new ArgumentException(SR.Arg_InsufficientSpace);
}
for (IEnumerator e = this.GetEnumerator(); e.MoveNext();)
array.SetValue(e.Current, index++);
}
Object ICollection.SyncRoot
{
get { return ((ICollection)_coll).SyncRoot; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
}
}
}
| |
//
// Generator.cs: C++ Interop Code Generator
//
//
using System;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Linq;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using NDesk.Options;
using Mono.VisualC.Interop;
public class Generator
{
// Command line arguments
string OutputDir;
string Namespace;
string LibBaseName;
string InputFileName;
string FilterFile;
CodeDomProvider Provider;
CodeGeneratorOptions CodeGenOptions;
// Classes to generate code for
Dictionary<string, string> Filters;
public static int Main (String[] args) {
var generator = new Generator ();
generator.Run (args);
return 0;
}
int ParseArguments (String[] args) {
bool help = false;
var p = new OptionSet {
{ "h|?|help", "Show this help message", v => help = v != null },
{ "o=", "Set the output directory", v => OutputDir = v },
{ "ns=|namespace=", "Set the namespace of the generated code", v => Namespace = v },
{ "lib=", "The base name of the C++ library, i.e. 'qt' for libqt.so", v =>LibBaseName = v },
{ "filters=", "A file containing filter directives for filtering classes", v => FilterFile = v }
};
try {
args = p.Parse (args).ToArray ();
} catch (OptionException) {
Console.WriteLine ("Try `generator --help' for more information.");
return 1;
}
if (help) {
p.WriteOptionDescriptions (Console.Error);
return 1;
}
if (args.Length != 1) {
Console.WriteLine ("Usage: generator <options> <input xml file>");
return 1;
}
InputFileName = args [0];
if (LibBaseName == null) {
Console.WriteLine ("The --lib= option is required.");
return 1;
}
if (OutputDir == null)
OutputDir = "output";
return 0;
}
void Run (String[] args) {
if (ParseArguments (args) != 0) {
Environment.Exit (1);
}
Node root = LoadXml (InputFileName);
if (FilterFile != null)
LoadFilters (FilterFile);
CreateClasses (root);
CreateMethods ();
GenerateCode ();
}
Node LoadXml (string file) {
XmlReader reader = XmlReader.Create (file, new XmlReaderSettings ());
Node[] parents = new Node [1024];
Node root = null;
while (reader.Read()) {
if (reader.IsStartElement ()) {
string type = reader.Name;
var attributes = new Dictionary<string, string> ();
while (reader.MoveToNextAttribute ()) {
attributes [reader.Name] = reader.Value;
}
Node n = new Node {
Id = "",
Type = type,
Attributes = attributes,
Children = new List<Node> ()
};
if (attributes.ContainsKey ("id")) {
n.Id = attributes ["id"];
Node.IdToNode [n.Id] = n;
}
if (attributes.ContainsKey ("name"))
n.Name = attributes ["name"];
if (parents [reader.Depth - 1] != null) {
//Console.WriteLine (parents [reader.Depth - 1].type + " -> " + e.type);
parents [reader.Depth - 1].Children.Add (n);
}
parents [reader.Depth] = n;
if (n.Type == "GCC_XML" && root == null)
root = n;
}
}
return root;
}
void LoadFilters (string file) {
Filters = new Dictionary <string, string> ();
foreach (string s in File.ReadAllLines (file)) {
Filters [s] = s;
}
}
List<Class> Classes;
Dictionary<Node, Class> NodeToClass;
void CreateClasses (Node root) {
List<Node> classNodes = root.Children.Where (o => o.Type == "Class" || o.Type == "Struct").ToList ();
classNodes.RemoveAll (o => o.IsTrue ("incomplete") || !o.HasValue ("name"));
if (Filters != null)
classNodes.RemoveAll (o => !Filters.ContainsKey (o.Name));
List<Class> classes = new List<Class> ();
NodeToClass = new Dictionary <Node, Class> ();
foreach (Node n in classNodes) {
Console.WriteLine (n.Name);
Class klass = new Class (n);
classes.Add (klass);
NodeToClass [n] = klass;
}
// Compute bases
foreach (Class klass in classes) {
foreach (Node bn in klass.Node.Children.Where (o => o.Type == "Base")) {
Class baseClass = NodeToClass [bn.NodeForAttr ("type")];
klass.BaseClasses.Add (baseClass);
}
}
Classes = classes;
}
void CreateMethods () {
foreach (Class klass in Classes) {
if (!klass.Node.HasValue ("members"))
continue;
List<Node> members = new List<Node> ();
foreach (string id in klass.Node ["members"].Split (' ')) {
if (id == "")
continue;
members.Add (Node.IdToNode [id]);
}
int fieldCount = 0;
foreach (Node n in members) {
bool ctor = false;
bool dtor = false;
switch (n.Type) {
case "Field":
CppType fieldType = GetType (GetTypeNode (n));
string fieldName;
if (n.Name != "")
fieldName = n.Name;
else
fieldName = "field" + fieldCount++;
if (CppTypeToCodeDomType (fieldType) == null)
// FIXME: Assume IntPtr
fieldType = ((CppType)CppTypes.Void).Modify (CppModifiers.Pointer);
klass.Fields.Add (new Field (fieldName, fieldType));
break;
case "Constructor":
ctor = true;
break;
case "Destructor":
dtor = true;
break;
case "Method":
break;
default:
continue;
}
if (!n.CheckValue ("access", "public") || (n.HasValue ("overrides") && !dtor))
continue;
if (!n.IsTrue ("extern") && !n.IsTrue ("inline"))
continue;
string name = dtor ? "Destruct" : n.Name;
var method = new Method (n) {
Name = name,
IsVirtual = n.IsTrue ("virtual"),
IsStatic = n.IsTrue ("static"),
IsConst = n.IsTrue ("const"),
IsInline = n.IsTrue ("inline"),
IsArtificial = n.IsTrue ("artificial"),
IsConstructor = ctor,
IsDestructor = dtor
};
bool skip = false;
CppType retType;
if (n.HasValue ("returns"))
retType = GetType (n.NodeForAttr ("returns"));
else
retType = CppTypes.Void;
if (retType.ElementType == CppTypes.Unknown)
skip = true;
if (CppTypeToCodeDomType (retType) == null) {
//Console.WriteLine ("\t\tS: " + retType);
skip = true;
}
method.ReturnType = retType;
int c = 0;
List<CppType> argTypes = new List<CppType> ();
foreach (Node arg in n.Children.Where (o => o.Type == "Argument")) {
string argname;
if (arg.Name == null || arg.Name == "")
argname = "arg" + c;
else
argname = arg.Name;
CppType argtype = GetType (GetTypeNode (arg));
if (argtype.ElementType == CppTypes.Unknown) {
//Console.WriteLine ("Skipping method " + klass.Name + "::" + member.Name + " () because it has an argument with unknown type '" + TypeNodeToString (arg) + "'.");
skip = true;
}
if (CppTypeToCodeDomType (argtype) == null) {
//Console.WriteLine ("\t\tS: " + argtype);
skip = true;
}
method.Parameters.Add (new Parameter (argname, argtype));
argTypes.Add (argtype);
c++;
}
if (skip)
continue;
// FIXME: More complete type name check
if (ctor && argTypes.Count == 1 && argTypes [0].ElementType == CppTypes.Class && argTypes [0].ElementTypeName == klass.Name && argTypes [0].Modifiers.Count == 2 && argTypes [0].Modifiers.Contains (CppModifiers.Const) && argTypes [0].Modifiers.Contains (CppModifiers.Reference))
method.IsCopyCtor = true;
Console.WriteLine ("\t" + klass.Name + "." + method.Name);
klass.Methods.Add (method);
}
foreach (Method method in klass.Methods) {
if (AddAsQtProperty (klass, method))
method.GenWrapperMethod = false;
}
Field f2 = klass.Fields.FirstOrDefault (f => f.Type.ElementType == CppTypes.Unknown);
if (f2 != null) {
Console.WriteLine ("Skipping " + klass.Name + " because field " + f2.Name + " has unknown type.");
klass.Disable = true;
}
}
}
//
// Property support
// This is QT specific
//
bool AddAsQtProperty (Class klass, Method method) {
// if it's const, returns a value, has no parameters, and there is no other method with the same name
// in this class assume it's a property getter (for now?)
if (method.IsConst && !method.ReturnType.Equals (CppTypes.Void) && !method.Parameters.Any () &&
klass.Methods.Where (o => o.Name == method.Name).FirstOrDefault () == method) {
Property property;
property = klass.Properties.Where (o => o.Name == method.FormattedName).FirstOrDefault ();
if (property != null) {
property.GetMethod = method;
} else {
property = new Property (method.FormattedName, method.ReturnType) { GetMethod = method };
klass.Properties.Add (property);
}
return true;
}
// if it's name starts with "set", does not return a value, and has one arg (besides this ptr)
// and there is no other method with the same name...
if (method.Name.ToLower ().StartsWith ("set") && method.ReturnType.Equals (CppTypes.Void) &&
method.Parameters.Count == 1 && klass.Methods.Where (o => o.Name == method.Name).Count () == 1) {
string getterName = method.Name.Substring (3).TrimStart ('_').ToLower ();
string pname = method.FormattedName.Substring (3);
Property property = null;
// ...AND there is a corresponding getter method that returns the right type, then assume it's a property setter
bool doIt = false;
property = klass.Properties.Where (o => o.Name == pname).FirstOrDefault ();
if (property != null) {
doIt = property.GetMethod != null && property.GetMethod.ReturnType.Equals (method.Parameters[0].Type);
} else {
Method getter = klass.Methods.Where (o => o.Name == getterName).FirstOrDefault ();
doIt = getter != null && getter.ReturnType.Equals (method.Parameters[0].Type);
}
if (doIt) {
if (property != null) {
property.SetMethod = method;
} else {
property = new Property (pname, method.Parameters [0].Type) { SetMethod = method };
klass.Properties.Add (property);
}
// set the method's arg name to "value" so that the prop setter works right
var valueParam = method.Parameters[0];
valueParam.Name = "value";
return true;
}
}
return false;
}
// Return a CppType for the type node N, return CppTypes.Unknown for unknown types
CppType GetType (Node n) {
return GetType (n, new CppType ());
}
CppType GetType (Node n, CppType modifiers) {
switch (n.Type) {
case "ArrayType":
return GetType (GetTypeNode (n), modifiers.Modify (CppModifiers.Array));
case "PointerType":
return GetType (GetTypeNode (n), modifiers.Modify (CppModifiers.Pointer));
case "ReferenceType":
return GetType (GetTypeNode (n), modifiers.Modify (CppModifiers.Reference));
case "FundamentalType":
return modifiers.CopyTypeFrom (new CppType (n.Name));
case "CvQualifiedType":
if (n.IsTrue ("const"))
return GetType (GetTypeNode (n), modifiers.Modify (CppModifiers.Const));
else
throw new NotImplementedException ();
case "Class":
case "Struct":
if (!NodeToClass.ContainsKey (n)) {
if (modifiers.Modifiers.Count () == 1 && modifiers.Modifiers [0] == CppModifiers.Pointer)
// Map these to void*
return modifiers.CopyTypeFrom (CppTypes.Void);
else
return CppTypes.Unknown;
}
return modifiers.CopyTypeFrom (new CppType (CppTypes.Class, NodeToClass [n].Name));
default:
return CppTypes.Unknown;
}
}
Node GetTypeNode (Node n) {
return Node.IdToNode [n.Attributes ["type"]];
}
// Return the CodeDom type reference corresponding to T, or null
public CodeTypeReference CppTypeToCodeDomType (CppType t, out bool byref) {
CodeTypeReference rtype = null;
byref = false;
Type mtype = t.ToManagedType ();
if (mtype != null) {
if (mtype.IsByRef) {
byref = true;
mtype = mtype.GetElementType ();
}
return new CodeTypeReference (mtype);
}
if (t.Modifiers.Count > 0 && t.ElementType != CppTypes.Void && t.ElementType != CppTypes.Class)
return null;
switch (t.ElementType) {
case CppTypes.Void:
if (t.Modifiers.Count > 0) {
if (t.Modifiers.Count == 1 && t.Modifiers [0] == CppModifiers.Pointer)
rtype = new CodeTypeReference (typeof (IntPtr));
else
return null;
} else {
rtype = new CodeTypeReference (typeof (void));
}
break;
case CppTypes.Bool:
rtype = new CodeTypeReference (typeof (bool));
break;
case CppTypes.Int:
rtype = new CodeTypeReference (typeof (int));
break;
case CppTypes.Float:
rtype = new CodeTypeReference (typeof (float));
break;
case CppTypes.Double:
rtype = new CodeTypeReference (typeof (double));
break;
case CppTypes.Char:
rtype = new CodeTypeReference (typeof (char));
break;
case CppTypes.Class:
// FIXME: Full name
rtype = new CodeTypeReference (t.ElementTypeName);
break;
default:
return null;
}
return rtype;
}
public CodeTypeReference CppTypeToCodeDomType (CppType t) {
bool byref;
return CppTypeToCodeDomType (t, out byref);
}
void GenerateCode () {
Directory.CreateDirectory (OutputDir);
Provider = new CSharpCodeProvider ();
CodeGenOptions = new CodeGeneratorOptions { BlankLinesBetweenMembers = false };
CodeTypeDeclaration libDecl = null;
// Generate Libs class
{
var cu = new CodeCompileUnit ();
var ns = new CodeNamespace (Namespace);
ns.Imports.Add(new CodeNamespaceImport("System"));
ns.Imports.Add(new CodeNamespaceImport("Mono.VisualC.Interop"));
cu.Namespaces.Add (ns);
var decl = new CodeTypeDeclaration ("Libs");
var field = new CodeMemberField (new CodeTypeReference ("CppLibrary"), LibBaseName);
field.Attributes = MemberAttributes.Public|MemberAttributes.Static;
field.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("CppLibrary"), new CodeExpression [] { new CodePrimitiveExpression (LibBaseName) });
decl.Members.Add (field);
ns.Types.Add (decl);
libDecl = decl;
//Provider.GenerateCodeFromCompileUnit(cu, Console.Out, CodeGenOptions);
using (TextWriter w = File.CreateText (Path.Combine (OutputDir, "Libs.cs"))) {
Provider.GenerateCodeFromCompileUnit(cu, w, CodeGenOptions);
}
}
// Generate user classes
foreach (Class klass in Classes) {
if (klass.Disable)
continue;
var cu = new CodeCompileUnit ();
var ns = new CodeNamespace (Namespace);
ns.Imports.Add(new CodeNamespaceImport("System"));
ns.Imports.Add(new CodeNamespaceImport("Mono.VisualC.Interop"));
cu.Namespaces.Add (ns);
ns.Types.Add (klass.GenerateClass (this, libDecl, LibBaseName));
//Provider.GenerateCodeFromCompileUnit(cu, Console.Out, CodeGenOptions);
using (TextWriter w = File.CreateText (Path.Combine (OutputDir, klass.Name + ".cs"))) {
// These are reported for the fields of the native layout structures
Provider.GenerateCodeFromCompileUnit (new CodeSnippetCompileUnit("#pragma warning disable 0414, 0169"), w, CodeGenOptions);
Provider.GenerateCodeFromCompileUnit(cu, w, CodeGenOptions);
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Localization;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.Localization.Bidi;
namespace OpenLiveWriter.ApplicationFramework.Preferences
{
public class PreferencesForm : BaseForm
{
#region Static & Constant Declarations
#endregion Static & Constant Declarations
#region Private Member Variables
/// <summary>
/// The SideBarControl that provides our TabControl-like user interface.
/// </summary>
private SideBarControl sideBarControl;
/// <summary>
/// The PreferencesPanel list.
/// </summary>
private ArrayList preferencesPanelList = new ArrayList();
/// <summary>
/// A value which indicates whether the form is initialized.
/// </summary>
private bool initialized;
#endregion Private Member Variables
#region Windows Form Designer generated code
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Button buttonApply;
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.Panel panelPreferences;
private System.ComponentModel.IContainer components;
#endregion Windows Form Designer generated code
#region Class Initialization & Termination
public PreferencesForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.buttonOK.Text = Res.Get(StringId.OKButtonText);
this.buttonCancel.Text = Res.Get(StringId.CancelButton);
this.buttonApply.Text = Res.Get(StringId.ApplyButton);
// Set the title of the form.
Text = Res.Get(StringId.Options);
// Instantiate and initialize the SideBarControl.
sideBarControl = new SideBarControl();
sideBarControl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom;
sideBarControl.TabStop = true;
sideBarControl.TabIndex = 0;
sideBarControl.SelectedIndexChanged += new EventHandler(sideBarControl_SelectedIndexChanged);
sideBarControl.Location = new Point(10, 10);
sideBarControl.Size = new Size(151, ClientSize.Height - 20);
Controls.Add(sideBarControl);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
foreach (PreferencesPanel panel in preferencesPanelList)
panel.Dispose();
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#endregion Class Initialization & Termination
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PreferencesForm));
this.buttonOK = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonApply = new System.Windows.Forms.Button();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.panelPreferences = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// buttonOK
//
this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonOK.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonOK.Location = new System.Drawing.Point(288, 568);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(75, 23);
this.buttonOK.TabIndex = 2;
this.buttonOK.Text = "OK";
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonCancel.Location = new System.Drawing.Point(368, 568);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 3;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonApply
//
this.buttonApply.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonApply.Enabled = false;
this.buttonApply.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonApply.Location = new System.Drawing.Point(448, 568);
this.buttonApply.Name = "buttonApply";
this.buttonApply.Size = new System.Drawing.Size(75, 23);
this.buttonApply.TabIndex = 4;
this.buttonApply.Text = "&Apply";
this.buttonApply.Click += new System.EventHandler(this.buttonApply_Click);
//
// imageList
//
this.imageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.imageList.ImageSize = new System.Drawing.Size(32, 32);
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.White;
//
// panelPreferences
//
this.panelPreferences.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.panelPreferences.BackColor = System.Drawing.SystemColors.Control;
this.panelPreferences.Location = new System.Drawing.Point(162, 0);
this.panelPreferences.Name = "panelPreferences";
this.panelPreferences.Size = new System.Drawing.Size(370, 567);
this.panelPreferences.TabIndex = 1;
//
// PreferencesForm
//
this.AcceptButton = this.buttonOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.CancelButton = this.buttonCancel;
this.ClientSize = new System.Drawing.Size(534, 600);
this.Controls.Add(this.panelPreferences);
this.Controls.Add(this.buttonApply);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PreferencesForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Options";
this.ResumeLayout(false);
}
#endregion
#region Events
/// <summary>
/// Event triggered when the user saves a new set of preferences (by pressing OK, or Apply).
/// </summary>
public event EventHandler PreferencesSaved;
public void OnPreferencesSaved(EventArgs evt)
{
if (PreferencesSaved != null)
PreferencesSaved(this, evt);
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the selected index.
/// </summary>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int SelectedIndex
{
get
{
return sideBarControl.SelectedIndex;
}
set
{
sideBarControl.SelectedIndex = value;
}
}
public IWin32Window Win32Owner
{
get
{
if (_win32Owner != null)
return _win32Owner;
else
return Owner;
}
set
{
_win32Owner = value;
}
}
private IWin32Window _win32Owner;
#endregion Public Properties
#region Public Methods
public void HideApplyButton()
{
buttonApply.Visible = false;
int shift = buttonApply.Right - buttonCancel.Right;
buttonOK.Left += shift;
buttonCancel.Left += shift;
}
public void SelectEntry(Type panel)
{
for (int i = 0; i < preferencesPanelList.Count; i++)
{
if (preferencesPanelList[i].GetType() == panel)
{
SelectedIndex = i;
return;
}
}
}
/// <summary>
/// Sets a PreferencesPanel.
/// </summary>
/// <param name="index">Index of the entry to set; zero based.</param>
/// <param name="preferencesPanel">The PreferencesPanel to set.</param>
public void SetEntry(int index, PreferencesPanel preferencesPanel)
{
// Set the SideBarControl entry.
sideBarControl.SetEntry(index, preferencesPanel.PanelBitmap, preferencesPanel.PanelName, "btn" + preferencesPanel.Name);
// Set our PreferencesPanel event handlers.
preferencesPanel.Modified += new EventHandler(preferencesPanel_Modified);
// Replace and existing PreferencesPanel.
if (index < preferencesPanelList.Count)
{
// Remove the existing PreferencesPanel.
if (preferencesPanelList[index] != null)
{
PreferencesPanel oldPreferencesPanel = (PreferencesPanel)preferencesPanelList[index];
oldPreferencesPanel.Modified -= new EventHandler(preferencesPanel_Modified);
if (sideBarControl.SelectedIndex == index)
panelPreferences.Controls.Remove(oldPreferencesPanel);
}
// Set the new PreferencesPabel.
preferencesPanelList[index] = preferencesPanel;
}
// Add a new PreferencesPanel.
else
{
// Ensure that there are entries up to the index position (make them null). This
// allows the user of this control to add his entries out of order or with gaps.
for (int i = preferencesPanelList.Count; i < index; i++)
preferencesPanelList.Add(null);
// Add the BitmapButton.
preferencesPanelList.Add(preferencesPanel);
}
// Add the Preferences panel.
preferencesPanel.Dock = DockStyle.Fill;
panelPreferences.Controls.Add(preferencesPanel);
}
#endregion Public Methods
#region Protected Event Overrides
/// <summary>
/// Raises the Load event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnLoad(EventArgs e)
{
// Call the base class's method so that registered delegates receive the event.
base.OnLoad(e);
// The Collection Settings dialog looks weird when it comes up with Fields
// selected but Flags focused... both boxes are blue. This makes sure that
// doesn't happen.
this.buttonCancel.Focus();
AdjustHeightToFit();
using (new AutoGrow(this, AnchorStyles.Right, true))
{
LayoutHelper.EqualizeButtonWidthsHoriz(AnchorStyles.Right, buttonCancel.Width, int.MaxValue,
buttonOK, buttonCancel, buttonApply);
int oldSize = sideBarControl.Width;
sideBarControl.AdjustSize();
int deltaX = sideBarControl.Width - oldSize;
new ControlGroup(panelPreferences, buttonOK, buttonCancel, buttonApply).Left += deltaX;
if (buttonOK.Left < sideBarControl.Right)
{
int right = buttonApply.Right;
DisplayHelper.AutoFitSystemButton(buttonOK);
DisplayHelper.AutoFitSystemButton(buttonCancel);
DisplayHelper.AutoFitSystemButton(buttonApply);
LayoutHelper.DistributeHorizontally(8, buttonOK, buttonCancel, buttonApply);
new ControlGroup(buttonOK, buttonCancel, buttonApply).Left += right - buttonApply.Right;
}
}
// We're initialized, so remove all unselected panels. This allows AutoScale to
// work.
initialized = true;
RemoveUnselectedPanels();
// protect against being shown directly on top of an identically sized owner
OffsetFromIdenticalOwner();
}
private void AdjustHeightToFit()
{
int maxPanelHeight = 0;
foreach (PreferencesPanel panel in preferencesPanelList)
{
maxPanelHeight = Math.Max(maxPanelHeight, GetPanelHeightRequired(panel));
}
panelPreferences.Height = maxPanelHeight;
Height = maxPanelHeight + (int)Math.Ceiling(DisplayHelper.ScaleY(100));
}
private int GetPanelHeightRequired(PreferencesPanel preferencesPanel)
{
int maxBottom = 0;
foreach (Control c in preferencesPanel.Controls)
maxBottom = Math.Max(maxBottom, c.Bottom);
return maxBottom;
}
#endregion Protected Event Overrides
#region Private Properties
#endregion
#region Private Methods
/// <summary>
/// Helper method to save Preferences.
/// Returns true if saved successfully.
/// </summary>
private bool SavePreferences()
{
TabSwitcher tabSwitcher = new TabSwitcher(sideBarControl);
for (int i = 0; i < preferencesPanelList.Count; i++)
{
PreferencesPanel preferencesPanel = (PreferencesPanel)preferencesPanelList[i];
tabSwitcher.Tab = i;
if (!preferencesPanel.PrepareSave(new PreferencesPanel.SwitchToPanel(tabSwitcher.Switch)))
{
return false;
}
}
// Save every PreferencesPanel.
for (int i = 0; i < preferencesPanelList.Count; i++)
{
PreferencesPanel preferencesPanel = (PreferencesPanel)preferencesPanelList[i];
if (preferencesPanel != null)
preferencesPanel.Save();
}
// Disable the Apply button.
buttonApply.Enabled = false;
//notify listeners that the preferences where saved.
OnPreferencesSaved(EventArgs.Empty);
return true;
}
internal class TabSwitcher
{
private SideBarControl control;
internal TabSwitcher(SideBarControl control)
{
this.control = control;
}
public int Tab;
public void Switch()
{
control.SelectedIndex = Tab;
}
}
/// <summary>
/// Removes all unselected panels.
/// </summary>
private void RemoveUnselectedPanels()
{
if (!initialized)
return;
for (int i = 0; i < preferencesPanelList.Count; i++)
{
if (i != sideBarControl.SelectedIndex && preferencesPanelList[i] != null)
{
PreferencesPanel preferencesPanel = (PreferencesPanel)preferencesPanelList[i];
if (panelPreferences.Controls.Contains(preferencesPanel))
panelPreferences.Controls.Remove(preferencesPanel);
}
}
}
private void OffsetFromIdenticalOwner()
{
if (Win32Owner != null)
{
RECT ownerRect = new RECT();
RECT prefsRect = new RECT();
if (User32.GetWindowRect(Win32Owner.Handle, ref ownerRect) && User32.GetWindowRect(Handle, ref prefsRect))
{
if ((ownerRect.right - ownerRect.left) == (prefsRect.right - prefsRect.left))
{
// adjust location
StartPosition = FormStartPosition.Manual;
Location = new Point(ownerRect.left - SystemInformation.CaptionHeight, ownerRect.top - SystemInformation.CaptionHeight);
}
}
}
}
#endregion Private Methods
#region Private Event Handlers
/// <summary>
/// sideBarControl_SelectedIndexChanged event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void sideBarControl_SelectedIndexChanged(object sender, EventArgs e)
{
// Make the selected PreferencesPanel visible.
if (sideBarControl.SelectedIndex < preferencesPanelList.Count && preferencesPanelList[sideBarControl.SelectedIndex] != null)
{
PreferencesPanel preferencesPanel = (PreferencesPanel)preferencesPanelList[sideBarControl.SelectedIndex];
if (BidiHelper.IsRightToLeft && preferencesPanel.RightToLeft != RightToLeft.Yes)
preferencesPanel.RightToLeft = RightToLeft.Yes;
BidiHelper.RtlLayoutFixup(preferencesPanel);
panelPreferences.Controls.Add(preferencesPanel);
if (ShowKeyboardCues)
{
//fix bug 406441, if the show cues window messages have been sent to the form
//resend them to force the new control to show them
ControlHelper.HideAccelerators(this);
ControlHelper.ShowAccelerators(this);
}
if (ShowFocusCues)
{
//fix bug 406420, if the show cues window messages have been sent to the form
//resend them to force the new control to show them
ControlHelper.HideFocus(this);
ControlHelper.ShowFocus(this);
}
preferencesPanel.BringToFront();
}
// Remove unselected panels.
RemoveUnselectedPanels();
}
/// <summary>
/// preferencesPanel_Modified event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void preferencesPanel_Modified(object sender, EventArgs e)
{
buttonApply.Enabled = true;
}
/// <summary>
/// buttonOK_Click event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void buttonOK_Click(object sender, EventArgs e)
{
if (SavePreferences())
DialogResult = DialogResult.OK;
}
/// <summary>
/// buttonCancel_Click event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
/// <summary>
/// buttonApply_Click event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void buttonApply_Click(object sender, EventArgs e)
{
SavePreferences();
}
#endregion Event Handlers
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class ReadChar : PortsTest
{
//The number of random bytes to receive for large input buffer testing
// This was 4096, but the largest buffer setting on FTDI USB-Serial devices is "4096", which actually only allows a read of 4094 or 4095 bytes
// The test code assumes that we will be able to do this transfer as a single read, so 4000 is safer and would seem to be about
// as rigourous a test
private const int largeNumRndBytesToRead = 4000;
//The number of random characters to receive
private const int numRndChar = 8;
private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };
#region Test Cases
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ASCIIEncoding()
{
Debug.WriteLine("Verifying read with bytes encoded with ASCIIEncoding");
VerifyRead(new ASCIIEncoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF8Encoding()
{
Debug.WriteLine("Verifying read with bytes encoded with UTF8Encoding");
VerifyRead(new UTF8Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF32Encoding()
{
Debug.WriteLine("Verifying read with bytes encoded with UTF32Encoding");
VerifyRead(new UTF32Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedAndNonBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedAndNonBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Zero_ResizeBuffer()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
byte[] byteXmitBuffer = new byte[1024];
char utf32Char = 'A';
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
char[] charXmitBuffer = TCSupport.GetRandomChars(16, false);
char[] expectedChars = new char[charXmitBuffer.Length + 1];
Debug.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer");
expectedChars[0] = utf32Char;
Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length);
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
com1.ReadTimeout = 0;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
Assert.Equal(1, com1.BytesToRead);
com1.Encoding = Encoding.UTF32;
byteXmitBuffer = Encoding.UTF32.GetBytes(charXmitBuffer);
Assert.Throws<TimeoutException>(() => com1.ReadChar());
Assert.Equal(1, com1.BytesToRead);
com2.Write(utf32CharBytes, 1, 3);
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, 4 + byteXmitBuffer.Length);
PerformReadOnCom1FromCom2(com1, com2, expectedChars);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_NonZero_ResizeBuffer()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
byte[] byteXmitBuffer = new byte[1024];
char utf32Char = 'A';
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
char[] charXmitBuffer = TCSupport.GetRandomChars(16, false);
char[] expectedChars = new char[charXmitBuffer.Length + 1];
Debug.WriteLine("Verifying Read method with non zero timeout that resizes SerialPort's buffer");
expectedChars[0] = utf32Char;
Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length);
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
com1.ReadTimeout = 500;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
Assert.Equal(1, com1.BytesToRead);
com1.Encoding = Encoding.UTF32;
byteXmitBuffer = Encoding.UTF32.GetBytes(charXmitBuffer);
Assert.Throws<TimeoutException>(() => com1.ReadChar());
Assert.Equal(1, com1.BytesToRead);
com2.Write(utf32CharBytes, 1, 3);
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, 4 + byteXmitBuffer.Length);
PerformReadOnCom1FromCom2(com1, com2, expectedChars);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void GreedyRead()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
byte[] byteXmitBuffer = new byte[1024];
char utf32Char = TCSupport.GenerateRandomCharNonSurrogate();
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
int charRead;
Debug.WriteLine("Verifying that ReadChar() will read everything from internal buffer and drivers buffer");
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
TCSupport.SetHighSpeed(com1, com2);
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
Assert.Equal(1, com1.BytesToRead);
com1.Encoding = Encoding.UTF32;
com2.Write(utf32CharBytes, 1, 3);
TCSupport.WaitForReadBufferToLoad(com1, 4);
if (utf32Char != (charRead = com1.ReadChar()))
{
Fail("Err_6481sfadw ReadChar() returned={0} expected={1}", charRead, utf32Char);
}
Assert.Equal(0, com1.BytesToRead);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void LargeInputBuffer()
{
Debug.WriteLine("Verifying read with large input buffer");
VerifyRead(Encoding.ASCII, largeNumRndBytesToRead);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Zero_Bytes()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char utf32Char = (char)0x254b; //Box drawing char
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
int readChar;
Debug.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer");
com1.Encoding = Encoding.UTF32;
com1.ReadTimeout = 0;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
//[] Try ReadChar with no bytes available
Assert.Throws<TimeoutException>(() => com1.ReadChar());
Assert.Equal(0, com1.BytesToRead);
//[] Try ReadChar with 1 byte available
com2.Write(utf32CharBytes, 0, 1);
TCSupport.WaitForPredicate(() => com1.BytesToRead == 1, 2000,
"Err_28292aheid Expected BytesToRead to be 1");
Assert.Throws<TimeoutException>(() => com1.ReadChar());
Assert.Equal(1, com1.BytesToRead);
//[] Try ReadChar with the bytes in the buffer and in available in the SerialPort
com2.Write(utf32CharBytes, 1, 3);
TCSupport.WaitForPredicate(() => com1.BytesToRead == 4, 2000,
"Err_415568haikpas Expected BytesToRead to be 4");
readChar = com1.ReadChar();
Assert.Equal(utf32Char, readChar);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_DataReceivedBeforeTimeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None);
char[] charRcvBuffer = new char[charXmitBuffer.Length];
ASyncRead asyncRead = new ASyncRead(com1);
Thread asyncReadThread =
new Thread(asyncRead.Read);
Debug.WriteLine(
"Verifying that ReadChar will read characters that have been received after the call to Read was made");
com1.Encoding = Encoding.UTF8;
com2.Encoding = Encoding.UTF8;
com1.ReadTimeout = 20000; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
asyncReadThread.Start();
asyncRead.ReadStartedEvent.WaitOne();
//This only tells us that the thread has started to execute code in the method
Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
asyncRead.ReadCompletedEvent.WaitOne();
Assert.Null(asyncRead.Exception);
if (asyncRead.Result != charXmitBuffer[0])
{
Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], asyncRead.Result);
}
else
{
charRcvBuffer[0] = (char)asyncRead.Result;
int receivedLength = 1;
while (receivedLength < charXmitBuffer.Length)
{
receivedLength += com1.Read(charRcvBuffer, receivedLength, charRcvBuffer.Length - receivedLength);
}
Assert.Equal(receivedLength, charXmitBuffer.Length);
Assert.Equal(charXmitBuffer, charRcvBuffer);
}
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_Timeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None);
byte[] byteXmitBuffer = new UTF32Encoding().GetBytes(charXmitBuffer);
char[] charRcvBuffer = new char[charXmitBuffer.Length];
int result;
Debug.WriteLine(
"Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown");
com1.Encoding = new UTF32Encoding();
com2.Encoding = new UTF32Encoding();
com1.ReadTimeout = 500; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
//Write the first 3 bytes of a character
com2.Write(byteXmitBuffer, 0, 3);
Assert.Throws<TimeoutException>(() => com1.ReadChar());
Assert.Equal(3, com1.BytesToRead);
com2.Write(byteXmitBuffer, 3, byteXmitBuffer.Length - 3);
TCSupport.WaitForExpected(() => com1.BytesToRead, byteXmitBuffer.Length,
5000, "Err_91818aheid BytesToRead");
result = com1.ReadChar();
if (result != charXmitBuffer[0])
{
Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], result);
}
else
{
charRcvBuffer[0] = (char)result;
int readResult = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1);
if (readResult + 1 != charXmitBuffer.Length)
{
Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", charXmitBuffer.Length - 1, readResult);
}
else
{
for (int i = 0; i < charXmitBuffer.Length; ++i)
{
if (charRcvBuffer[i] != charXmitBuffer[i])
{
Fail("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X})", i, charXmitBuffer[i], charRcvBuffer[i]);
}
}
}
}
VerifyBytesReadOnCom1FromCom2(com1, com2, byteXmitBuffer, charXmitBuffer);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_Surrogate()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] surrogateChars = { (char)0xDB26, (char)0xDC49 };
char[] additionalChars = TCSupport.GetRandomChars(32, TCSupport.CharacterOptions.None);
char[] charRcvBuffer = new char[2];
Debug.WriteLine("Verifying that ReadChar works correctly when trying to read surrogate characters");
com1.Encoding = new UTF32Encoding();
com2.Encoding = new UTF32Encoding();
com1.ReadTimeout = 500; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
int numBytes = com2.Encoding.GetByteCount(surrogateChars);
numBytes += com2.Encoding.GetByteCount(additionalChars);
com2.Write(surrogateChars, 0, 2);
com2.Write(additionalChars, 0, additionalChars.Length);
TCSupport.WaitForExpected(() => com1.BytesToRead, numBytes,
5000, "Err_91818aheid BytesToRead");
// We expect this to fail, because it can't read a surrogate
Assert.Throws<ArgumentException>(() => com1.ReadChar());
int result = com1.Read(charRcvBuffer, 0, 2);
Assert.Equal(2, result);
if (charRcvBuffer[0] != surrogateChars[0])
{
Fail("Err_12929anied Expected first char read={0}({1:X}) actually read={2}({3:X})",
surrogateChars[0], (int)surrogateChars[0], charRcvBuffer[0], (int)charRcvBuffer[0]);
}
else if (charRcvBuffer[1] != surrogateChars[1])
{
Fail("Err_12929anied Expected second char read={0}({1:X}) actually read={2}({3:X})",
surrogateChars[1], (int)surrogateChars[1], charRcvBuffer[1], (int)charRcvBuffer[1]);
}
PerformReadOnCom1FromCom2(com1, com2, additionalChars);
}
}
#endregion
#region Verification for Test Cases
private void VerifyRead(Encoding encoding)
{
VerifyRead(encoding, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(Encoding encoding, int bufferSize)
{
VerifyRead(encoding, ReadDataFromEnum.NonBuffered, bufferSize);
}
private void VerifyRead(Encoding encoding, ReadDataFromEnum readDataFrom)
{
VerifyRead(encoding, readDataFrom, numRndChar);
}
private void VerifyRead(Encoding encoding, ReadDataFromEnum readDataFrom, int bufferSize)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(bufferSize, false);
byte[] byteXmitBuffer = encoding.GetBytes(charXmitBuffer);
com1.ReadTimeout = 500;
com1.Encoding = encoding;
TCSupport.SetHighSpeed(com1, com2);
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
switch (readDataFrom)
{
case ReadDataFromEnum.NonBuffered:
VerifyReadNonBuffered(com1, com2, byteXmitBuffer);
break;
case ReadDataFromEnum.Buffered:
VerifyReadBuffered(com1, com2, byteXmitBuffer);
break;
case ReadDataFromEnum.BufferedAndNonBuffered:
VerifyReadBufferedAndNonBuffered(com1, com2, byteXmitBuffer);
break;
default:
throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null);
}
}
}
private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars);
}
private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
BufferData(com1, com2, bytesToWrite);
PerformReadOnCom1FromCom2(com1, com2, expectedChars);
}
private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
char[] expectedChars = new char[com1.Encoding.GetCharCount(bytesToWrite, 0, bytesToWrite.Length) * 2];
char[] encodedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
Array.Copy(encodedChars, 0, expectedChars, 0, bytesToWrite.Length);
Array.Copy(encodedChars, 0, expectedChars, encodedChars.Length, encodedChars.Length);
BufferData(com1, com2, bytesToWrite);
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars);
}
private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer
Assert.Equal(bytesToWrite.Length, com1.BytesToRead);
}
private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars)
{
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 500;
Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250);
PerformReadOnCom1FromCom2(com1, com2, expectedChars);
}
private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars)
{
int bytesToRead = com1.Encoding.GetByteCount(expectedChars);
char[] charRcvBuffer = new char[expectedChars.Length];
int rcvBufferSize = 0;
int i;
i = 0;
while (true)
{
int readInt;
try
{
readInt = com1.ReadChar();
}
catch (TimeoutException)
{
Assert.Equal(expectedChars.Length, i);
break;
}
//While there are more characters to be read
if (expectedChars.Length <= i)
{
//If we have read in more characters then were actually sent
Fail("ERROR!!!: We have received more characters then were sent");
}
charRcvBuffer[i] = (char)readInt;
rcvBufferSize += com1.Encoding.GetByteCount(charRcvBuffer, i, 1);
int com1ToRead = com1.BytesToRead;
if (bytesToRead - rcvBufferSize != com1ToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1} at {2}", bytesToRead - rcvBufferSize, com1ToRead, i);
}
if (readInt != expectedChars[i])
{
//If the character read is not the expected character
Fail("ERROR!!!: Expected to read {0} actual read char {1} at {2}", (int)expectedChars[i], readInt, i);
}
i++;
}
Assert.Equal(0, com1.BytesToRead);
}
public class ASyncRead
{
private readonly SerialPort _com;
private int _result;
private readonly AutoResetEvent _readCompletedEvent;
private readonly AutoResetEvent _readStartedEvent;
private Exception _exception;
public ASyncRead(SerialPort com)
{
_com = com;
_result = int.MinValue;
_readCompletedEvent = new AutoResetEvent(false);
_readStartedEvent = new AutoResetEvent(false);
_exception = null;
}
public void Read()
{
try
{
_readStartedEvent.Set();
_result = _com.ReadChar();
}
catch (Exception e)
{
_exception = e;
}
finally
{
_readCompletedEvent.Set();
}
}
public AutoResetEvent ReadStartedEvent => _readStartedEvent;
public AutoResetEvent ReadCompletedEvent => _readCompletedEvent;
public int Result => _result;
public Exception Exception => _exception;
}
#endregion
}
}
| |
using System;
using System.Xml;
using System.Data;
using System.Data.OleDb;
using System.Runtime.InteropServices;
namespace MyMeta
{
#if ENTERPRISE
using System.Runtime.InteropServices;
[ComVisible(false), ClassInterface(ClassInterfaceType.AutoDual)]
#endif
public class ProviderType : Single, IProviderType, INameValueItem
{
public ProviderType()
{
}
#region Properties
virtual public string Type
{
get
{
return this.GetString(ProviderTypes.f_Type);
}
}
virtual public System.Int32 DataType
{
get
{
return this.GetInt32(ProviderTypes.f_DataType);
}
}
virtual public System.Int32 ColumnSize
{
get
{
return this.GetInt32(ProviderTypes.f_ColumnSize);
}
}
virtual public string LiteralPrefix
{
get
{
return this.GetString(ProviderTypes.f_LiteralPrefix);
}
}
virtual public string LiteralSuffix
{
get
{
return this.GetString(ProviderTypes.f_LiteralSuffix);
}
}
virtual public string CreateParams
{
get
{
return this.GetString(ProviderTypes.f_CreateParams);
}
}
virtual public System.Boolean IsNullable
{
get
{
return this.GetBool(ProviderTypes.f_IsNullable);
}
}
virtual public System.Boolean IsCaseSensitive
{
get
{
return this.GetBool(ProviderTypes.f_IsCaseSensitive);
}
}
virtual public string Searchable
{
get
{
return this.GetString(ProviderTypes.f_Searchable);
}
}
virtual public System.Boolean IsUnsigned
{
get
{
return this.GetBool(ProviderTypes.f_IsUnsigned);
}
}
virtual public System.Boolean HasFixedPrecScale
{
get
{
return this.GetBool(ProviderTypes.f_HasFixedPrecScale);
}
}
virtual public System.Boolean CanBeAutoIncrement
{
get
{
return this.GetBool(ProviderTypes.f_CanBeAutoIncrement);
}
}
virtual public string LocalType
{
get
{
return this.GetString(ProviderTypes.f_LocalType);
}
}
virtual public System.Int32 MinimumScale
{
get
{
return this.GetInt32(ProviderTypes.f_MinimumScale);
}
}
virtual public System.Int32 MaximumScale
{
get
{
return this.GetInt32(ProviderTypes.f_MaximumScale);
}
}
virtual public Guid TypeGuid
{
get
{
return this.GetGuid(ProviderTypes.f_TypeGuid);
}
}
virtual public string TypeLib
{
get
{
return this.GetString(ProviderTypes.f_TypeLib);
}
}
virtual public string Version
{
get
{
return this.GetString(ProviderTypes.f_Version);
}
}
virtual public System.Boolean IsLong
{
get
{
return this.GetBool(ProviderTypes.f_IsLong);
}
}
virtual public System.Boolean BestMatch
{
get
{
return this.GetBool(ProviderTypes.f_BestMatch);
}
}
virtual public System.Boolean IsFixedLength
{
get
{
return this.GetBool(ProviderTypes.f_IsFixedLength);
}
}
#endregion
#region INameValueCollection Members
public string ItemName
{
get
{
return this.Type;
}
}
public string ItemValue
{
get
{
return this.Type;
}
}
#endregion
internal ProviderTypes ProviderTypes = null;
}
}
| |
namespace System.Web.UI.WebControls {
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using System.Web.UI;
public sealed class TreeNodeCollection : ICollection, IStateManager {
private List<TreeNode> _list;
private TreeNode _owner;
private bool _updateParent;
private int _version;
private bool _isTrackingViewState;
private List<LogItem> _log;
public TreeNodeCollection() : this(null, true) {
}
public TreeNodeCollection(TreeNode owner) : this(owner, true) {
}
internal TreeNodeCollection(TreeNode owner, bool updateParent) {
_owner = owner;
_list = new List<TreeNode>();
_updateParent = updateParent;
}
public int Count {
get {
return _list.Count;
}
}
public bool IsSynchronized {
get {
return ((ICollection)_list).IsSynchronized;
}
}
private List<LogItem> Log {
get {
if (_log == null) {
_log = new List<LogItem>();
}
return _log;
}
}
public object SyncRoot {
get {
return ((ICollection)_list).SyncRoot;
}
}
public TreeNode this[int index] {
get {
return _list[index];
}
}
public void Add(TreeNode child) {
AddAt(Count, child);
}
public void AddAt(int index, TreeNode child) {
if (child == null) {
throw new ArgumentNullException("child");
}
if (_updateParent) {
if (child.Owner != null && child.Parent == null) {
child.Owner.Nodes.Remove(child);
}
if (child.Parent != null) {
child.Parent.ChildNodes.Remove(child);
}
if (_owner != null) {
child.SetParent(_owner);
child.SetOwner(_owner.Owner);
}
}
_list.Insert(index, child);
_version++;
if (_isTrackingViewState) {
((IStateManager)child).TrackViewState();
child.SetDirty();
}
Log.Add(new LogItem(LogItemType.Insert, index, _isTrackingViewState));
}
public void Clear() {
if (this.Count == 0) return;
if (_owner != null) {
TreeView owner = _owner.Owner;
if (owner != null) {
// Clear checked nodes if necessary
if (owner.CheckedNodes.Count != 0) {
owner.CheckedNodes.Clear();
}
TreeNode current = owner.SelectedNode;
// Check if the selected item is under this collection
while (current != null) {
if (this.Contains(current)) {
owner.SetSelectedNode(null);
break;
}
current = current.Parent;
}
}
}
foreach (TreeNode node in _list) {
node.SetParent(null);
}
_list.Clear();
_version++;
if (_isTrackingViewState) {
// Clearing invalidates all previous log entries, so we can just clear them out and save some space
Log.Clear();
}
Log.Add(new LogItem(LogItemType.Clear, 0, _isTrackingViewState));
}
public void CopyTo(TreeNode[] nodeArray, int index) {
((ICollection)this).CopyTo(nodeArray, index);
}
public bool Contains(TreeNode c) {
return _list.Contains(c);
}
internal TreeNode FindNode(string[] path, int pos) {
if (pos == path.Length) {
return _owner;
}
string pathPart = TreeView.UnEscape(path[pos]);
for (int i = 0; i < Count; i++) {
TreeNode node = this[i];
if (node.Value == pathPart) {
return node.ChildNodes.FindNode(path, pos + 1);
}
}
return null;
}
public IEnumerator GetEnumerator() {
return new TreeNodeCollectionEnumerator(this);
}
public int IndexOf(TreeNode value) {
return _list.IndexOf(value);
}
public void Remove(TreeNode value) {
if (value == null) {
throw new ArgumentNullException("value");
}
int index = _list.IndexOf(value);
if (index != -1) {
RemoveAt(index);
}
}
public void RemoveAt(int index) {
TreeNode node = _list[index];
if (_updateParent) {
TreeView owner = node.Owner;
if (owner != null) {
if (owner.CheckedNodes.Count != 0) {
// We have to scan the whole tree of subnodes to remove any checked nodes
// (and unselect the selected node if it is a descendant).
// That could badly hurt performance, except that removing a node is a pretty
// exceptional event.
UnCheckUnSelectRecursive(node);
}
else {
// otherwise, we can just climb the tree up from the selected node
// to see if it is a descendant of the removed node.
TreeNode current = owner.SelectedNode;
// Check if the selected item is under this collection
while (current != null) {
if (current == node) {
owner.SetSelectedNode(null);
break;
}
current = current.Parent;
}
}
}
node.SetParent(null);
}
_list.RemoveAt(index);
_version++;
Log.Add(new LogItem(LogItemType.Remove, index, _isTrackingViewState));
}
internal void SetDirty() {
foreach (LogItem item in Log) {
item.Tracked = true;
}
for (int i = 0; i < Count; i++) {
this[i].SetDirty();
}
}
private static void UnCheckUnSelectRecursive(TreeNode node) {
TreeNodeCollection checkedNodes = node.Owner.CheckedNodes;
if (node.Checked) {
checkedNodes.Remove(node);
}
TreeNode selectedNode = node.Owner.SelectedNode;
if (node == selectedNode) {
node.Owner.SetSelectedNode(null);
selectedNode = null;
}
// Only recurse if there could be some more work to do
if (selectedNode != null || checkedNodes.Count != 0) {
foreach (TreeNode child in node.ChildNodes) {
UnCheckUnSelectRecursive(child);
}
}
}
#region ICollection implementation
void ICollection.CopyTo(Array array, int index) {
if (!(array is TreeNode[])) {
throw new ArgumentException(SR.GetString(SR.TreeNodeCollection_InvalidArrayType), "array");
}
_list.CopyTo((TreeNode[])array, index);
}
#endregion
#region IStateManager implementation
/// <internalonly/>
bool IStateManager.IsTrackingViewState {
get {
return _isTrackingViewState;
}
}
/// <internalonly/>
void IStateManager.LoadViewState(object state) {
object[] nodeState = (object[])state;
if (nodeState != null) {
if (nodeState[0] != null) {
string logString = (string)nodeState[0];
// Process each log entry
string[] items = logString.Split(',');
for (int i = 0; i < items.Length; i++) {
string[] parts = items[i].Split(':');
LogItemType type = (LogItemType)Int32.Parse(parts[0], CultureInfo.InvariantCulture);
int index = Int32.Parse(parts[1], CultureInfo.InvariantCulture);
if (type == LogItemType.Insert) {
if (_owner != null && _owner.Owner != null) {
AddAt(index, _owner.Owner.CreateNode());
}
else {
AddAt(index, new TreeNode());
}
}
else if (type == LogItemType.Remove) {
RemoveAt(index);
}
else if (type == LogItemType.Clear) {
Clear();
}
}
}
for (int i = 0; i < nodeState.Length - 1; i++) {
if ((nodeState[i + 1] != null) && (this[i] != null)) {
((IStateManager)this[i]).LoadViewState(nodeState[i + 1]);
}
}
}
}
/// <internalonly/>
object IStateManager.SaveViewState() {
object[] nodes = new object[Count + 1];
bool hasViewState = false;
if ((_log != null) && (_log.Count > 0)) {
// Construct a string representation of the log, delimiting entries with commas
// and seperator command and index with a colon
StringBuilder builder = new StringBuilder();
int realLogCount = 0;
for (int i = 0; i < _log.Count; i++) {
LogItem item = _log[i];
if (item.Tracked) {
builder.Append((int)item.Type);
builder.Append(":");
builder.Append(item.Index);
if (i < (_log.Count - 1)) {
builder.Append(",");
}
realLogCount++;
}
}
if (realLogCount > 0) {
nodes[0] = builder.ToString();
hasViewState = true;
}
}
for (int i = 0; i < Count; i++) {
nodes[i + 1] = ((IStateManager)this[i]).SaveViewState();
if (nodes[i + 1] != null) {
hasViewState = true;
}
}
return (hasViewState ? nodes : null);
}
/// <internalonly/>
void IStateManager.TrackViewState() {
_isTrackingViewState = true;
for (int i = 0; i < Count; i++) {
((IStateManager)this[i]).TrackViewState();
}
}
#endregion
/// <devdoc>
/// Convenience class for storing and using log entries.
/// </devdoc>
private class LogItem {
private LogItemType _type;
private int _index;
private bool _tracked;
public LogItem(LogItemType type, int index, bool tracked) {
_type = type;
_index = index;
_tracked = tracked;
}
public int Index {
get {
return _index;
}
}
public bool Tracked {
get {
return _tracked;
}
set {
_tracked = value;
}
}
public LogItemType Type {
get {
return _type;
}
}
}
/// <devdoc>
/// Convenience enumeration for identifying log commands
/// </devdoc>
private enum LogItemType {
Insert = 0,
Remove = 1,
Clear = 2
}
// This is a copy of the ArrayListEnumeratorSimple in ArrayList.cs
private class TreeNodeCollectionEnumerator : IEnumerator {
private TreeNodeCollection list;
private int index;
private int version;
private TreeNode currentElement;
internal TreeNodeCollectionEnumerator(TreeNodeCollection list) {
this.list = list;
this.index = -1;
version = list._version;
}
public bool MoveNext() {
if (version != list._version)
throw new InvalidOperationException(SR.GetString(SR.ListEnumVersionMismatch));
if (index < (list.Count - 1)) {
index++;
currentElement = list[index];
return true;
}
else
index = list.Count;
return false;
}
object IEnumerator.Current {
get {
return Current;
}
}
public TreeNode Current {
get {
if (index == -1)
throw new InvalidOperationException(SR.GetString(SR.ListEnumCurrentOutOfRange));
if (index >= list.Count)
throw new InvalidOperationException(SR.GetString(SR.ListEnumCurrentOutOfRange));
return currentElement;
}
}
public void Reset() {
if (version != list._version)
throw new InvalidOperationException(SR.GetString(SR.ListEnumVersionMismatch));
currentElement = null;
index = -1;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using Magecrawl.EngineInterfaces;
using Magecrawl.Interfaces;
using Magecrawl.StatusEffects;
using Magecrawl.StatusEffects.Interfaces;
using Magecrawl.Utilities;
namespace Magecrawl.Actors
{
public abstract class Character : ICharacterCore, IXmlSerializable
{
public Point Position { get; set; }
public int CT { get; internal set; }
public abstract int CurrentHP { get; }
public abstract int MaxHP { get; }
public string Name { get; internal set; }
public abstract int Vision { get; }
public abstract IWeapon CurrentWeapon { get; }
public bool IsAlive
{
get
{
return CurrentHP > 0;
}
}
private int m_uniqueID;
public int UniqueID
{
get
{
return m_uniqueID;
}
}
public string DisplayName
{
get
{
return Name;
}
}
private double m_ctIncreaseModifier;
public double CTIncreaseModifier
{
get
{
double modifier = GetTotalDoubleAttributeValue("CTIncreaseModifierBonus");
return modifier == 0 ? m_ctIncreaseModifier : m_ctIncreaseModifier * modifier;
}
}
private double m_ctCostModifierToMove;
public double CTCostModifierToMove
{
get
{
double modifier = GetTotalDoubleAttributeValue("CTCostModifierToMoveBonus");
return modifier == 0 ? m_ctCostModifierToMove : m_ctCostModifierToMove * modifier;
}
}
private double m_ctCostModifierToAct;
public double CTCostModifierToAct
{
get
{
double modifier = GetTotalDoubleAttributeValue("CTCostModifierToActBonus");
return modifier == 0 ? m_ctCostModifierToAct : m_ctCostModifierToAct * modifier;
}
}
private static int s_idCounter = 0;
protected List<IStatusEffectCore> m_effects;
public Character() : this("", Point.Invalid, 0, 0, 0)
{
m_effects = new List<IStatusEffectCore>();
}
public Character(string name, Point p) : this(name, p, 1.0, 1.0, 1.0)
{
m_effects = new List<IStatusEffectCore>();
}
public Character(string name, Point p, double ctIncreaseModifer, double ctMoveCost, double ctActCost)
{
Position = p;
CT = 0;
Name = name;
m_ctIncreaseModifier = ctIncreaseModifer;
m_ctCostModifierToMove = ctMoveCost;
m_ctCostModifierToAct = ctActCost;
m_effects = new List<IStatusEffectCore>();
m_uniqueID = s_idCounter;
s_idCounter++;
}
public virtual double CTCostModifierToAttack
{
get
{
return CurrentWeapon.CTCostToAttack;
}
}
public abstract double Evade { get; }
// Returns amount actually healed by
public abstract int Heal(int toHeal, bool magical);
public abstract void Damage(int dmg);
public abstract void DamageJustStamina(int dmg);
public abstract bool IsDead
{
get;
}
public abstract DiceRoll MeleeDamage { get; }
public abstract double MeleeCTCost { get; }
public virtual void IncreaseCT(int increase)
{
CT += increase;
}
public virtual void DecreaseCT(int decrease)
{
CT -= decrease;
// Remove short term effects if ct <= 0
List<IShortTermStatusEffect> shortTermEffects = m_effects.OfType<IShortTermStatusEffect>().ToList();
shortTermEffects.ForEach(e => e.DecreaseCT(CT + decrease, CT));
foreach (IShortTermStatusEffect effect in shortTermEffects.Where(e => e.CTLeft <= 0))
RemoveEffect(effect);
// Remove any long term effects that have been "dismissed"
List<ILongTermStatusEffect> longTermEffectsToRemove = m_effects.OfType<ILongTermStatusEffect>().Where(a => a.Dismissed).ToList();
foreach (ILongTermStatusEffect effect in longTermEffectsToRemove)
RemoveEffect(effect);
}
public virtual void AddEffect(IStatusEffectCore effectToAdd)
{
m_effects.Add(effectToAdd);
effectToAdd.Apply(this);
}
public virtual void RemoveEffect(IStatusEffectCore effectToRemove)
{
m_effects.Remove(effectToRemove);
effectToRemove.Remove(this);
}
public IEnumerable<IStatusEffectCore> Effects
{
get
{
return m_effects;
}
}
public virtual int GetTotalAttributeValue(string attribute)
{
return 0;
}
public virtual double GetTotalDoubleAttributeValue(string attribute)
{
return 0;
}
public virtual bool HasAttribute(string attribute)
{
return false;
}
#region SaveLoad
public virtual System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public virtual void ReadXml(XmlReader reader)
{
Position = Position.ReadXml(reader);
Name = reader.ReadElementContentAsString();
CT = reader.ReadElementContentAsInt();
m_uniqueID = reader.ReadElementContentAsInt();
m_ctIncreaseModifier = reader.ReadElementContentAsDouble();
m_ctCostModifierToMove = reader.ReadElementContentAsDouble();
m_ctCostModifierToAct = reader.ReadElementContentAsDouble();
ListSerialization.ReadListFromXML(
reader,
innerReader =>
{
string typeName = reader.ReadElementContentAsString();
bool longTerm = Boolean.Parse(reader.ReadElementContentAsString());
IStatusEffectCore effect = EffectFactory.CreateEffectBaseObject(typeName, longTerm);
effect.ReadXml(reader);
AddEffect(effect);
});
}
public virtual void WriteXml(XmlWriter writer)
{
m_effects.ForEach(a => a.Remove(this));
Position.WriteToXml(writer, "Position");
writer.WriteElementString("Name", Name);
writer.WriteElementString("CT", CT.ToString());
writer.WriteElementString("UniqueID", m_uniqueID.ToString());
writer.WriteElementString("CTIncraseModifier", CTIncreaseModifier.ToString());
writer.WriteElementString("CTCostModifierToMove", CTCostModifierToMove.ToString());
writer.WriteElementString("CTCostModifierToAct", CTCostModifierToAct.ToString());
ListSerialization.WriteListToXML(writer, m_effects.ToList(), "Effect");
m_effects.ForEach(a => a.Apply(this));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using Sharpmake;
[module: Sharpmake.Include("Modules/Dementia/Dementia.sharpmake.cs")]
[module: Sharpmake.Include("Modules/ImGui/ImGui.sharpmake.cs")]
[module: Sharpmake.Include("Modules/Moonlight/Moonlight.sharpmake.cs")]
[module: Sharpmake.Include("Modules/Havana/Havana.sharpmake.cs")]
[module: Sharpmake.Include("Tools/BaseProject.sharpmake.cs")]
[module: Sharpmake.Include("Tools/CommonTarget.sharpmake.cs")]
[module: Sharpmake.Include("Tools/HUB/MitchHub.sharpmake.cs")]
[module: Sharpmake.Include("Tools/SharpmakeProject.sharpmake.cs")]
public abstract class BaseGameProject : BaseProject
{
public BaseGameProject()
: base()
{
SourceRootPath = @"Game/Source";
}
public override void ConfigureAll(Project.Configuration conf, CommonTarget target)
{
base.ConfigureAll(conf, target);
conf.Output = Configuration.OutputType.Lib;
conf.SolutionFolder = "Apps/Game";
conf.IncludePaths.Add("[project.SourceRootPath]");
conf.LibraryFiles.Add("[project.Name]");
conf.AddPublicDependency<Engine>(target);
}
}
[Generate]
public class EntryPointGameProject : BaseProject
{
public EntryPointGameProject()
: base()
{
Name = "Game_EntryPoint";
SourceRootPath = Globals.RootDir + @"/Game_EntryPoint/Source";
NatvisFiles.Add("Engine.natvis");
}
public override void ConfigureAll(Project.Configuration conf, CommonTarget target)
{
base.ConfigureAll(conf, target);
conf.Output = Configuration.OutputType.Exe;
conf.SolutionFolder = "Apps";
if(target.GetPlatform() == Platform.win64)
{
conf.ProjectFileName = @"[project.Name]_[target.Platform]";
}
conf.TargetPath = Globals.RootDir + "/.build/[target.Name]/";
conf.VcxprojUserFile.LocalDebuggerWorkingDirectory = "$(OutDir)";
if(target.SubPlatform == CommonTarget.SubPlatformType.UWP)
{
conf.ConsumeWinRTExtensions.Add("main.cpp");
}
conf.AddPublicDependency<SharpGameProject>(target);
}
}
[Generate]
public class EntryPointGameProjectUWP : EntryPointGameProject
{
public EntryPointGameProjectUWP()
: base()
{
Name = "Game_EntryPoint_UWP";
RootPath = Path.Combine(RootPath, "Game_EntryPoint");
//ResourceFiles.Add(Globals.RootDir + "/Game_EntryPoint/Assets/*.*");
//ResourceFiles.Add();
//ResourceFilesExtensions.Add(".appxmanifest");
}
public override void ConfigureAll(Project.Configuration conf, CommonTarget target)
{
base.ConfigureAll(conf, target);
conf.ProjectPath = Path.Combine(Globals.RootDir, "Game_EntryPoint");
conf.ConsumeWinRTExtensions.Add("main.cpp");
conf.AppxManifestFilePath = Path.Combine(Globals.RootDir, "Game_EntryPoint/Package.appxmanifest");
conf.NeedsAppxManifestFile = true;
conf.IsUniversalWindowsPlatform = true;
conf.PackageCertificateKeyFile = Path.Combine(Globals.RootDir, "Game_EntryPoint/Game_EntryPoint_UWP_TemporaryKey.pfx");
conf.PackageCertificateThumbprint = "60E3DE390F85DDE86FE881ABCB08591FB0B5D556";
conf.Options.Add(Options.Vc.Linker.SubSystem.Windows);
conf.Images.Add("Assets/SplashScreen.scale-200.png");
conf.Images.Add("Assets/LockScreenLogo.scale-200.png");
conf.Images.Add("Assets/Wide310x150Logo.scale-200.png");
conf.Images.Add("Assets/Square44x44Logo.scale-200.png");
conf.Images.Add("Assets/Square44x44Logo.targetsize-24_altform-unplated.png");
conf.Images.Add("Assets/Square150x150Logo.scale-200.png");
conf.Images.Add("Assets/StoreLogo.png");
}
}
[Generate]
public class Engine : BaseProject
{
public Engine()
: base()
{
Name = "MitchEngine";
}
public override void ConfigureAll(Project.Configuration conf, CommonTarget target)
{
base.ConfigureAll(conf, target);
conf.Output = Configuration.OutputType.Lib;
conf.SolutionFolder = "Engine";
conf.PrecompHeader = "PCH.h";
conf.PrecompSource = "PCH.cpp";
conf.IncludePaths.Add(Path.Combine("[project.SharpmakeCsPath]", "Source"));
conf.IncludePaths.Add(Path.Combine("[project.SharpmakeCsPath]", "Modules/Singleton/Source"));
conf.IncludePaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/SDL/include"));
conf.IncludePaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/UltralightSDK/include"));
conf.LibraryPaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/UltralightSDK/lib/[target.SubPlatform]"));
conf.LibraryFiles.Add("MitchEngine");
conf.LibraryFiles.Add("Ultralight");
conf.LibraryFiles.Add("UltralightCore");
conf.LibraryFiles.Add("WebCore");
conf.AddPublicDependency<Dementia>(target);
conf.AddPublicDependency<ImGui>(target);
conf.AddPublicDependency<Moonlight>(target);
if(!string.IsNullOrEmpty(Globals.FMOD_Win64_Dir) || !string.IsNullOrEmpty(Globals.FMOD_UWP_Dir))
{
conf.Defines.Add("FMOD_ENABLED");
conf.Defines.Add("_DISABLE_EXTENDED_ALIGNED_STORAGE");
}
}
public override void ConfigureWin64(Configuration conf, CommonTarget target)
{
base.ConfigureWin64(conf, target);
conf.LibraryPaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/Lib/Assimp/[target.Optimization]"));
conf.LibraryPaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/Lib/SDL/Win64/[target.Optimization]"));
conf.LibraryPaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/Lib/Bullet/Win64/[target.Optimization]"));
conf.LibraryFiles.Add("assimp-vc140-mt.lib");
conf.LibraryFiles.Add("AppCore");
if (!string.IsNullOrEmpty(Globals.FMOD_Win64_Dir))
{
conf.IncludePaths.Add(Path.Combine(Globals.FMOD_Win64_Dir, "api/core/inc"));
conf.LibraryPaths.Add(Path.Combine(Globals.FMOD_Win64_Dir, "api/core/lib/x64"));
conf.LibraryFiles.Add("fmodL_vc.lib");
// FMOD DLL
{
var copyDirBuildStep = new Configuration.BuildStepCopy(
Path.Combine(Globals.FMOD_Win64_Dir, "api/core/lib/x64"),
Globals.RootDir + "/.build/[target.Name]");
copyDirBuildStep.IsFileCopy = false;
copyDirBuildStep.CopyPattern = "*.dll";
conf.EventPostBuildExe.Add(copyDirBuildStep);
}
}
// Do a virtual method for different configs
if (target.Optimization == Optimization.Debug)
{
conf.LibraryFiles.Add("SDL2d.lib");
conf.LibraryFiles.Add("BulletCollision_Debug.lib");
conf.LibraryFiles.Add("BulletDynamics_Debug.lib");
conf.LibraryFiles.Add("LinearMath_Debug.lib");
conf.LibraryFiles.Add("zlibstaticd.lib");
}
else
{
conf.LibraryFiles.Add("SDL2.lib");
conf.LibraryFiles.Add("BulletCollision_MinsizeRel.lib");
conf.LibraryFiles.Add("BulletDynamics_MinsizeRel.lib");
conf.LibraryFiles.Add("LinearMath_MinsizeRel.lib");
conf.LibraryFiles.Add("zlibstatic.lib");
}
// SDL DLL
{
var copyDirBuildStep = new Configuration.BuildStepCopy(
@"[project.SharpmakeCsPath]/ThirdParty/Lib/SDL/Win64/[target.Optimization]",
Globals.RootDir + "/.build/[target.Name]");
copyDirBuildStep.IsFileCopy = false;
copyDirBuildStep.CopyPattern = "*.dll";
conf.EventPostBuildExe.Add(copyDirBuildStep);
}
// Ultralight DLL
{
var copyDirBuildStep = new Configuration.BuildStepCopy(
@"[project.SharpmakeCsPath]/ThirdParty/UltralightSDK/bin/Win64/",
Globals.RootDir + "/.build/[target.Name]");
conf.EventPostBuildExe.Add(copyDirBuildStep);
}
}
public override void ConfigureUWP(Configuration conf, CommonTarget target)
{
base.ConfigureUWP(conf, target);
conf.LibraryPaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/Lib/Assimp/[target.Optimization]"));
conf.LibraryPaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/Lib/Bullet/Win64/[target.Optimization]"));
conf.LibraryPaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/Lib/SDL/UWP/[target.Optimization]"));
conf.LibraryPaths.Add("$(VCInstallDir)\\lib\\store\\amd64");
conf.LibraryPaths.Add("$(VCInstallDir)\\lib\\amd64");
conf.LibraryFiles.Add("assimp-vc140-mt.lib");
conf.LibraryFiles.Add("SDL2.lib");
if (target.Optimization == Optimization.Debug)
{
conf.LibraryFiles.Add("BulletCollision_Debug.lib");
conf.LibraryFiles.Add("BulletDynamics_Debug.lib");
conf.LibraryFiles.Add("LinearMath_Debug.lib");
conf.LibraryFiles.Add("zlibstaticd.lib");
}
else
{
conf.LibraryFiles.Add("BulletCollision_MinsizeRel.lib");
conf.LibraryFiles.Add("BulletDynamics_MinsizeRel.lib");
conf.LibraryFiles.Add("LinearMath_MinsizeRel.lib");
conf.LibraryFiles.Add("zlibstatic.lib");
}
}
public override void ConfigureMac(Configuration conf, CommonTarget target)
{
base.ConfigureMac(conf, target);
// What the actual fuck lmao v
conf.LibraryPaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/Lib/Bullet/macOS/Debug"));
conf.LibraryPaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/Lib/SDL/macOS/Debug"));
conf.LibraryPaths.Add(Path.Combine("[project.SharpmakeCsPath]", "ThirdParty/Lib/Assimp/macOS/[target.Optimization]"));
conf.LibraryFiles.Add("assimp");
conf.LibraryFiles.Add("BulletCollision");
conf.LibraryFiles.Add("BulletDynamics");
conf.LibraryFiles.Add("LinearMath");
conf.LibraryFiles.Add("SDL2d");
conf.LibraryFiles.Add("AppCore");
}
}
public class BaseGameSolution : Solution
{
public BaseGameSolution()
: base(typeof(CommonTarget))
{
Name = "BaseGameSolution";
AddTargets(CommonTarget.GetDefaultTargets());
IsFileNameToLower = false;
}
[Configure]
public virtual void ConfigureAll(Solution.Configuration conf, CommonTarget target)
{
conf.SolutionPath = @"[solution.SharpmakeCsPath]";
conf.SolutionFileName = "[solution.Name]";
Globals.RootDir = Path.GetFullPath("../");
conf.AddProject<Dementia>(target);
conf.AddProject<ImGui>(target);
conf.AddProject<Moonlight>(target);
conf.AddProject<Engine>(target);
if(target.SelectedMode == CommonTarget.Mode.Editor)
{
conf.AddProject<Havana>(target);
conf.AddProject<MitchHubProject>(target);
}
else
{
if (target.SubPlatform == CommonTarget.SubPlatformType.UWP)
{
conf.AddProject<EntryPointGameProjectUWP>(target);
}
else
{
conf.AddProject<EntryPointGameProject>(target);
}
}
if(target.Platform == Platform.win64)
{
conf.AddProject<UserSharpmakeProject>(target);
}
conf.AddProject<SharpGameProject>(target);
}
}
public class Globals
{
public static string RootDir = string.Empty;
public static string FMOD_Win64_Dir = string.Empty;
public static string FMOD_UWP_Dir = string.Empty;
}
public static class Main
{
[Sharpmake.Main]
public static void SharpmakeMain(Sharpmake.Arguments arguments)
{
KitsRootPaths.SetUseKitsRootForDevEnv(DevEnv.vs2019, KitsRootEnum.KitsRoot10, Options.Vc.General.WindowsTargetPlatformVersion.v10_0_19041_0);
arguments.Generate<SharpGameSolution>();
}
}
| |
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* Primary Updates
*
* Copyright 2011-2012 Marc-Andre Moreau <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Runtime.InteropServices;
namespace FreeRDP
{
[StructLayout(LayoutKind.Sequential)]
public unsafe struct rdpBrush
{
public UInt32 x;
public UInt32 y;
public UInt32 bpp;
public UInt32 style;
public UInt32 hatch;
public UInt32 index;
public UInt32 data;
public fixed byte p8x8[8];
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct OrderInfo
{
public UInt32 orderType;
public UInt32 fieldFlags;
public rdpBounds* bounds;
public Int32 deltaBoundLeft;
public Int32 deltaBoundTop;
public Int32 deltaBoundRight;
public Int32 deltaBoundBottom;
public int deltaCoordinates;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct DstBltOrder
{
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nWidth;
public Int32 nHeight;
public UInt32 bRop;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct PatBltOrder
{
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nWidth;
public Int32 nHeight;
public UInt32 bRop;
public UInt32 backColor;
public UInt32 foreColor;
public rdpBrush* brush;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct ScrBltOrder
{
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nWidth;
public Int32 nHeight;
public UInt32 bRop;
public Int32 nXSrc;
public Int32 nYSrc;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct OpaqueRectOrder
{
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nWidth;
public Int32 nHeight;
public UInt32 color;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct DrawNineGridOrder
{
public Int32 srcLeft;
public Int32 srcTop;
public Int32 srcRight;
public Int32 srcBottom;
public UInt32 bitmapId;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct DeltaRect
{
public Int32 left;
public Int32 top;
public Int32 width;
public Int32 height;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct MultiDstBltOrder
{
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nWidth;
public Int32 nHeight;
public UInt32 bRop;
public UInt32 numRectangles;
public UInt32 cbData;
//public fixed DeltaRect rectangles[45];
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct MultiPatBltOrder
{
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nWidth;
public Int32 nHeight;
public UInt32 bRop;
public UInt32 backColor;
public UInt32 foreColor;
public rdpBrush brush;
public UInt32 numRectangles;
public UInt32 cbData;
//public fixed DeltaRect rectangles[45];
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct MultiScrBltOrder
{
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nWidth;
public Int32 nHeight;
public UInt32 bRop;
public Int32 nXSrc;
public Int32 nYSrc;
public UInt32 numRectangles;
public UInt32 cbData;
//public fixed DeltaRect rectangles[45];
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct MultiOpaqueRectOrder
{
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nWidth;
public Int32 nHeight;
public UInt32 color;
public UInt32 numRectangles;
public UInt32 cbData;
//public fixed DeltaRect rectangles[45];
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct MultiDrawNineGridOrder
{
public Int32 srcLeft;
public Int32 srcTop;
public Int32 srcRight;
public Int32 srcBottom;
public UInt32 bitmapId;
public UInt32 nDeltaEntries;
public UInt32 cbData;
public byte* codeDeltaList;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct LineToOrder
{
public UInt32 backMode;
public Int32 nXStart;
public Int32 nYStart;
public Int32 nXEnd;
public Int32 nYEnd;
public UInt32 backColor;
public UInt32 bRop2;
public UInt32 penStyle;
public UInt32 penWidth;
public UInt32 penColor;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct DeltaPoint
{
public Int32 x;
public Int32 y;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct PolylineOrder
{
public Int32 xStart;
public Int32 yStart;
public UInt32 bRop2;
public UInt32 penColor;
public UInt32 numPoints;
public UInt32 cbData;
public DeltaPoint* points;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct MemBltOrder
{
public UInt32 cacheId;
public UInt32 colorIndex;
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nWidth;
public Int32 nHeight;
public UInt32 bRop;
public Int32 nXSrc;
public Int32 nYSrc;
public UInt32 cacheIndex;
public rdpBitmap* bitmap;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct Mem3BltOrder
{
public UInt32 cacheId;
public UInt32 colorIndex;
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nWidth;
public Int32 nHeight;
public UInt32 bRop;
public Int32 nXSrc;
public Int32 nYSrc;
public UInt32 backColor;
public UInt32 foreColor;
public rdpBrush brush;
public UInt32 cacheIndex;
public rdpBitmap* bitmap;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct SaveBitmapOrder
{
public UInt32 savedBitmapPosition;
public Int32 nLeftRect;
public Int32 nTopRect;
public Int32 nRightRect;
public Int32 nBottomRect;
public UInt32 operation;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct GlyphFragmentIndex
{
public UInt32 index;
public UInt32 delta;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct GlyphFragment
{
public UInt32 operation;
public UInt32 index;
public UInt32 size;
public UInt32 nindices;
public GlyphFragmentIndex* indices;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct GlyphIndexOrder
{
public UInt32 cacheId;
public UInt32 flAccel;
public UInt32 ulCharInc;
public UInt32 fOpRedundant;
public UInt32 backColor;
public UInt32 foreColor;
public Int32 bkLeft;
public Int32 bkTop;
public Int32 bkRight;
public Int32 bkBottom;
public Int32 opLeft;
public Int32 opTop;
public Int32 opRight;
public Int32 opBottom;
public rdpBrush brush;
public Int32 x;
public Int32 y;
public UInt32 cbData;
public fixed byte data[256];
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct FastIndexOrder
{
public UInt32 cacheId;
public UInt32 flAccel;
public UInt32 ulCharInc;
public UInt32 backColor;
public UInt32 foreColor;
public Int32 bkLeft;
public Int32 bkTop;
public Int32 bkRight;
public Int32 bkBottom;
public Int32 opLeft;
public Int32 opTop;
public Int32 opRight;
public Int32 opBottom;
public int opaqueRect;
public Int32 x;
public Int32 y;
public UInt32 cbData;
public fixed byte data[256];
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct FastGlyphOrder
{
public UInt32 cacheId;
public UInt32 flAccel;
public UInt32 ulCharInc;
public UInt32 backColor;
public UInt32 foreColor;
public Int32 bkLeft;
public Int32 bkTop;
public Int32 bkRight;
public Int32 bkBottom;
public Int32 opLeft;
public Int32 opTop;
public Int32 opRight;
public Int32 opBottom;
public Int32 x;
public Int32 y;
public UInt32 cbData;
public fixed byte data[256];
public void* glyphData;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct PolygonSCOrder
{
public Int32 xStart;
public Int32 yStart;
public UInt32 bRop2;
public UInt32 fillMode;
public UInt32 brushColor;
public UInt32 nDeltaEntries;
public UInt32 cbData;
public byte* codeDeltaList;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct PolygonCBOrder
{
public Int32 xStart;
public Int32 yStart;
public UInt32 bRop2;
public UInt32 fillMode;
public UInt32 backColor;
public UInt32 foreColor;
public rdpBrush brush;
public UInt32 nDeltaEntries;
public UInt32 cbData;
public byte* codeDeltaList;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct EllipseSCOrder
{
public Int32 leftRect;
public Int32 topRect;
public Int32 rightRect;
public Int32 bottomRect;
public UInt32 bRop2;
public UInt32 fillMode;
public UInt32 color;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct EllipseCBOrder
{
public Int32 leftRect;
public Int32 topRect;
public Int32 rightRect;
public Int32 bottomRect;
public UInt32 bRop2;
public UInt32 fillMode;
public UInt32 backColor;
public UInt32 foreColor;
public rdpBrush brush;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct rdpPrimaryUpdate
{
public rdpContext* context;
public fixed UInt32 paddingA[16-1];
public IntPtr DstBlt;
public IntPtr PatBlt;
public IntPtr ScrBlt;
public IntPtr OpaqueRect;
public IntPtr DrawNineGrid;
public IntPtr MultiDstBlt;
public IntPtr MultiPatBlt;
public IntPtr MultiScrBlt;
public IntPtr MultiOpaqueRect;
public IntPtr MultiDrawNineGrid;
public IntPtr LineTo;
public IntPtr Polyline;
public IntPtr MemBlt;
public IntPtr Mem3Blt;
public IntPtr SaveBitmap;
public IntPtr GlyphIndex;
public IntPtr FastIndex;
public IntPtr FastGlyph;
public IntPtr PolygonSC;
public IntPtr PolygonCB;
public IntPtr EllipseSC;
public IntPtr EllipseCB;
public fixed UInt32 paddingB[48-38];
}
public unsafe interface IPrimaryUpdate
{
void DstBlt(rdpContext* context, DstBltOrder* dstblt);
void PatBlt(rdpContext* context, PatBltOrder* patblt);
void ScrBlt(rdpContext* context, ScrBltOrder* scrblt);
void OpaqueRect(rdpContext* context, OpaqueRectOrder* opaqueRect);
void DrawNineGrid(rdpContext* context, DrawNineGridOrder* drawNineGrid);
void MultiDstBlt(rdpContext* context, MultiDstBltOrder* multi_dstblt);
void MultiPatBlt(rdpContext* context, MultiPatBltOrder* multi_patblt);
void MultiScrBlt(rdpContext* context, MultiScrBltOrder* multi_scrblt);
void MultiOpaqueRect(rdpContext* context, MultiOpaqueRectOrder* multi_opaque_rect);
void MultiDrawNineGrid(rdpContext* context, MultiDrawNineGridOrder* multi_draw_nine_grid);
void LineTo(rdpContext* context, LineToOrder* line_to);
void Polyline(rdpContext* context, PolylineOrder* polyline);
void MemBlt(rdpContext* context, MemBltOrder* memblt);
void Mem3Blt(rdpContext* context, Mem3BltOrder* mem3blt);
void SaveBitmap(rdpContext* context, SaveBitmapOrder* save_bitmap);
void GlyphIndex(rdpContext* context, GlyphIndexOrder* glyph_index);
void FastIndex(rdpContext* context, FastIndexOrder* fast_index);
void FastGlyph(rdpContext* context, FastGlyphOrder* fast_glyph);
void PolygonSC(rdpContext* context, PolygonSCOrder* polygon_sc);
void PolygonCB(rdpContext* context, PolygonCBOrder* polygon_cb);
void EllipseSC(rdpContext* context, EllipseSCOrder* ellipse_sc);
void EllipseCB(rdpContext* context, EllipseCBOrder* ellipse_cb);
}
public unsafe class PrimaryUpdate
{
private freerdp* instance;
private rdpContext* context;
private rdpUpdate* update;
private rdpPrimaryUpdate* primary;
delegate void DstBltDelegate(rdpContext* context, DstBltOrder* dstBlt);
delegate void PatBltDelegate(rdpContext* context, PatBltOrder* patBlt);
delegate void ScrBltDelegate(rdpContext* context, ScrBltOrder* scrBlt);
delegate void OpaqueRectDelegate(rdpContext* context, OpaqueRectOrder* opaqueRect);
delegate void DrawNineGridDelegate(rdpContext* context, DrawNineGridOrder* drawNineGrid);
delegate void MultiDstBltDelegate(rdpContext* context, MultiDstBltOrder* multiDstBlt);
delegate void MultiPatBltDelegate(rdpContext* context, MultiPatBltOrder* multiPatBlt);
delegate void MultiScrBltDelegate(rdpContext* context, MultiScrBltOrder* multiScrBlt);
delegate void MultiOpaqueRectDelegate(rdpContext* context, MultiOpaqueRectOrder* multiOpaqueRect);
delegate void MultiDrawNineGridDelegate(rdpContext* context, MultiDrawNineGridOrder* multiDrawNineGrid);
delegate void LineToDelegate(rdpContext* context, LineToOrder* lineTo);
delegate void PolylineDelegate(rdpContext* context, PolylineOrder* polyline);
delegate void MemBltDelegate(rdpContext* context, MemBltOrder* memBlt);
delegate void Mem3BltDelegate(rdpContext* context, Mem3BltOrder* mem3Blt);
delegate void SaveBitmapDelegate(rdpContext* context, SaveBitmapOrder* saveBitmap);
delegate void GlyphIndexDelegate(rdpContext* context, GlyphIndexOrder* glyphIndex);
delegate void FastIndexDelegate(rdpContext* context, FastIndexOrder* fastIndex);
delegate void FastGlyphDelegate(rdpContext* context, FastGlyphOrder* fastGlyph);
delegate void PolygonSCDelegate(rdpContext* context, PolygonSCOrder* polygonSC);
delegate void PolygonCBDelegate(rdpContext* context, PolygonCBOrder* polygonCB);
delegate void EllipseSCDelegate(rdpContext* context, EllipseSCOrder* ellipseSC);
delegate void EllipseCBDelegate(rdpContext* context, EllipseCBOrder* ellipseCB);
private DstBltDelegate DstBlt;
private PatBltDelegate PatBlt;
private ScrBltDelegate ScrBlt;
private OpaqueRectDelegate OpaqueRect;
private DrawNineGridDelegate DrawNineGrid;
private MultiDstBltDelegate MultiDstBlt;
private MultiPatBltDelegate MultiPatBlt;
private MultiScrBltDelegate MultiScrBlt;
private MultiOpaqueRectDelegate MultiOpaqueRect;
private MultiDrawNineGridDelegate MultiDrawNineGrid;
private LineToDelegate LineTo;
private PolylineDelegate Polyline;
private MemBltDelegate MemBlt;
private Mem3BltDelegate Mem3Blt;
private SaveBitmapDelegate SaveBitmap;
private GlyphIndexDelegate GlyphIndex;
private FastIndexDelegate FastIndex;
private FastGlyphDelegate FastGlyph;
private PolygonSCDelegate PolygonSC;
private PolygonCBDelegate PolygonCB;
private EllipseSCDelegate EllipseSC;
private EllipseCBDelegate EllipseCB;
public PrimaryUpdate(rdpContext* context)
{
this.context = context;
this.instance = context->instance;
this.update = instance->update;
this.primary = update->primary;
}
public void RegisterInterface(IPrimaryUpdate iPrimary)
{
DstBlt = new DstBltDelegate(iPrimary.DstBlt);
PatBlt = new PatBltDelegate(iPrimary.PatBlt);
ScrBlt = new ScrBltDelegate(iPrimary.ScrBlt);
OpaqueRect = new OpaqueRectDelegate(iPrimary.OpaqueRect);
DrawNineGrid = new DrawNineGridDelegate(iPrimary.DrawNineGrid);
MultiDstBlt = new MultiDstBltDelegate(iPrimary.MultiDstBlt);
MultiPatBlt = new MultiPatBltDelegate(iPrimary.MultiPatBlt);
MultiScrBlt = new MultiScrBltDelegate(iPrimary.MultiScrBlt);
MultiOpaqueRect = new MultiOpaqueRectDelegate(iPrimary.MultiOpaqueRect);
MultiDrawNineGrid = new MultiDrawNineGridDelegate(iPrimary.MultiDrawNineGrid);
LineTo = new LineToDelegate(iPrimary.LineTo);
Polyline = new PolylineDelegate(iPrimary.Polyline);
MemBlt = new MemBltDelegate(iPrimary.MemBlt);
Mem3Blt = new Mem3BltDelegate(iPrimary.Mem3Blt);
SaveBitmap = new SaveBitmapDelegate(iPrimary.SaveBitmap);
GlyphIndex = new GlyphIndexDelegate(iPrimary.GlyphIndex);
FastIndex = new FastIndexDelegate(iPrimary.FastIndex);
FastGlyph = new FastGlyphDelegate(iPrimary.FastGlyph);
PolygonSC = new PolygonSCDelegate(iPrimary.PolygonSC);
PolygonCB = new PolygonCBDelegate(iPrimary.PolygonCB);
EllipseSC = new EllipseSCDelegate(iPrimary.EllipseSC);
EllipseCB = new EllipseCBDelegate(iPrimary.EllipseCB);
primary->DstBlt = Marshal.GetFunctionPointerForDelegate(DstBlt);
primary->PatBlt = Marshal.GetFunctionPointerForDelegate(PatBlt);
primary->ScrBlt = Marshal.GetFunctionPointerForDelegate(ScrBlt);
primary->OpaqueRect = Marshal.GetFunctionPointerForDelegate(OpaqueRect);
primary->DrawNineGrid = Marshal.GetFunctionPointerForDelegate(DrawNineGrid);
primary->MultiDstBlt = Marshal.GetFunctionPointerForDelegate(MultiDstBlt);
primary->MultiPatBlt = Marshal.GetFunctionPointerForDelegate(MultiPatBlt);
primary->MultiScrBlt = Marshal.GetFunctionPointerForDelegate(MultiScrBlt);
primary->MultiOpaqueRect = Marshal.GetFunctionPointerForDelegate(MultiOpaqueRect);
primary->MultiDrawNineGrid = Marshal.GetFunctionPointerForDelegate(MultiDrawNineGrid);
primary->LineTo = Marshal.GetFunctionPointerForDelegate(LineTo);
primary->Polyline = Marshal.GetFunctionPointerForDelegate(Polyline);
primary->MemBlt = Marshal.GetFunctionPointerForDelegate(MemBlt);
primary->Mem3Blt = Marshal.GetFunctionPointerForDelegate(Mem3Blt);
primary->SaveBitmap = Marshal.GetFunctionPointerForDelegate(SaveBitmap);
primary->GlyphIndex = Marshal.GetFunctionPointerForDelegate(GlyphIndex);
primary->FastIndex = Marshal.GetFunctionPointerForDelegate(FastIndex);
primary->FastGlyph = Marshal.GetFunctionPointerForDelegate(FastGlyph);
primary->PolygonSC = Marshal.GetFunctionPointerForDelegate(PolygonSC);
primary->PolygonCB = Marshal.GetFunctionPointerForDelegate(PolygonCB);
primary->EllipseSC = Marshal.GetFunctionPointerForDelegate(EllipseSC);
primary->EllipseCB = Marshal.GetFunctionPointerForDelegate(EllipseCB);
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009 Oracle. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using BerkeleyDB.Internal;
namespace BerkeleyDB {
/// <summary>
/// A class representing a HashDatabase. The Hash format is an extensible,
/// dynamic hashing scheme.
/// </summary>
public class HashDatabase : Database {
private HashFunctionDelegate hashHandler;
private EntryComparisonDelegate compareHandler;
private EntryComparisonDelegate dupCompareHandler;
private BDB_CompareDelegate doCompareRef;
private BDB_HashDelegate doHashRef;
private BDB_CompareDelegate doDupCompareRef;
#region Constructors
private HashDatabase(DatabaseEnvironment env, uint flags)
: base(env, flags) { }
internal HashDatabase(BaseDatabase clone) : base(clone) { }
private void Config(HashDatabaseConfig cfg) {
base.Config(cfg);
/*
* Database.Config calls set_flags, but that doesn't get the Hash
* specific flags. No harm in calling it again.
*/
db.set_flags(cfg.flags);
if (cfg.HashFunction != null)
HashFunction = cfg.HashFunction;
// The duplicate comparison function cannot change.
if (cfg.DuplicateCompare != null)
DupCompare = cfg.DuplicateCompare;
if (cfg.fillFactorIsSet)
db.set_h_ffactor(cfg.FillFactor);
if (cfg.nelemIsSet)
db.set_h_nelem(cfg.TableSize);
if (cfg.HashComparison != null)
Compare = cfg.HashComparison;
}
/// <summary>
/// Instantiate a new HashDatabase object and open the database
/// represented by <paramref name="Filename"/>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation
/// will be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <returns>A new, open database object</returns>
public static HashDatabase Open(
string Filename, HashDatabaseConfig cfg) {
return Open(Filename, null, cfg, null);
}
/// <summary>
/// Instantiate a new HashDatabase object and open the database
/// represented by <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/>.
/// </summary>
/// <remarks>
/// <para>
/// If both <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/> are null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe. If
/// <paramref name="Filename"/> is null and
/// <paramref name="DatabaseName"/> is non-null, the database can be
/// opened by other threads of control and will be replicated to client
/// sites in any replication group.
/// </para>
/// <para>
/// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation
/// will be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="DatabaseName">
/// This parameter allows applications to have multiple databases in a
/// single file. Although no DatabaseName needs to be specified, it is
/// an error to attempt to open a second database in a file that was not
/// initially created using a database name.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <returns>A new, open database object</returns>
public static HashDatabase Open(
string Filename, string DatabaseName, HashDatabaseConfig cfg) {
return Open(Filename, DatabaseName, cfg, null);
}
/// <summary>
/// Instantiate a new HashDatabase object and open the database
/// represented by <paramref name="Filename"/>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but
/// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will
/// be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open. Also note that the
/// transaction must be committed before the object is closed.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>A new, open database object</returns>
public static HashDatabase Open(
string Filename, HashDatabaseConfig cfg, Transaction txn) {
return Open(Filename, null, cfg, txn);
}
/// <summary>
/// Instantiate a new HashDatabase object and open the database
/// represented by <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/>.
/// </summary>
/// <remarks>
/// <para>
/// If both <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/> are null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe. If
/// <paramref name="Filename"/> is null and
/// <paramref name="DatabaseName"/> is non-null, the database can be
/// opened by other threads of control and will be replicated to client
/// sites in any replication group.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but
/// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will
/// be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open. Also note that the
/// transaction must be committed before the object is closed.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="DatabaseName">
/// This parameter allows applications to have multiple databases in a
/// single file. Although no DatabaseName needs to be specified, it is
/// an error to attempt to open a second database in a file that was not
/// initially created using a database name.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>A new, open database object</returns>
public static HashDatabase Open(string Filename,
string DatabaseName, HashDatabaseConfig cfg, Transaction txn) {
HashDatabase ret = new HashDatabase(cfg.Env, 0);
ret.Config(cfg);
ret.db.open(Transaction.getDB_TXN(txn),
Filename, DatabaseName, DBTYPE.DB_HASH, cfg.openFlags, 0);
ret.isOpen = true;
return ret;
}
#endregion Constructors
#region Callbacks
private static int doDupCompare(
IntPtr dbp, IntPtr dbt1p, IntPtr dbt2p) {
DB db = new DB(dbp, false);
DBT dbt1 = new DBT(dbt1p, false);
DBT dbt2 = new DBT(dbt2p, false);
return ((HashDatabase)(db.api_internal)).DupCompare(
DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2));
}
private static uint doHash(IntPtr dbp, IntPtr datap, uint len) {
DB db = new DB(dbp, false);
byte[] t_data = new byte[len];
Marshal.Copy(datap, t_data, 0, (int)len);
return ((HashDatabase)(db.api_internal)).hashHandler(t_data);
}
private static int doCompare(IntPtr dbp, IntPtr dbtp1, IntPtr dbtp2) {
DB db = new DB(dbp, false);
DBT dbt1 = new DBT(dbtp1, false);
DBT dbt2 = new DBT(dbtp2, false);
return ((HashDatabase)(db.api_internal)).compareHandler(
DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2));
}
#endregion Callbacks
#region Properties
/// <summary>
/// The Hash key comparison function. The comparison function is called
/// whenever it is necessary to compare a key specified by the
/// application with a key currently stored in the tree.
/// </summary>
public EntryComparisonDelegate Compare {
get { return compareHandler; }
private set {
if (value == null)
db.set_h_compare(null);
else if (compareHandler == null) {
if (doCompareRef == null)
doCompareRef = new BDB_CompareDelegate(doCompare);
db.set_h_compare(doCompareRef);
}
compareHandler = value;
}
}
/// <summary>
/// The duplicate data item comparison function.
/// </summary>
public EntryComparisonDelegate DupCompare {
get { return dupCompareHandler; }
private set {
/* Cannot be called after open. */
if (value == null)
db.set_dup_compare(null);
else if (dupCompareHandler == null) {
if (doDupCompareRef == null)
doDupCompareRef = new BDB_CompareDelegate(doDupCompare);
db.set_dup_compare(doDupCompareRef);
}
dupCompareHandler = value;
}
}
/// <summary>
/// Whether the insertion of duplicate data items in the database is
/// permitted, and whether duplicates items are sorted.
/// </summary>
public DuplicatesPolicy Duplicates {
get {
uint flags = 0;
db.get_flags(ref flags);
if ((flags & DbConstants.DB_DUPSORT) != 0)
return DuplicatesPolicy.SORTED;
else if ((flags & DbConstants.DB_DUP) != 0)
return DuplicatesPolicy.UNSORTED;
else
return DuplicatesPolicy.NONE;
}
}
/// <summary>
/// The desired density within the hash table.
/// </summary>
public uint FillFactor {
get {
uint ret = 0;
db.get_h_ffactor(ref ret);
return ret;
}
}
/// <summary>
/// A user-defined hash function; if no hash function is specified, a
/// default hash function is used.
/// </summary>
public HashFunctionDelegate HashFunction {
get { return hashHandler; }
private set {
if (value == null)
db.set_h_hash(null);
else if (hashHandler == null) {
if (doHashRef == null)
doHashRef = new BDB_HashDelegate(doHash);
db.set_h_hash(doHashRef);
}
hashHandler = value;
}
}
/// <summary>
/// An estimate of the final size of the hash table.
/// </summary>
public uint TableSize {
get {
uint ret = 0;
db.get_h_nelem(ref ret);
return ret;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Create a database cursor.
/// </summary>
/// <returns>A newly created cursor</returns>
public new HashCursor Cursor() {
return Cursor(new CursorConfig(), null);
}
/// <summary>
/// Create a database cursor with the given configuration.
/// </summary>
/// <param name="cfg">
/// The configuration properties for the cursor.
/// </param>
/// <returns>A newly created cursor</returns>
public new HashCursor Cursor(CursorConfig cfg) {
return Cursor(cfg, null);
}
/// <summary>
/// Create a transactionally protected database cursor.
/// </summary>
/// <param name="txn">
/// The transaction context in which the cursor may be used.
/// </param>
/// <returns>A newly created cursor</returns>
public new HashCursor Cursor(Transaction txn) {
return Cursor(new CursorConfig(), txn);
}
/// <summary>
/// Create a transactionally protected database cursor with the given
/// configuration.
/// </summary>
/// <param name="cfg">
/// The configuration properties for the cursor.
/// </param>
/// <param name="txn">
/// The transaction context in which the cursor may be used.
/// </param>
/// <returns>A newly created cursor</returns>
public new HashCursor Cursor(CursorConfig cfg, Transaction txn) {
return new HashCursor(
db.cursor(Transaction.getDB_TXN(txn), cfg.flags), Pagesize);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public HashStats FastStats() {
return Stats(null, true, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public HashStats FastStats(Transaction txn) {
return Stats(txn, true, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <overloads>
/// <para>
/// Among other things, this method makes it possible for applications
/// to request key and record counts without incurring the performance
/// penalty of traversing the entire database.
/// </para>
/// <para>
/// The statistical information is described by the
/// <see cref="BTreeStats"/>, <see cref="HashStats"/>,
/// <see cref="QueueStats"/>, and <see cref="RecnoStats"/> classes.
/// </para>
/// </overloads>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="isoDegree">
/// The level of isolation for database reads.
/// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for
/// databases which did not specify
/// <see cref="DatabaseConfig.ReadUncommitted"/>.
/// </param>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public HashStats FastStats(Transaction txn, Isolation isoDegree) {
return Stats(txn, true, isoDegree);
}
/// <summary>
/// Return pages to the filesystem that are already free and at the end
/// of the file.
/// </summary>
/// <returns>
/// The number of database pages returned to the filesystem
/// </returns>
public uint TruncateUnusedPages() {
return TruncateUnusedPages(null);
}
/// <summary>
/// Return pages to the filesystem that are already free and at the end
/// of the file.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// The number of database pages returned to the filesystem
/// </returns>
public uint TruncateUnusedPages(Transaction txn) {
DB_COMPACT cdata = new DB_COMPACT();
db.compact(Transaction.getDB_TXN(txn),
null, null, cdata, DbConstants.DB_FREELIST_ONLY, null);
return cdata.compact_pages_truncated;
}
/// <summary>
/// Store the key/data pair in the database only if it does not already
/// appear in the database.
/// </summary>
/// <param name="key">The key to store in the database</param>
/// <param name="data">The data item to store in the database</param>
public void PutNoDuplicate(DatabaseEntry key, DatabaseEntry data) {
PutNoDuplicate(key, data, null);
}
/// <summary>
/// Store the key/data pair in the database only if it does not already
/// appear in the database.
/// </summary>
/// <param name="key">The key to store in the database</param>
/// <param name="data">The data item to store in the database</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
public void PutNoDuplicate(
DatabaseEntry key, DatabaseEntry data, Transaction txn) {
Put(key, data, txn, DbConstants.DB_NODUPDATA);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <returns>Database statistical information.</returns>
public HashStats Stats() {
return Stats(null, false, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>Database statistical information.</returns>
public HashStats Stats(Transaction txn) {
return Stats(txn, false, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <overloads>
/// The statistical information is described by
/// <see cref="BTreeStats"/>.
/// </overloads>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="isoDegree">
/// The level of isolation for database reads.
/// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for
/// databases which did not specify
/// <see cref="DatabaseConfig.ReadUncommitted"/>.
/// </param>
/// <returns>Database statistical information.</returns>
public HashStats Stats(Transaction txn, Isolation isoDegree) {
return Stats(txn, false, isoDegree);
}
private HashStats Stats(
Transaction txn, bool fast, Isolation isoDegree) {
uint flags = 0;
flags |= fast ? DbConstants.DB_FAST_STAT : 0;
switch (isoDegree) {
case Isolation.DEGREE_ONE:
flags |= DbConstants.DB_READ_UNCOMMITTED;
break;
case Isolation.DEGREE_TWO:
flags |= DbConstants.DB_READ_COMMITTED;
break;
}
HashStatStruct st = db.stat_hash(Transaction.getDB_TXN(txn), flags);
return new HashStats(st);
}
#endregion Methods
}
}
| |
using System;
using System.Text;
using System.Web;
using Umbraco.Core;
using umbraco;
namespace Umbraco.Web
{
public static class UriUtility
{
static string _appPath;
static string _appPathPrefix;
static UriUtility()
{
SetAppDomainAppVirtualPath(HttpRuntime.AppDomainAppVirtualPath);
}
// internal for unit testing only
internal static void SetAppDomainAppVirtualPath(string appPath)
{
_appPath = appPath ?? "/";
_appPathPrefix = _appPath;
if (_appPathPrefix == "/")
_appPathPrefix = String.Empty;
}
// will be "/" or "/foo"
public static string AppPath
{
get { return _appPath; }
}
// will be "" or "/foo"
public static string AppPathPrefix
{
get { return _appPathPrefix; }
}
// adds the virtual directory if any
// see also VirtualPathUtility.ToAbsolute
// FIXME
public static string ToAbsolute(string url)
{
//return ResolveUrl(url);
url = url.TrimStart('~');
return _appPathPrefix + url;
}
// strips the virtual directory if any
// see also VirtualPathUtility.ToAppRelative
public static string ToAppRelative(string virtualPath)
{
if (virtualPath.InvariantStartsWith(_appPathPrefix))
virtualPath = virtualPath.Substring(_appPathPrefix.Length);
if (virtualPath.Length == 0)
virtualPath = "/";
return virtualPath;
}
// maps an internal umbraco uri to a public uri
// ie with virtual directory, .aspx if required...
public static Uri UriFromUmbraco(Uri uri)
{
var path = uri.GetSafeAbsolutePath();
if (path != "/")
{
if (!GlobalSettings.UseDirectoryUrls)
path += ".aspx";
else if (UmbracoSettings.AddTrailingSlash)
path += "/";
}
path = ToAbsolute(path);
return uri.Rewrite(path);
}
// maps a public uri to an internal umbraco uri
// ie no virtual directory, no .aspx, lowercase...
public static Uri UriToUmbraco(Uri uri)
{
// note: no need to decode uri here because we're returning a uri
// so it will be re-encoded anyway
var path = uri.GetSafeAbsolutePath();
path = path.ToLower();
path = ToAppRelative(path); // strip vdir if any
//we need to check if the path is /default.aspx because this will occur when using a
//web server pre IIS 7 when requesting the root document
//if this is the case we need to change it to '/'
if (path.StartsWith("/default.aspx", StringComparison.InvariantCultureIgnoreCase))
{
string rempath = path.Substring("/default.aspx".Length, path.Length - "/default.aspx".Length);
path = rempath.StartsWith("/") ? rempath : "/" + rempath;
}
if (path != "/")
{
path = path.TrimEnd('/');
}
//if any part of the path contains .aspx, replace it with nothing.
//sometimes .aspx is not at the end since we might have /home/sub1.aspx/customtemplate
path = path.Replace(".aspx", "");
return uri.Rewrite(path);
}
#region ResolveUrl
// http://www.codeproject.com/Articles/53460/ResolveUrl-in-ASP-NET-The-Perfect-Solution
// note
// if browsing http://example.com/sub/page1.aspx then
// ResolveUrl("page2.aspx") returns "/page2.aspx"
// Page.ResolveUrl("page2.aspx") returns "/sub/page2.aspx" (relative...)
//
public static string ResolveUrl(string relativeUrl)
{
if (relativeUrl == null) throw new ArgumentNullException("relativeUrl");
if (relativeUrl.Length == 0 || relativeUrl[0] == '/' || relativeUrl[0] == '\\')
return relativeUrl;
int idxOfScheme = relativeUrl.IndexOf(@"://", StringComparison.Ordinal);
if (idxOfScheme != -1)
{
int idxOfQM = relativeUrl.IndexOf('?');
if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl;
}
StringBuilder sbUrl = new StringBuilder();
sbUrl.Append(_appPathPrefix);
if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/');
// found question mark already? query string, do not touch!
bool foundQM = false;
bool foundSlash; // the latest char was a slash?
if (relativeUrl.Length > 1
&& relativeUrl[0] == '~'
&& (relativeUrl[1] == '/' || relativeUrl[1] == '\\'))
{
relativeUrl = relativeUrl.Substring(2);
foundSlash = true;
}
else foundSlash = false;
foreach (char c in relativeUrl)
{
if (!foundQM)
{
if (c == '?') foundQM = true;
else
{
if (c == '/' || c == '\\')
{
if (foundSlash) continue;
else
{
sbUrl.Append('/');
foundSlash = true;
continue;
}
}
else if (foundSlash) foundSlash = false;
}
}
sbUrl.Append(c);
}
return sbUrl.ToString();
}
#endregion
#region Uri string utilities
public static bool HasScheme(string uri)
{
return uri.IndexOf("://") > 0;
}
public static string StartWithScheme(string uri)
{
return StartWithScheme(uri, null);
}
public static string StartWithScheme(string uri, string scheme)
{
return HasScheme(uri) ? uri : String.Format("{0}://{1}", scheme ?? Uri.UriSchemeHttp, uri);
}
public static string EndPathWithSlash(string uri)
{
var pos1 = Math.Max(0, uri.IndexOf('?'));
var pos2 = Math.Max(0, uri.IndexOf('#'));
var pos = Math.Min(pos1, pos2);
var path = pos > 0 ? uri.Substring(0, pos) : uri;
path = path.EnsureEndsWith('/');
if (pos > 0)
path += uri.Substring(pos);
return path;
}
public static string TrimPathEndSlash(string uri)
{
var pos1 = Math.Max(0, uri.IndexOf('?'));
var pos2 = Math.Max(0, uri.IndexOf('#'));
var pos = Math.Min(pos1, pos2);
var path = pos > 0 ? uri.Substring(0, pos) : uri;
path = path.TrimEnd('/');
if (pos > 0)
path += uri.Substring(pos);
return path;
}
#endregion
/// <summary>
/// Returns an faull url with the host, port, etc...
/// </summary>
/// <param name="absolutePath">An absolute path (i.e. starts with a '/' )</param>
/// <param name="httpContext"> </param>
/// <returns></returns>
/// <remarks>
/// Based on http://stackoverflow.com/questions/3681052/get-absolute-url-from-relative-path-refactored-method
/// </remarks>
internal static Uri ToFullUrl(string absolutePath, HttpContextBase httpContext)
{
if (httpContext == null) throw new ArgumentNullException("httpContext");
if (String.IsNullOrEmpty(absolutePath))
throw new ArgumentNullException("absolutePath");
if (!absolutePath.StartsWith("/"))
throw new FormatException("The absolutePath specified does not start with a '/'");
return new Uri(absolutePath, UriKind.Relative).MakeAbsolute(httpContext.Request.Url);
}
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Diagnostics;
using BitUtil = Lucene.Net.Util.BitUtil;
namespace Lucene.Net.Codecs.Lucene40
{
/*
* 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 ChecksumIndexInput = Lucene.Net.Store.ChecksumIndexInput;
using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory;
using Directory = Lucene.Net.Store.Directory;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using IMutableBits = Lucene.Net.Util.IMutableBits;
/// <summary>
/// Optimized implementation of a vector of bits. This is more-or-less like
/// <c>java.util.BitSet</c>, but also includes the following:
/// <list type="bullet">
/// <item><description>a count() method, which efficiently computes the number of one bits;</description></item>
/// <item><description>optimized read from and write to disk;</description></item>
/// <item><description>inlinable get() method;</description></item>
/// <item><description>store and load, as bit set or d-gaps, depending on sparseness;</description></item>
/// </list>
/// <para/>
/// @lucene.internal
/// </summary>
// pkg-private: if this thing is generally useful then it can go back in .util,
// but the serialization must be here underneath the codec.
internal sealed class BitVector : IMutableBits
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
private byte[] bits;
private int size;
private int count;
private int version;
/// <summary>
/// Constructs a vector capable of holding <paramref name="n"/> bits. </summary>
public BitVector(int n)
{
size = n;
bits = new byte[GetNumBytes(size)];
count = 0;
}
internal BitVector(byte[] bits, int size)
{
this.bits = bits;
this.size = size;
count = -1;
}
private int GetNumBytes(int size)
{
int bytesLength = (int)((uint)size >> 3);
if ((size & 7) != 0)
{
bytesLength++;
}
return bytesLength;
}
public object Clone()
{
byte[] copyBits = new byte[bits.Length];
Array.Copy(bits, 0, copyBits, 0, bits.Length);
BitVector clone = new BitVector(copyBits, size);
clone.count = count;
return clone;
}
/// <summary>
/// Sets the value of <paramref name="bit"/> to one. </summary>
public void Set(int bit)
{
if (bit >= size)
{
throw new IndexOutOfRangeException("bit=" + bit + " size=" + size);
}
bits[bit >> 3] |= (byte)(1 << (bit & 7));
count = -1;
}
/// <summary>
/// Sets the value of <paramref name="bit"/> to <c>true</c>, and
/// returns <c>true</c> if bit was already set.
/// </summary>
public bool GetAndSet(int bit)
{
if (bit >= size)
{
throw new IndexOutOfRangeException("bit=" + bit + " size=" + size);
}
int pos = bit >> 3;
int v = bits[pos];
int flag = 1 << (bit & 7);
if ((flag & v) != 0)
{
return true;
}
else
{
bits[pos] = (byte)(v | flag);
if (count != -1)
{
count++;
if (Debugging.AssertsEnabled) Debugging.Assert(count <= size);
}
return false;
}
}
/// <summary>
/// Sets the value of <paramref name="bit"/> to zero. </summary>
public void Clear(int bit)
{
if (bit >= size)
{
throw new IndexOutOfRangeException(bit.ToString());
}
bits[bit >> 3] &= (byte)(~(1 << (bit & 7)));
count = -1;
}
public bool GetAndClear(int bit)
{
if (bit >= size)
{
throw new IndexOutOfRangeException(bit.ToString());
}
int pos = bit >> 3;
int v = bits[pos];
int flag = 1 << (bit & 7);
if ((flag & v) == 0)
{
return false;
}
else
{
bits[pos] &= (byte)(~flag);
if (count != -1)
{
count--;
if (Debugging.AssertsEnabled) Debugging.Assert(count >= 0);
}
return true;
}
}
/// <summary>
/// Returns <c>true</c> if <paramref name="bit"/> is one and
/// <c>false</c> if it is zero.
/// </summary>
public bool Get(int bit)
{
if (Debugging.AssertsEnabled) Debugging.Assert(bit >= 0 && bit < size, () => "bit " + bit + " is out of bounds 0.." + (size - 1));
return (bits[bit >> 3] & (1 << (bit & 7))) != 0;
}
// LUCENENET specific - removing this because 1) size is not .NETified and 2) it is identical to Length anyway
///// <summary>
///// Returns the number of bits in this vector. this is also one greater than
///// the number of the largest valid bit number.
///// </summary>
//public int Size()
//{
// return size;
//}
/// <summary>
/// Returns the number of bits in this vector. This is also one greater than
/// the number of the largest valid bit number.
/// <para/>
/// This is the equivalent of either size() or length() in Lucene.
/// </summary>
public int Length => size;
/// <summary>
/// Returns the total number of one bits in this vector. This is efficiently
/// computed and cached, so that, if the vector is not changed, no
/// recomputation is done for repeated calls.
/// </summary>
public int Count() // LUCENENET TODO: API - make into a property
{
// if the vector has been modified
if (count == -1)
{
int c = 0;
int end = bits.Length;
for (int i = 0; i < end; i++)
{
c += BitUtil.BitCount(bits[i]); // sum bits per byte
}
count = c;
}
if (Debugging.AssertsEnabled) Debugging.Assert(count <= size, () => "count=" + count + " size=" + size);
return count;
}
/// <summary>
/// For testing </summary>
public int GetRecomputedCount()
{
int c = 0;
int end = bits.Length;
for (int i = 0; i < end; i++)
{
c += BitUtil.BitCount(bits[i]); // sum bits per byte
}
return c;
}
private static string CODEC = "BitVector";
// Version before version tracking was added:
public readonly static int VERSION_PRE = -1;
// First version:
public readonly static int VERSION_START = 0;
// Changed DGaps to encode gaps between cleared bits, not
// set:
public readonly static int VERSION_DGAPS_CLEARED = 1;
// added checksum
public readonly static int VERSION_CHECKSUM = 2;
// Increment version to change it:
public readonly static int VERSION_CURRENT = VERSION_CHECKSUM;
public int Version => version;
/// <summary>
/// Writes this vector to the file <paramref name="name"/> in Directory
/// <paramref name="d"/>, in a format that can be read by the constructor
/// <see cref="BitVector(Directory, string, IOContext)"/>.
/// </summary>
public void Write(Directory d, string name, IOContext context)
{
if (Debugging.AssertsEnabled) Debugging.Assert(!(d is CompoundFileDirectory));
IndexOutput output = d.CreateOutput(name, context);
try
{
output.WriteInt32(-2);
CodecUtil.WriteHeader(output, CODEC, VERSION_CURRENT);
if (IsSparse)
{
// sparse bit-set more efficiently saved as d-gaps.
WriteClearedDgaps(output);
}
else
{
WriteBits(output);
}
CodecUtil.WriteFooter(output);
if (Debugging.AssertsEnabled) Debugging.Assert(VerifyCount());
}
finally
{
IOUtils.Dispose(output);
}
}
/// <summary>
/// Invert all bits. </summary>
public void InvertAll()
{
if (count != -1)
{
count = size - count;
}
if (bits.Length > 0)
{
for (int idx = 0; idx < bits.Length; idx++)
{
bits[idx] = (byte)(~bits[idx]);
}
ClearUnusedBits();
}
}
private void ClearUnusedBits()
{
// Take care not to invert the "unused" bits in the
// last byte:
if (bits.Length > 0)
{
int lastNBits = size & 7;
if (lastNBits != 0)
{
int mask = (1 << lastNBits) - 1;
bits[bits.Length - 1] &= (byte)mask;
}
}
}
/// <summary>
/// Set all bits. </summary>
public void SetAll()
{
Arrays.Fill(bits, (byte)0xff);
ClearUnusedBits();
count = size;
}
/// <summary>
/// Write as a bit set. </summary>
private void WriteBits(IndexOutput output)
{
output.WriteInt32(Length); // write size
output.WriteInt32(Count()); // write count
output.WriteBytes(bits, bits.Length);
}
/// <summary>
/// Write as a d-gaps list. </summary>
private void WriteClearedDgaps(IndexOutput output)
{
output.WriteInt32(-1); // mark using d-gaps
output.WriteInt32(Length); // write size
output.WriteInt32(Count()); // write count
int last = 0;
int numCleared = Length - Count();
for (int i = 0; i < bits.Length && numCleared > 0; i++)
{
if (bits[i] != 0xff)
{
output.WriteVInt32(i - last);
output.WriteByte(bits[i]);
last = i;
numCleared -= (8 - BitUtil.BitCount(bits[i]));
if (Debugging.AssertsEnabled) Debugging.Assert(numCleared >= 0 || (i == (bits.Length - 1) && numCleared == -(8 - (size & 7))));
}
}
}
/// <summary>
/// Indicates if the bit vector is sparse and should be saved as a d-gaps list, or dense, and should be saved as a bit set. </summary>
private bool IsSparse
{
get
{
int clearedCount = Length - Count();
if (clearedCount == 0)
{
return true;
}
int avgGapLength = bits.Length / clearedCount;
// expected number of bytes for vInt encoding of each gap
int expectedDGapBytes;
if (avgGapLength <= (1 << 7))
{
expectedDGapBytes = 1;
}
else if (avgGapLength <= (1 << 14))
{
expectedDGapBytes = 2;
}
else if (avgGapLength <= (1 << 21))
{
expectedDGapBytes = 3;
}
else if (avgGapLength <= (1 << 28))
{
expectedDGapBytes = 4;
}
else
{
expectedDGapBytes = 5;
}
// +1 because we write the byte itself that contains the
// set bit
int bytesPerSetBit = expectedDGapBytes + 1;
// note: adding 32 because we start with ((int) -1) to indicate d-gaps format.
long expectedBits = 32 + 8 * bytesPerSetBit * clearedCount;
// note: factor is for read/write of byte-arrays being faster than vints.
const long factor = 10;
return factor * expectedBits < Length;
}
}
/// <summary>
/// Constructs a bit vector from the file <paramref name="name"/> in Directory
/// <paramref name="d"/>, as written by the <see cref="Write(Directory, string, IOContext)"/> method.
/// </summary>
public BitVector(Directory d, string name, IOContext context)
{
ChecksumIndexInput input = d.OpenChecksumInput(name, context);
try
{
int firstInt = input.ReadInt32();
if (firstInt == -2)
{
// New format, with full header & version:
version = CodecUtil.CheckHeader(input, CODEC, VERSION_START, VERSION_CURRENT);
size = input.ReadInt32();
}
else
{
version = VERSION_PRE;
size = firstInt;
}
if (size == -1)
{
if (version >= VERSION_DGAPS_CLEARED)
{
ReadClearedDgaps(input);
}
else
{
ReadSetDgaps(input);
}
}
else
{
ReadBits(input);
}
if (version < VERSION_DGAPS_CLEARED)
{
InvertAll();
}
if (version >= VERSION_CHECKSUM)
{
CodecUtil.CheckFooter(input);
}
else
{
#pragma warning disable 612, 618
CodecUtil.CheckEOF(input);
#pragma warning restore 612, 618
}
if (Debugging.AssertsEnabled) Debugging.Assert(VerifyCount());
}
finally
{
input.Dispose();
}
}
// asserts only
private bool VerifyCount()
{
if (Debugging.AssertsEnabled) Debugging.Assert(count != -1);
int countSav = count;
count = -1;
if (Debugging.AssertsEnabled) Debugging.Assert(countSav == Count(), () => "saved count was " + countSav + " but recomputed count is " + count);
return true;
}
/// <summary>
/// Read as a bit set. </summary>
private void ReadBits(IndexInput input)
{
count = input.ReadInt32(); // read count
bits = new byte[GetNumBytes(size)]; // allocate bits
input.ReadBytes(bits, 0, bits.Length);
}
/// <summary>
/// Read as a d-gaps list. </summary>
private void ReadSetDgaps(IndexInput input)
{
size = input.ReadInt32(); // (re)read size
count = input.ReadInt32(); // read count
bits = new byte[GetNumBytes(size)]; // allocate bits
int last = 0;
int n = Count();
while (n > 0)
{
last += input.ReadVInt32();
bits[last] = input.ReadByte();
n -= BitUtil.BitCount(bits[last]);
if (Debugging.AssertsEnabled) Debugging.Assert(n >= 0);
}
}
/// <summary>
/// Read as a d-gaps cleared bits list. </summary>
private void ReadClearedDgaps(IndexInput input)
{
size = input.ReadInt32(); // (re)read size
count = input.ReadInt32(); // read count
bits = new byte[GetNumBytes(size)]; // allocate bits
for (int i = 0; i < bits.Length; ++i)
{
bits[i] = 0xff;
}
ClearUnusedBits();
int last = 0;
int numCleared = Length - Count();
while (numCleared > 0)
{
last += input.ReadVInt32();
bits[last] = input.ReadByte();
numCleared -= 8 - BitUtil.BitCount(bits[last]);
if (Debugging.AssertsEnabled) Debugging.Assert(numCleared >= 0 || (last == (bits.Length - 1) && numCleared == -(8 - (size & 7))));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
namespace System.Net.NetworkInformation
{
// Linux implementation of NetworkChange
public class NetworkChange
{
private static NetworkAddressChangedEventHandler s_addressChangedSubscribers;
private static NetworkAvailabilityChangedEventHandler s_availabilityChangedSubscribers;
private static volatile int s_socket = 0;
// Lock controlling access to delegate subscriptions and socket initialization.
private static readonly object s_subscriberLock = new object();
// Lock controlling access to availability-changed state and timer.
private static readonly object s_availabilityLock = new object();
private static readonly Interop.Sys.NetworkChangeEvent s_networkChangeCallback = ProcessEvent;
// The "leniency" window for NetworkAvailabilityChanged socket events.
// All socket events received within this duration will be coalesced into a
// single event. Generally, many route changed events are fired in succession,
// and we are not interested in all of them, just the fact that network availability
// has potentially changed as a result.
private const int AvailabilityTimerWindowMilliseconds = 150;
private static readonly TimerCallback s_availabilityTimerFiredCallback = OnAvailabilityTimerFired;
private static Timer s_availabilityTimer;
private static bool s_availabilityHasChanged;
// Introduced for supporting design-time loading of System.Windows.dll
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
public static void RegisterNetworkChange(NetworkChange nc) { }
public static event NetworkAddressChangedEventHandler NetworkAddressChanged
{
add
{
lock (s_subscriberLock)
{
if (s_socket == 0)
{
CreateSocket();
}
s_addressChangedSubscribers += value;
}
}
remove
{
lock (s_subscriberLock)
{
if (s_addressChangedSubscribers == null && s_availabilityChangedSubscribers == null)
{
Debug.Assert(s_socket == 0, "s_socket != 0, but there are no subscribers to NetworkAddressChanged or NetworkAvailabilityChanged.");
return;
}
s_addressChangedSubscribers -= value;
if (s_addressChangedSubscribers == null && s_availabilityChangedSubscribers == null)
{
CloseSocket();
}
}
}
}
public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged
{
add
{
lock (s_subscriberLock)
{
if (s_socket == 0)
{
CreateSocket();
}
if (s_availabilityTimer == null)
{
s_availabilityTimer = new Timer(s_availabilityTimerFiredCallback, null, -1, -1);
}
s_availabilityChangedSubscribers += value;
}
}
remove
{
lock (s_subscriberLock)
{
if (s_addressChangedSubscribers == null && s_availabilityChangedSubscribers == null)
{
Debug.Assert(s_socket == 0, "s_socket != 0, but there are no subscribers to NetworkAddressChanged or NetworkAvailabilityChanged.");
return;
}
s_availabilityChangedSubscribers -= value;
if (s_availabilityChangedSubscribers == null)
{
s_availabilityTimer.Dispose();
s_availabilityTimer = null;
if (s_addressChangedSubscribers == null)
{
CloseSocket();
}
}
}
}
}
private static void CreateSocket()
{
Debug.Assert(s_socket == 0, "s_socket != 0, must close existing socket before opening another.");
int newSocket;
Interop.Error result = Interop.Sys.CreateNetworkChangeListenerSocket(out newSocket);
if (result != Interop.Error.SUCCESS)
{
string message = Interop.Sys.GetLastErrorInfo().GetErrorMessage();
throw new NetworkInformationException(message);
}
s_socket = newSocket;
Task.Factory.StartNew(s => LoopReadSocket((int)s), s_socket,
CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
private static void CloseSocket()
{
Debug.Assert(s_socket != 0, "s_socket was 0 when CloseSocket was called.");
Interop.Error result = Interop.Sys.CloseNetworkChangeListenerSocket(s_socket);
if (result != Interop.Error.SUCCESS)
{
string message = Interop.Sys.GetLastErrorInfo().GetErrorMessage();
throw new NetworkInformationException(message);
}
s_socket = 0;
}
private static void LoopReadSocket(int socket)
{
while (socket == s_socket)
{
Interop.Sys.ReadEvents(socket, s_networkChangeCallback);
}
}
private static void ProcessEvent(int socket, Interop.Sys.NetworkChangeKind kind)
{
if (kind != Interop.Sys.NetworkChangeKind.None)
{
lock (s_subscriberLock)
{
if (socket == s_socket)
{
OnSocketEvent(kind);
}
}
}
}
private static void OnSocketEvent(Interop.Sys.NetworkChangeKind kind)
{
switch (kind)
{
case Interop.Sys.NetworkChangeKind.AddressAdded:
case Interop.Sys.NetworkChangeKind.AddressRemoved:
s_addressChangedSubscribers?.Invoke(null, EventArgs.Empty);
break;
case Interop.Sys.NetworkChangeKind.AvailabilityChanged:
lock (s_availabilityLock)
{
if (!s_availabilityHasChanged)
{
s_availabilityTimer.Change(AvailabilityTimerWindowMilliseconds, -1);
}
s_availabilityHasChanged = true;
}
break;
}
}
private static void OnAvailabilityTimerFired(object state)
{
bool changed;
lock (s_availabilityLock)
{
changed = s_availabilityHasChanged;
s_availabilityHasChanged = false;
}
if (changed)
{
s_availabilityChangedSubscribers?.Invoke(null, new NetworkAvailabilityEventArgs(NetworkInterface.GetIsNetworkAvailable()));
}
}
}
}
| |
using GlueTestProject.DataTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlatRedBall.Content.Scene;
using FlatRedBall.Content;
using FlatRedBall.IO;
using FlatRedBall.Debugging;
using FlatRedBall.Performance.Measurement;
using System.IO;
using TMXGlueLib.DataTypes;
using TMXGlueLib;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Animation;
namespace FlatRedBall.TileGraphics
{
public class LayeredTileMap : PositionedObject, IVisible
{
#region Fields
FlatRedBall.Math.PositionedObjectList<MapDrawableBatch> mMapLists = new FlatRedBall.Math.PositionedObjectList<MapDrawableBatch>();
float mRenderingScale = 1;
float mZSplit = 1;
float? mNumberTilesWide;
float? mNumberTilesTall;
float? mWidthPerTile;
float? mHeightPerTile;
#endregion
#region Properties
public Dictionary<string, List<NamedValue>> Properties
{
get;
private set;
} = new Dictionary<string, List<NamedValue>>();
public float RenderingScale
{
get
{
return mRenderingScale;
}
set
{
mRenderingScale = value;
foreach (var map in mMapLists)
{
map.RenderingScale = value;
}
}
}
public float ZSplit
{
get
{
return mZSplit;
}
set
{
for (int i = 0; i < this.mMapLists.Count; i++)
{
mMapLists[i].RelativeZ = mZSplit * i;
}
}
}
public List<FlatRedBall.Math.Geometry.ShapeCollection> ShapeCollections { get; private set; } = new List<FlatRedBall.Math.Geometry.ShapeCollection>();
public FlatRedBall.Math.PositionedObjectList<MapDrawableBatch> MapLayers
{
get
{
return mMapLists;
}
}
bool visible = true;
public bool Visible
{
get
{
return visible;
}
set
{
visible = value;
foreach (var item in this.mMapLists)
{
item.Visible = visible;
}
}
}
/// <summary>
/// Returns the width in world units of the entire map. The map may not visibly extend to this width;
/// </summary>
public float Width
{
get
{
if (mNumberTilesWide.HasValue && mWidthPerTile.HasValue)
{
return mNumberTilesWide.Value * mWidthPerTile.Value;
}
else
{
return 0;
}
}
}
/// <summary>
/// Returns the height in world units of the entire map. The map may not visibly extend to this height;
/// </summary>
public float Height
{
get
{
if (mNumberTilesTall.HasValue && mHeightPerTile.HasValue)
{
return mNumberTilesTall.Value * mHeightPerTile.Value;
}
else
{
return 0;
}
}
}
public LayeredTileMapAnimation Animation { get; set; }
public List<NamedValue> MapProperties { get; set; }
IVisible IVisible.Parent
{
get
{
return Parent as IVisible;
}
}
public bool AbsoluteVisible
{
get
{
if (this.Visible)
{
var parentAsIVisible = this.Parent as IVisible;
if (parentAsIVisible == null || IgnoresParentVisibility)
{
return true;
}
else
{
// this is true, so return if the parent is visible:
return parentAsIVisible.AbsoluteVisible;
}
}
else
{
return false;
}
}
}
public bool IgnoresParentVisibility
{
get;
set;
}
#endregion
public IEnumerable<string> TileNamesWith(string propertyName)
{
foreach (var item in Properties.Values)
{
if (item.Any(item2 => item2.Name == propertyName))
{
var hasName = item.Any(item2 => item2.Name == "Name");
if (hasName)
{
yield return item.First(item2 => item2.Name == "Name").Value as string;
}
}
}
}
public static LayeredTileMap FromScene(string fileName, string contentManagerName)
{
return FromScene(fileName, contentManagerName, false);
}
public static LayeredTileMap FromScene(string fileName, string contentManagerName, bool verifySameTexturePerLayer)
{
Section.GetAndStartContextAndTime("Initial FromScene");
LayeredTileMap toReturn = new LayeredTileMap();
string absoluteFileName = FileManager.MakeAbsolute(fileName);
Section.EndContextAndTime();
Section.GetAndStartContextAndTime("FromFile");
SceneSave ses = SceneSave.FromFile(absoluteFileName);
Section.EndContextAndTime();
Section.GetAndStartContextAndTime("BreaksNStuff");
string oldRelativeDirectory = FileManager.RelativeDirectory;
FileManager.RelativeDirectory = FileManager.GetDirectory(absoluteFileName);
var breaks = GetZBreaks(ses.SpriteList);
int valueBefore = 0;
MapDrawableBatch mdb;
int valueAfter;
float zValue = 0;
Section.EndContextAndTime();
Section.GetAndStartContextAndTime("Create MDBs");
for (int i = 0; i < breaks.Count; i++)
{
valueAfter = breaks[i];
int count = valueAfter - valueBefore;
mdb = MapDrawableBatch.FromSpriteSaves(ses.SpriteList, valueBefore, count, contentManagerName, verifySameTexturePerLayer);
mdb.AttachTo(toReturn, false);
mdb.RelativeZ = zValue;
toReturn.mMapLists.Add(mdb);
zValue += toReturn.mZSplit;
valueBefore = valueAfter;
}
valueAfter = ses.SpriteList.Count;
if (valueBefore != valueAfter)
{
int count = valueAfter - valueBefore;
mdb = MapDrawableBatch.FromSpriteSaves(ses.SpriteList, valueBefore, count, contentManagerName, verifySameTexturePerLayer);
mdb.AttachTo(toReturn, false);
mdb.RelativeZ = zValue;
toReturn.mMapLists.Add(mdb);
}
Section.EndContextAndTime();
FileManager.RelativeDirectory = oldRelativeDirectory;
return toReturn;
}
public static LayeredTileMap FromReducedTileMapInfo(string fileName, string contentManagerName)
{
using (Stream inputStream = FileManager.GetStreamForFile(fileName))
using (BinaryReader binaryReader = new BinaryReader(inputStream))
{
ReducedTileMapInfo rtmi = ReducedTileMapInfo.ReadFrom(binaryReader);
string fullFileName = fileName;
if (FileManager.IsRelative(fullFileName))
{
fullFileName = FileManager.RelativeDirectory + fileName;
}
var toReturn = FromReducedTileMapInfo(rtmi, contentManagerName, fileName);
toReturn.Name = fullFileName;
return toReturn;
}
}
public static LayeredTileMap FromReducedTileMapInfo(TMXGlueLib.DataTypes.ReducedTileMapInfo rtmi, string contentManagerName, string tilbToLoad)
{
var toReturn = new LayeredTileMap();
string oldRelativeDirectory = FileManager.RelativeDirectory;
FileManager.RelativeDirectory = FileManager.GetDirectory(tilbToLoad);
MapDrawableBatch mdb;
if (rtmi.NumberCellsWide != 0)
{
toReturn.mNumberTilesWide = rtmi.NumberCellsWide;
}
if (rtmi.NumberCellsTall != 0)
{
toReturn.mNumberTilesTall = rtmi.NumberCellsTall;
}
toReturn.mWidthPerTile = rtmi.QuadWidth;
toReturn.mHeightPerTile = rtmi.QuadHeight;
for (int i = 0; i < rtmi.Layers.Count; i++)
{
var reducedLayer = rtmi.Layers[i];
mdb = MapDrawableBatch.FromReducedLayer(reducedLayer, toReturn, rtmi, contentManagerName);
mdb.AttachTo(toReturn, false);
mdb.RelativeZ = reducedLayer.Z;
toReturn.mMapLists.Add(mdb);
}
FileManager.RelativeDirectory = oldRelativeDirectory;
return toReturn;
}
public static LayeredTileMap FromTiledMapSave(string fileName, string contentManager)
{
TiledMapSave tms = TiledMapSave.FromFile(fileName);
// Ultimately properties are tied to tiles by the tile name.
// If a tile has no name but it has properties, those properties
// will be lost in the conversion. Therefore, we have to add name properties.
tms.NameUnnamedTilesetTiles();
string directory = FlatRedBall.IO.FileManager.GetDirectory(fileName);
var rtmi = ReducedTileMapInfo.FromTiledMapSave(
tms, 1, 0, directory, FileReferenceType.Absolute);
var toReturn = FromReducedTileMapInfo(rtmi, contentManager, fileName);
foreach (var mapObjectgroup in tms.objectgroup)
{
var shapeCollection = tms.ToShapeCollection(mapObjectgroup.Name);
if (shapeCollection != null && shapeCollection.IsEmpty == false)
{
shapeCollection.Name = mapObjectgroup.Name;
toReturn.ShapeCollections.Add(shapeCollection);
}
}
foreach (var layer in tms.MapLayers)
{
var matchingLayer = toReturn.MapLayers.FirstOrDefault(item => item.Name == layer.Name);
if (matchingLayer != null)
{
if (layer is MapLayer)
{
var mapLayer = layer as MapLayer;
foreach (var propertyValues in mapLayer.properties)
{
matchingLayer.Properties.Add(new NamedValue
{
Name = propertyValues.StrippedName,
Value = propertyValues.value,
Type = propertyValues.Type
});
}
matchingLayer.Visible = mapLayer.visible == 1;
}
}
}
foreach (var tileset in tms.Tilesets)
{
foreach (var tile in tileset.TileDictionary.Values)
{
if (tile.properties.Count != 0)
{
// this needs a name:
string name = tile.properties.FirstOrDefault(item => item.StrippedName.ToLowerInvariant() == "name")?.value;
if (!string.IsNullOrEmpty(name))
{
List<NamedValue> namedValues = new List<NamedValue>();
foreach (var prop in tile.properties)
{
namedValues.Add(new NamedValue()
{ Name = prop.StrippedName, Value = prop.value, Type = prop.Type });
}
toReturn.Properties.Add(name, namedValues);
}
}
}
}
var tmxDirectory = FileManager.GetDirectory(fileName);
var animationDictionary = new Dictionary<string, AnimationChain>();
// add animations
foreach (var tileset in tms.Tilesets)
{
string tilesetImageFile = tmxDirectory + tileset.Images[0].Source;
if (tileset.SourceDirectory != ".")
{
tilesetImageFile = tmxDirectory + tileset.SourceDirectory + tileset.Images[0].Source;
}
var texture = FlatRedBallServices.Load<Microsoft.Xna.Framework.Graphics.Texture2D>(tilesetImageFile);
foreach (var tile in tileset.Tiles.Where(item => item.Animation != null && item.Animation.Frames.Count != 0))
{
var animation = tile.Animation;
var animationChain = new AnimationChain();
foreach (var frame in animation.Frames)
{
var animationFrame = new AnimationFrame();
animationFrame.FrameLength = frame.Duration / 1000.0f;
animationFrame.Texture = texture;
int tileIdRelative = frame.TileId;
int globalTileId = (int)(tileIdRelative + tileset.Firstgid);
int leftPixel;
int rightPixel;
int topPixel;
int bottomPixel;
TiledMapSave.GetPixelCoordinatesFromGid((uint)globalTileId, tileset, out leftPixel, out topPixel, out rightPixel, out bottomPixel);
animationFrame.LeftCoordinate = MapDrawableBatch.CoordinateAdjustment + leftPixel / (float)texture.Width;
animationFrame.RightCoordinate = -MapDrawableBatch.CoordinateAdjustment + rightPixel / (float)texture.Width;
animationFrame.TopCoordinate = MapDrawableBatch.CoordinateAdjustment + topPixel / (float)texture.Height;
animationFrame.BottomCoordinate = -MapDrawableBatch.CoordinateAdjustment + bottomPixel / (float)texture.Height;
animationChain.Add(animationFrame);
}
var property = tile.properties.FirstOrDefault(item => item.StrippedNameLower == "name");
if (property == null)
{
throw new InvalidOperationException(
$"The tile with ID {tile.id} has an animation, but it doesn't have a Name property, which is required for animation.");
}
else
{
animationDictionary.Add(property.value, animationChain);
}
}
}
toReturn.Animation = new LayeredTileMapAnimation(animationDictionary);
toReturn.MapProperties = tms.properties
.Select(propertySave => new NamedValue
{ Name = propertySave.name, Value = propertySave.value, Type = propertySave.Type })
.ToList();
return toReturn;
}
public void AnimateSelf()
{
if (Animation != null)
{
Animation.Activity(this);
}
}
public void AddToManagers()
{
AddToManagers(null);
}
public void AddToManagers(FlatRedBall.Graphics.Layer layer)
{
bool isAlreadyManaged = SpriteManager.ManagedPositionedObjects
.Contains(this);
// This allows AddToManagers to be called multiple times, so it can be added to multiple layers
if (!isAlreadyManaged)
{
SpriteManager.AddPositionedObject(this);
}
foreach (var item in this.mMapLists)
{
item.AddToManagers(layer);
}
}
//Write some addtomanagers and remove methods
static List<int> GetZBreaks(List<SpriteSave> list)
{
List<int> zBreaks = new List<int>();
GetZBreaks(list, zBreaks);
return zBreaks;
}
static void GetZBreaks(List<SpriteSave> list, List<int> zBreaks)
{
zBreaks.Clear();
if (list.Count == 0 || list.Count == 1)
return;
for (int i = 1; i < list.Count; i++)
{
if (list[i].Z != list[i - 1].Z)
zBreaks.Add(i);
}
}
public LayeredTileMap Clone()
{
var toReturn = base.Clone<LayeredTileMap>();
toReturn.mMapLists = new Math.PositionedObjectList<MapDrawableBatch>();
foreach (var item in this.MapLayers)
{
var clonedLayer = item.Clone();
if (item.Parent == this)
{
clonedLayer.AttachTo(toReturn, false);
}
toReturn.mMapLists.Add(clonedLayer);
}
toReturn.ShapeCollections = new List<Math.Geometry.ShapeCollection>();
foreach (var shapeCollection in this.ShapeCollections)
{
toReturn.ShapeCollections.Add(shapeCollection.Clone());
}
return toReturn;
}
public void RemoveFromManagersOneWay()
{
this.mMapLists.MakeOneWay();
for (int i = 0; i < mMapLists.Count; i++)
{
SpriteManager.RemoveDrawableBatch(this.mMapLists[i]);
}
SpriteManager.RemovePositionedObject(this);
this.mMapLists.MakeTwoWay();
}
public void Destroy()
{
// Make it one-way because we want the
// contained objects to persist after a destroy
mMapLists.MakeOneWay();
for (int i = 0; i < mMapLists.Count; i++)
{
SpriteManager.RemoveDrawableBatch(mMapLists[i]);
}
SpriteManager.RemovePositionedObject(this);
mMapLists.MakeTwoWay();
}
}
public static class LayeredTileMapExtensions
{
public static void RemoveTiles(this LayeredTileMap map,
Func<List<NamedValue>, bool> predicate,
Dictionary<string, List<NamedValue>> Properties)
{
// Force execution now for performance reasons
var filteredInfos = Properties.Values.Where(predicate).ToList();
foreach (var layer in map.MapLayers)
{
RemoveTilesFromLayer(filteredInfos, layer);
}
}
public static void RemoveTiles(this MapDrawableBatch layer,
Func<List<NamedValue>, bool> predicate,
Dictionary<string, List<NamedValue>> Properties)
{
// Force execution now for performance reasons
var filteredInfos = Properties.Values.Where(predicate).ToList();
RemoveTilesFromLayer(filteredInfos, layer);
}
private static void RemoveTilesFromLayer(List<List<NamedValue>> filteredInfos, MapDrawableBatch layer)
{
List<int> indexes = new List<int>();
foreach (var itemThatPasses in filteredInfos)
{
string tileName = itemThatPasses
.FirstOrDefault(item => item.Name.ToLowerInvariant() == "name")
.Value as string;
if (layer.NamedTileOrderedIndexes.ContainsKey(tileName))
{
var intsOnThisLayer =
layer.NamedTileOrderedIndexes[tileName];
indexes.AddRange(intsOnThisLayer);
}
}
layer.RemoveQuads(indexes);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using StackingEntities.Desktop.View.Controls;
using StackingEntities.Desktop.ViewModel;
using StackingEntities.Model.Annotations;
using StackingEntities.Model.Helpers;
using StackingEntities.Model.Items;
using StackingEntities.Model.Metadata;
using StackingEntities.Model.Objects;
using Xceed.Wpf.Toolkit;
using Attribute = StackingEntities.Model.Objects.Attribute;
using DisplayOptionList = System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<StackingEntities.Desktop.ViewModel.DisplayOption>>;
using CacheTypeList = System.Collections.Generic.Dictionary<System.Type, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<StackingEntities.Desktop.ViewModel.DisplayOption>>>;
using ExpanderList = System.Collections.Generic.List<System.Windows.Controls.Expander>;
namespace StackingEntities.Desktop.View
{
public class OptionsGenerator
{
public static ExpanderList AddGroups(DisplayOptionList dict, bool wide = false)
{
return dict.Keys.Select(key => AddGroup(key, dict, wide)).ToList();
}
public static Expander AddGroup(string header, DisplayOptionList dict, bool wide = false)
{
var g = new Expander { Header = header };
if (wide)
g.Margin = new Thickness(10, 0, 0, 0);
var grid = new Grid { Margin = new Thickness(20, 0, 10, 0) };
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(0, GridUnitType.Auto) });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
g.Content = grid;
var i = 0;
#region Add Controls
foreach (var option in dict[header])
{
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(0, GridUnitType.Auto) });
FrameworkElement elem;
#region Bool
if (option.PropertyType == typeof(bool))
{
elem = ExtractBool(option);
}
else if (option.PropertyType == typeof(bool?))
{
elem = ExtractNullableBool(option);
}
#endregion
#region Int
else if (option.PropertyType == typeof(int) || option.PropertyType == typeof(int?))
{
elem = ExtractInt(option);
}
#endregion
#region String
else if (option.PropertyType == typeof(string))
{
elem = ExtractString(option);
}
#endregion
#region Double
else if (option.PropertyType == typeof(double))
{
elem = ExtractDouble(option);
}
#endregion
#region Enum
else if (option.PropertyType.IsEnum)
{
elem = ExtractEnum(option);
}
#endregion
#region Item
else if (option.PropertyType == typeof(Item))
{
elem = ExtractItem(option);
}
#endregion
#region List
else if (option.PropertyType.IsGenericType && option.PropertyType.GetGenericTypeDefinition() == typeof(ObservableCollection<>))
{
elem = ExtractList(option);
}
#endregion
else
{
elem = ExtractGeneric(option);
}
if (elem.GetValue(Grid.ColumnSpanProperty)?.Equals(1) ?? true)
{
var l = new Label { Content = option.ReadableName, ToolTip = option.Description };
l.SetValue(Grid.RowProperty, i);
if (option.EnabledPropertyName != null)
l.SetBinding(UIElement.IsEnabledProperty, new Binding(option.EnabledPropertyName));
grid.Children.Add(l);
elem.SetValue(Grid.ColumnProperty, 1);
}
if (option.EnabledPropertyName != null)
elem.SetBinding(UIElement.IsEnabledProperty, new Binding(option.EnabledPropertyName));
elem.SetValue(Grid.RowProperty, i);
elem.ToolTip = option.Description;
grid.Children.Add(elem);
i++;
}
#endregion
return g;
}
private static FrameworkElement ExtractNullableBool(DisplayOption option)
{
var ctrl = new CheckBox {IsThreeState = true, Style = (Style)Application.Current.Resources["YesNoInheritCheckbox"] };
ctrl.SetBinding(ToggleButton.IsCheckedProperty, new Binding(option.PropertyName));
return ctrl;
}
private static FrameworkElement ExtractGeneric(DisplayOption option)
{
var ctrl = new ContentPresenter { Margin = new Thickness(3)};
ctrl.SetBinding(ContentPresenter.ContentProperty, new Binding(option.PropertyName));
if (option.Wide)
ctrl.SetValue(Grid.ColumnSpanProperty, 2);
return ctrl;
}
private static FrameworkElement ExtractList(DisplayOption option)
{
var drop = new Expander { Margin = new Thickness(5), Header = option.ReadableName };
var listType = option.PropertyType.GetGenericArguments()[0];
FrameworkElement ctrl;
if (listType == typeof(Item)
|| listType == typeof(Attribute)
|| listType == typeof(VillagerRecipe)
|| listType == typeof(PotionEffect)
|| listType == typeof(BookPage)
|| listType == typeof(Enchantment)
|| listType == typeof(MapDecoration)
|| listType == typeof(BlockType)
|| listType == typeof(BannerPattern)
|| listType == typeof(JsonTextElement))
{
if (!option.FixedSize || (option.Minimum == null || option.Maximum == null))
{
var sPanel = new ItemListControl
{
SlotDescription = { Text = option.Description },
AddRemoveButtons = { Visibility = option.FixedSize ? Visibility.Collapsed : Visibility.Visible }
};
sPanel.SetBinding(FrameworkElement.DataContextProperty, new Binding(option.PropertyName));
ctrl = sPanel;
}
else
{
var invGrid = new InventoryControl
{
InvWidth = (int) option.Minimum,
InvHeight = (int) option.Maximum,
HorizontalAlignment = HorizontalAlignment.Center
};
invGrid.SetBinding(FrameworkElement.DataContextProperty, new Binding(option.PropertyName));
ctrl = invGrid;
}
}
else
{
// ReSharper disable once UseObjectOrCollectionInitializer
var ctrl2 = new DataGrid
{
Margin = new Thickness(3),
AutoGenerateColumns = true,
CanUserAddRows = !option.FixedSize,
MinHeight = 50
};
ctrl2.AutoGeneratingColumn += (sender1, e1) =>
{
var displayName = PropertyHelpers.GetPropertyDisplayName(e1.PropertyDescriptor);
if (e1.PropertyType == typeof(string))
((DataGridTextColumn)e1.Column).EditingElementStyle = (Style)Application.Current.Resources["DataGridTextColumnStyle"];
if (!string.IsNullOrEmpty(displayName))
e1.Column.Header = displayName;
else
e1.Cancel = true;
};
if (option.DataGridRowHeaderPath != null)
{
var rowHeaderStyle = new Style(typeof(DataGridRowHeader));
rowHeaderStyle.Setters.Add(new Setter(ContentControl.ContentProperty, new Binding(option.DataGridRowHeaderPath)));
ctrl2.RowHeaderStyle = rowHeaderStyle;
}
ctrl2.Margin = new Thickness(15, 0, 0, 0);
ctrl = ctrl2;
ctrl.SetBinding(ItemsControl.ItemsSourceProperty, new Binding(option.PropertyName));
}
drop.Content = ctrl;
drop.SetValue(Grid.ColumnSpanProperty, 2);
return drop;
}
private static FrameworkElement ExtractItem(DisplayOption option)
{
var ctrl = new ItemControl { Margin = new Thickness(3) };
ctrl.SetBinding(FrameworkElement.DataContextProperty, new Binding(option.PropertyName));
if (option.Wide)
ctrl.SetValue(Grid.ColumnSpanProperty, 2);
return ctrl;
}
private static FrameworkElement ExtractEnum(DisplayOption option)
{
var ctrl = new ComboBox { Margin = new Thickness(3) };
var m = typeof(EnumHelper).GetMethod("GetAllValuesAndDescriptions").MakeGenericMethod(option.PropertyType);
var ie = m.Invoke(null, null) as IEnumerable;
ctrl.ItemsSource = ie;
ctrl.DisplayMemberPath = "Description";
ctrl.SetBinding(Selector.SelectedValueProperty, new Binding(option.PropertyName));
ctrl.SelectedValuePath = "Value";
return ctrl;
}
private static FrameworkElement ExtractDouble(DisplayOption option)
{
var ctrl = new DoubleUpDown
{
FormatString = "F2",
Margin = new Thickness(3),
HorizontalAlignment = HorizontalAlignment.Left,
MinWidth = 50
};
ctrl.SetBinding(DoubleUpDown.ValueProperty, new Binding(option.PropertyName));
double newVal;
if (option.Minimum != null)
{
newVal = Convert.ToDouble(option.Minimum);
ctrl.Minimum = newVal;
}
if (option.Maximum != null)
{
newVal = Convert.ToDouble(option.Maximum);
ctrl.Maximum = newVal;
}
return ctrl;
}
private static FrameworkElement ExtractString(DisplayOption option)
{
var ctrl = new TextBox { Margin = new Thickness(3) };
if (option.Multiline)
{
ctrl.TextWrapping = TextWrapping.Wrap;
ctrl.AcceptsReturn = true;
ctrl.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
ctrl.MinHeight = 100;
}
ctrl.SetBinding(TextBox.TextProperty, new Binding(option.PropertyName));
return ctrl;
}
private static FrameworkElement ExtractInt(DisplayOption option)
{
var ctrl = new IntegerUpDown
{
Margin = new Thickness(3),
HorizontalAlignment = HorizontalAlignment.Left,
MinWidth = 50
};
ctrl.SetBinding(IntegerUpDown.ValueProperty, new Binding(option.PropertyName));
int newVal;
if (option.Minimum != null)
{
newVal = Convert.ToInt32(option.Minimum);
ctrl.Minimum = newVal;
}
if (option.Maximum != null)
{
newVal = Convert.ToInt32(option.Maximum);
ctrl.Maximum = newVal;
}
return ctrl;
}
private static FrameworkElement ExtractBool(DisplayOption option)
{
var ctrl = new CheckBox();
ctrl.SetBinding(ToggleButton.IsCheckedProperty, new Binding(option.PropertyName));
return ctrl;
}
private static readonly CacheTypeList _cachedTypes = new CacheTypeList();
public static void ExtractOptions([NotNull] object ent, DisplayOptionList dict)
{
if (ent == null) throw new ArgumentNullException("ent");
var eType = ent.GetType();
if (_cachedTypes.ContainsKey(eType))
{
foreach (var type in _cachedTypes[eType])
{
dict[type.Key] = type.Value;
}
return;
}
var props = eType.GetProperties();
_cachedTypes[eType] = new DisplayOptionList();
foreach (var info in props.Reverse())
{
if (!System.Attribute.IsDefined(info, typeof (EntityDescriptorAttribute))) continue;
var prop = (EntityDescriptorAttribute) info.GetCustomAttribute(typeof (EntityDescriptorAttribute));
if (!dict.ContainsKey(prop.Category))
dict.Add(prop.Category, new List<DisplayOption>());
if (!_cachedTypes[eType].ContainsKey(prop.Category))
_cachedTypes[eType].Add(prop.Category, new List<DisplayOption>());
object min = null, max = null;
var multiline = System.Attribute.IsDefined(info, typeof (MultilineStringAttribute));
if (System.Attribute.IsDefined(info, typeof (MinMaxAttribute)))
{
var att = (MinMaxAttribute) info.GetCustomAttribute(typeof (MinMaxAttribute));
min = att.Minimum;
max = att.Maximum;
}
var displayOption = new DisplayOption(prop.Name, info.Name, info.PropertyType, prop.Description, min, max, multiline, prop.IsEnabledPath, prop.FixedSize, prop.DataGridRowHeaderPath, prop.Wide);
_cachedTypes[eType][prop.Category].Insert(0, displayOption);
dict[prop.Category].Insert(0, displayOption);
}
}
}
}
| |
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 SampleSPAApp.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Sensus.UI.UiProperties;
using Newtonsoft.Json;
using Sensus.Context;
using Sensus.Callbacks;
using Microsoft.AppCenter.Analytics;
using Sensus.Extensions;
using Sensus.Exceptions;
#if __IOS__
using CoreLocation;
#endif
namespace Sensus.Probes
{
/// <summary>
/// Polling Probes are triggered at regular intervals. When triggered, the <see cref="PollingProbe"/> asks the device (and perhaps the user)
/// for some type of information and stores the resulting information in the <see cref="LocalDataStore"/>.
///
/// # Background Considerations
/// On Android, each <see cref="PollingProbe"/> is able to periodically wake up in the background, take a reading, and allow the system to go back to
/// sleep. The Android operating system will occasionally delay the wake-up signal in order to batch wake-ups and thereby conserve energy; however,
/// this delay is usually only 5-10 seconds. So, if you configure a <see cref="PollingProbe"/> to poll every 60 seconds, you may see actual polling
/// delays of 65-70 seconds and maybe even more. This is by design within Android and cannot be changed.
///
/// Polling on iOS is generally less reliable than on Android. By design, iOS apps are restricted from performing processing in the background,
/// with the following exceptions for <see cref="PollingProbe"/>s:
///
/// * Significant location change processing: If <see cref="SignificantChangePoll"/> is enabled, the <see cref="PollingProbe"/> will wake up each time
/// the user's physical location changes significantly. This change is triggered by a change in cellular tower, which is roughly on the
/// order of several kilometers.
///
/// * Push notification processing: If you [configure push notifications](xref:push_notifications), the <see cref="PollingProbe"/> will be woken up
/// at the desired time to take a reading. Note that the reliability of these timings is subject to push notification throttling imposed
/// by the Apple Push Notification Service. The value of <see cref="PollingSleepDurationMS"/> should be set conservatively for all probes,
/// for example no lower than 15-20 minutes. The push notification backend server will attempt to deliver push notifications slightly ahead of their
/// scheduled times. If such a push notification arrives at the device before the scheduled time, then the local notification (if
/// <see cref="AlertUserWhenBackgrounded"/> is enabled) will be cancelled.
///
/// Beyond these exceptions, all processing within Sensus for iOS must be halted when the user backgrounds the app. Sensus does its best to support
/// <see cref="PollingProbe"/>s on iOS by scheduling notifications to appear when polling operations (e.g., taking a GPS reading) should execute. This
/// relies on the user to open the notification from the tray and bring Sensus to the foreground so that the polling operation can execute. Of course,
/// the user might not see the notification or might choose not to open it. The polling operation will not be executed in such cases.
/// </summary>
public abstract class PollingProbe : Probe, IPollingProbe
{
#if __IOS__
// we used to instantiate the CLLocationManager as an instance-level field of this class,
// but these references are duplicative and all point to the same object. as a result,
// we were seeing many warnings about unnecessary reinitialization. this is better done
// as a static member.
private static CLLocationManager SIGNIFICANT_CHANGE_LOCATION_MANAGER = new CLLocationManager
{
DistanceFilter = 5.0,
PausesLocationUpdatesAutomatically = false,
AllowsBackgroundLocationUpdates = true
};
#endif
private int _pollingSleepDurationMS;
private int _pollingTimeoutMinutes;
private bool _isPolling;
private List<DateTime> _pollTimes;
private ScheduledCallback _pollCallback;
private bool _acPowerConnectPoll;
private bool _acPowerConnectPollOverridesScheduledPolls;
private EventHandler<bool> _powerConnectionChanged;
private bool _significantChangePoll;
private bool _significantChangePollOverridesScheduledPolls;
/// <summary>
/// How long to sleep (become inactive) between successive polling operations.
/// </summary>
/// <value>The polling sleep duration in milliseconds.</value>
[EntryIntegerUiProperty("Sleep Duration (MS):", true, 5, true)]
public virtual int PollingSleepDurationMS
{
get { return _pollingSleepDurationMS; }
set
{
// this must be at least as larged as CALLBACK_NOTIFICATION_HORIZON_THRESHOLD,
// in order to prevent immediate poll-repoll cycles.
if (value <= 5000)
{
value = 5000;
}
_pollingSleepDurationMS = value;
}
}
/// <summary>
/// How long the <see cref="PollingProbe"/> has to complete a single poll operation before being cancelled.
/// </summary>
/// <value>The polling timeout minutes.</value>
[EntryIntegerUiProperty("Timeout (Mins.):", true, 6, true)]
public int PollingTimeoutMinutes
{
get
{
return _pollingTimeoutMinutes;
}
set
{
if (value < 1)
{
value = 1;
}
_pollingTimeoutMinutes = value;
}
}
[JsonIgnore]
public abstract int DefaultPollingSleepDurationMS { get; }
protected override double RawParticipation
{
get
{
int oneDayMS = (int)new TimeSpan(1, 0, 0, 0).TotalMilliseconds;
float pollsPerDay = oneDayMS / (float)_pollingSleepDurationMS;
float fullParticipationPolls = pollsPerDay * Protocol.ParticipationHorizonDays;
lock (_pollTimes)
{
return _pollTimes.Count(pollTime => pollTime >= Protocol.ParticipationHorizon) / fullParticipationPolls;
}
}
}
protected override long DataRateSampleSize => 10;
public override double? MaxDataStoresPerSecond { get => null; set { } }
public List<DateTime> PollTimes
{
get { return _pollTimes; }
}
/// <summary>
/// Whether to poll on when the device is connected to AC Power.
/// </summary>
/// <value><c>true</c> if we should poll on power connect; otherwise, <c>false</c>.</value>
[OnOffUiProperty("Poll On AC Power Connection:", true, 7)]
public bool AcPowerConnectPoll
{
get { return _acPowerConnectPoll; }
set { _acPowerConnectPoll = value; }
}
/// <summary>
/// Has no effect if <see cref="AcPowerConnectPoll"/> is disabled. If <see cref="AcPowerConnectPoll"/> is enabled: (1) If this
/// is on, polling will only occur on AC power connect. (2) If this is off, polling will occur based on <see cref="PollingSleepDurationMS"/> and
/// on AC power connect.
/// </summary>
/// <value><c>true</c> if AC power connect poll overrides scheduled polls; otherwise, <c>false</c>.</value>
[OnOffUiProperty("AC Power Connection Poll Overrides Scheduled Polls:", true, 8)]
public bool AcPowerConnectPollOverridesScheduledPolls
{
get { return _acPowerConnectPollOverridesScheduledPolls; }
set { _acPowerConnectPollOverridesScheduledPolls = value; }
}
/// <summary>
/// Available on iOS only. Whether or not to poll when a significant change in location has occurred. See
/// [here](https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html) for
/// more information on significant changes.
/// </summary>
/// <value><c>true</c> if significant change poll; otherwise, <c>false</c>.</value>
[OnOffUiProperty("(iOS) Poll On Significant Location Change:", true, 9)]
public bool SignificantChangePoll
{
get { return _significantChangePoll; }
set { _significantChangePoll = value; }
}
/// <summary>
/// Available on iOS only. Has no effect if significant-change polling is disabled. If significant-change polling is enabled: (1) If this
/// is on, polling will only occur on significant changes. (2) If this is off, polling will occur based on <see cref="PollingSleepDurationMS"/> and
/// on significant changes.
/// </summary>
/// <value><c>true</c> if significant change poll overrides scheduled polls; otherwise, <c>false</c>.</value>
[OnOffUiProperty("(iOS) Significant Change Poll Overrides Scheduled Polls:", true, 10)]
public bool SignificantChangePollOverridesScheduledPolls
{
get { return _significantChangePollOverridesScheduledPolls; }
set { _significantChangePollOverridesScheduledPolls = value; }
}
/// <summary>
/// Available on iOS only. Whether or not to alert the user with a notification when polling should occur and the
/// app is in the background. See the <see cref="PollingProbe"/> overview for information about background considerations.
/// The notifications issued when this setting is enabled encourage the user to bring the app to the foreground so that
/// data polling may occur. Depending on how many <see cref="PollingProbe"/>s are enabled, these notifications can
/// become excessive for the user.
/// </summary>
/// <value><c>true</c> to alert user when backgrounded; otherwise, <c>false</c>.</value>
[OnOffUiProperty("(iOS) Alert User When Backgrounded:", true, 11)]
public bool AlertUserWhenBackgrounded { get; set; } = true;
/// <summary>
/// Tolerance in milliseconds for running the <see cref="PollingProbe"/> before the scheduled
/// time, if doing so will increase the number of batched actions and thereby decrease battery consumption.
/// </summary>
/// <value>The delay tolerance before.</value>
[EntryIntegerUiProperty("Delay Tolerance Before (MS):", true, 12, true)]
public int DelayToleranceBeforeMS { get; set; }
/// <summary>
/// Tolerance in milliseconds for running the <see cref="PollingProbe"/> after the scheduled
/// time, if doing so will increase the number of batched actions and thereby decrease battery consumption.
/// </summary>
/// <value>The delay tolerance before.</value>
[EntryIntegerUiProperty("Delay Tolerance After (MS):", true, 13, true)]
public int DelayToleranceAfterMS { get; set; }
public override string CollectionDescription
{
get
{
string description = DisplayName + ": ";
bool scheduledPollOverridden = false;
#if __IOS__
if (_significantChangePoll)
{
description += "On significant changes in the device's location. ";
if (_significantChangePollOverridesScheduledPolls)
{
scheduledPollOverridden = true;
}
}
#endif
if (_acPowerConnectPoll)
{
description += "On AC power connection. ";
if (_acPowerConnectPollOverridesScheduledPolls)
{
scheduledPollOverridden = true;
}
}
if (!scheduledPollOverridden)
{
description += TimeSpan.FromMilliseconds(_pollingSleepDurationMS).GetFullDescription(TimeSpan.FromMilliseconds(DelayToleranceBeforeMS), TimeSpan.FromMilliseconds(DelayToleranceAfterMS)) + ".";
}
return description;
}
}
protected PollingProbe()
{
_pollingSleepDurationMS = DefaultPollingSleepDurationMS;
_pollingTimeoutMinutes = 5;
_isPolling = false;
_pollTimes = new List<DateTime>();
_acPowerConnectPoll = false;
_acPowerConnectPollOverridesScheduledPolls = false;
_significantChangePoll = false;
_significantChangePollOverridesScheduledPolls = false;
#if __IOS__
SIGNIFICANT_CHANGE_LOCATION_MANAGER.LocationsUpdated += async (sender, e) =>
{
try
{
CancellationTokenSource pollCallbackCanceller = new CancellationTokenSource();
// if the callback specified a timeout, request cancellation at the specified time.
if (_pollCallback.Timeout.HasValue)
{
pollCallbackCanceller.CancelAfter(_pollCallback.Timeout.Value);
}
await _pollCallback.ActionAsync(pollCallbackCanceller.Token);
}
catch (Exception ex)
{
SensusException.Report("Failed significant change poll.", ex);
}
};
#endif
_powerConnectionChanged = async (sender, connected) =>
{
try
{
if (connected)
{
CancellationTokenSource pollCallbackCanceller = new CancellationTokenSource();
// if the callback specified a timeout, request cancellation at the specified time.
if (_pollCallback.Timeout.HasValue)
{
pollCallbackCanceller.CancelAfter(_pollCallback.Timeout.Value);
}
await _pollCallback.ActionAsync(pollCallbackCanceller.Token);
}
}
catch (Exception ex)
{
SensusException.Report("Failed AC power connected poll: " + ex.Message, ex);
}
};
}
protected override async Task ProtectedStartAsync()
{
await base.ProtectedStartAsync();
// we used to use an initial delay of zero in order to poll immediately; however, this causes the following
// problems:
//
// * slow startup: the immediate poll causes delays when starting the protocol. we show a progress page
// when starting, but it's still irritating to the user.
//
// * protocol restart timeout on push notification (ios): ios occasionally kills the app, and we can wake
// it back up in the background via push notification. however, we only have ~30 seconds to finish processing
// the push notification before the system suspends the app. furthermore, long-running push notifications
// likely result in subsequent throttling of push notification delivery.
//
// given the above, we now use an initial delay equal to the standard delay. the only cost is a single lost
// reading at the very beginning.
_pollCallback = new ScheduledCallback(async cancellationToken =>
{
if (State == ProbeState.Running)
{
_isPolling = true;
List<Datum> data = null;
try
{
SensusServiceHelper.Get().Logger.Log("Polling.", LoggingLevel.Normal, GetType());
data = await PollAsync(cancellationToken);
lock (_pollTimes)
{
_pollTimes.Add(DateTime.Now);
_pollTimes.RemoveAll(pollTime => pollTime < Protocol.ParticipationHorizon);
}
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to poll: " + ex.Message, LoggingLevel.Normal, GetType());
}
if (data != null)
{
foreach (Datum datum in data)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
try
{
await StoreDatumAsync(datum, cancellationToken);
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to store datum: " + ex.Message, LoggingLevel.Normal, GetType());
}
}
}
_isPolling = false;
}
}, TimeSpan.FromMilliseconds(_pollingSleepDurationMS), TimeSpan.FromMilliseconds(_pollingSleepDurationMS), GetType().FullName, Protocol.Id, Protocol, TimeSpan.FromMinutes(_pollingTimeoutMinutes), TimeSpan.FromMilliseconds(DelayToleranceBeforeMS), TimeSpan.FromMilliseconds(DelayToleranceAfterMS), ScheduledCallbackPriority.Normal, GetType());
#if __IOS__
// on ios, notify the user about desired polling to encourage them to foreground the app.
if (AlertUserWhenBackgrounded)
{
// capitalize first character of data request message
string dataRequestMessage = DisplayName + " data requested.";
dataRequestMessage = dataRequestMessage[0].ToString().ToUpper() + dataRequestMessage.Substring(1).ToLower();
_pollCallback.UserNotificationMessage = dataRequestMessage;
// give the user some feedback when they tap the callback notification
_pollCallback.NotificationUserResponseMessage = "Data collected. Thanks!";
}
#endif
bool schedulePollCallback = true;
#if __IOS__
if (_significantChangePoll)
{
SIGNIFICANT_CHANGE_LOCATION_MANAGER.RequestAlwaysAuthorization();
if (CLLocationManager.LocationServicesEnabled)
{
SIGNIFICANT_CHANGE_LOCATION_MANAGER.StartMonitoringSignificantLocationChanges();
if (_significantChangePollOverridesScheduledPolls)
{
schedulePollCallback = false;
}
}
else
{
SensusServiceHelper.Get().Logger.Log("Location services not enabled.", LoggingLevel.Normal, GetType());
}
}
#endif
if (_acPowerConnectPoll)
{
SensusContext.Current.PowerConnectionChangeListener.PowerConnectionChanged += _powerConnectionChanged;
if (_acPowerConnectPollOverridesScheduledPolls)
{
schedulePollCallback = false;
}
}
if (schedulePollCallback)
{
await SensusContext.Current.CallbackScheduler.ScheduleCallbackAsync(_pollCallback);
}
}
protected abstract Task<List<Datum>> PollAsync(CancellationToken cancellationToken);
protected override async Task ProtectedStopAsync()
{
await base.ProtectedStopAsync();
#if __IOS__
if (_significantChangePoll)
{
SIGNIFICANT_CHANGE_LOCATION_MANAGER.StopMonitoringSignificantLocationChanges();
}
#endif
if (_acPowerConnectPoll)
{
#pragma warning disable RECS0020 // Delegate subtraction has unpredictable result
SensusContext.Current.PowerConnectionChangeListener.PowerConnectionChanged -= _powerConnectionChanged;
#pragma warning restore RECS0020 // Delegate subtraction has unpredictable result
}
await SensusContext.Current.CallbackScheduler.UnscheduleCallbackAsync(_pollCallback);
_pollCallback = null;
}
public override async Task<HealthTestResult> TestHealthAsync(List<AnalyticsTrackedEvent> events)
{
HealthTestResult result = await base.TestHealthAsync(events);
if (State == ProbeState.Running)
{
#if __IOS__
// on ios we do significant-change polling, which can override scheduled polls. don't check for polling delays if the scheduled polls are overridden.
if (_significantChangePoll && _significantChangePollOverridesScheduledPolls)
{
return result;
}
#endif
// don't check for polling delays if the scheduled polls are overridden.
if (_acPowerConnectPoll && _acPowerConnectPollOverridesScheduledPolls)
{
return result;
}
TimeSpan timeElapsedSincePreviousStore = DateTimeOffset.UtcNow - MostRecentStoreTimestamp.GetValueOrDefault(DateTimeOffset.MinValue);
int allowedLagMS = 5000;
if (!_isPolling && // don't raise a warning if the probe is currently trying to poll
_pollingSleepDurationMS <= int.MaxValue - allowedLagMS && // some probes (iOS HealthKit for age) have polling delays set to int.MaxValue. if we add to this (as we're about to do in the next check), we'll wrap around to 0 resulting in incorrect statuses. only do the check if we won't wrap around.
timeElapsedSincePreviousStore.TotalMilliseconds > (_pollingSleepDurationMS + allowedLagMS)) // system timer callbacks aren't always fired exactly as scheduled, resulting in health tests that identify warning conditions for delayed polling. allow a small fudge factor to ignore these warnings.
{
string eventName = TrackedEvent.Warning + ":" + GetType().Name;
Dictionary<string, string> properties = new Dictionary<string, string>
{
{ "Polling Latency", (timeElapsedSincePreviousStore.TotalMilliseconds - _pollingSleepDurationMS).RoundToWhole(1000).ToString() }
};
Analytics.TrackEvent(eventName, properties);
events.Add(new AnalyticsTrackedEvent(eventName, properties));
}
if (!SensusContext.Current.CallbackScheduler.ContainsCallback(_pollCallback))
{
string eventName = TrackedEvent.Error + ":" + GetType().Name;
Dictionary<string, string> properties = new Dictionary<string, string>
{
{ "Missing Callback", _pollCallback.Id }
};
Analytics.TrackEvent(eventName, properties);
events.Add(new AnalyticsTrackedEvent(eventName, properties));
result = HealthTestResult.Restart;
}
}
return result;
}
public override async Task ResetAsync()
{
await base.ResetAsync();
_isPolling = false;
_pollCallback = null;
lock (_pollTimes)
{
_pollTimes.Clear();
}
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2016 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using LibAzyotter.Internal;
using Newtonsoft.Json;
namespace LibAzyotter
{
/// <summary>
/// Represents the metadata and additional contextual information about content posted on Twitter.
/// </summary>
public class Entities : CoreBase
{
/// <summary>
/// Gets or sets the hashtags which have been parsed out of the Tweet text.
/// </summary>
[JsonProperty("hashtags")]
public HashtagEntity[] HashTags { get; set; }
/// <summary>
/// Gets or sets the media elements uploaded with the Tweet.
/// </summary>
[JsonProperty("media")]
public MediaEntity[] Media { get; set; }
/// <summary>
/// Gets or sets the URLs included in the text of a Tweet or within textual fields of a user object.
/// </summary>
[JsonProperty("urls")]
public UrlEntity[] Urls { get; set; }
/// <summary>
/// Gets or sets the other Twitter users mentioned in the text of the Tweet.
/// </summary>
[JsonProperty("user_mentions")]
public UserMentionEntity[] UserMentions { get; set; }
/// <summary>
/// Gets or sets the symbols which have been parsed out of the Tweet text.
/// </summary>
[JsonProperty("symbols")]
public CashtagEntity[] Symbols { get; set; }
}
/// <summary>
/// Represents an entity object in the content posted on Twitter. This is an <c>abstract</c> class.
/// </summary>
public abstract class Entity : CoreBase
{
/// <summary>
/// <para>Gets or sets an array of integers indicating the offsets within the Tweet text where the URL begins and ends.</para>
/// <para>The first integer represents the location of the first character of the URL in the Tweet text.</para>
/// <para>The second integer represents the location of the first non-URL character occurring after the URL (or the end of the string if the URL is the last part of the Tweet text).</para>
/// </summary>
[JsonProperty("indices")]
public int[] Indices { get; set; }
}
/// <summary>
/// Represents a symbol object that contains a symbol in the content posted on Twitter.
/// </summary>
public abstract class SymbolEntity : Entity
{
/// <summary>
/// Gets or sets the name of the hashtag, minus the leading '#' or '$' character.
/// </summary>
[JsonProperty("text")]
public string Text { get; set; }
}
/// <summary>
/// Represents a #hashtag object.
/// </summary>
public class HashtagEntity : SymbolEntity { }
/// <summary>
/// Represents a $cashtag object.
/// </summary>
public class CashtagEntity : SymbolEntity { }
/// <summary>
/// Represents a media object that contains the URLs, sizes and type of the media.
/// </summary>
public class MediaEntity : UrlEntity
{
/// <summary>
/// Gets or sets the ID of the media expressed as a 64-bit integer.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the URL pointing directly to the uploaded media file.
/// </summary>
[JsonProperty("media_url")]
public string MediaUrl { get; set; }
/// <summary>
/// Gets or sets the URL pointing directly to the uploaded media file, for embedding on https pages.
/// </summary>
[JsonProperty("media_url_https")]
public string MediaUrlHttps { get; set; }
/// <summary>
/// Gets or sets the object showing available sizes for the media file.
/// </summary>
[JsonProperty("sizes")]
public MediaSizes Sizes { get; set; }
/// <summary>
/// <para>Gets or sets the ID points to the original Tweet.</para>
/// <para>(Only for Tweets containing media that was originally associated with a different tweet.)</para>
/// </summary>
[JsonProperty("source_status_id")]
public long? SourceStatusId { get; set; }
/// <summary>
/// Gets or sets the type of uploaded media.
/// </summary>
[JsonProperty("type")]
public string Type { get; set; }
/// <summary>
/// Gets or sets the information of the uploaded video or animated GIF.
/// </summary>
[JsonProperty("video_info")]
public VideoInfo VideoInfo { get; set; }
/// <summary>
/// Returns the ID of this instance.
/// </summary>
/// <returns>The ID of this instance.</returns>
public override string ToString()
{
return this.Id.ToString("D");
}
}
/// <summary>
/// Represents the size of the <see cref="MediaSizes"/>.
/// </summary>
public class MediaSize : CoreBase
{
/// <summary>
/// Gets or sets the height in pixels of the size.
/// </summary>
[JsonProperty("h")]
public int Height { get; set; }
/// <summary>
/// <para>Gets or sets the resizing method used to obtain the size.</para>
/// <para>A value of fit means that the media was resized to fit one dimension, keeping its native aspect ratio.</para>
/// <para>A value of crop means that the media was cropped in order to fit a specific resolution.</para>
/// </summary>
[JsonProperty("resize")]
public string Resize { get; set; }
/// <summary>
/// Gets or sets the width in pixels of the size.
/// </summary>
[JsonProperty("w")]
public int Width { get; set; }
}
/// <summary>
/// Represents the variations of the media.
/// </summary>
public class MediaSizes : CoreBase
{
/// <summary>
/// Gets or sets the information for a large-sized version of the media.
/// </summary>
[JsonProperty("large")]
public MediaSize Large { get; set; }
/// <summary>
/// Gets or sets the information for a medium-sized version of the media.
/// </summary>
[JsonProperty("medium")]
public MediaSize Medium { get; set; }
/// <summary>
/// Gets or sets the information for a small-sized version of the media.
/// </summary>
[JsonProperty("small")]
public MediaSize Small { get; set; }
/// <summary>
/// Gets or sets the information for a thumbnail-sized version of the media.
/// </summary>
[JsonProperty("thumb")]
public MediaSize Thumb { get; set; }
}
/// <summary>
/// Represents a video_info object which is included by a video or animated GIF entity.
/// </summary>
public class VideoInfo : CoreBase
{
/// <summary>
/// Gets or sets the aspect ratio of the video,
/// as a simplified fraction of width and height in a 2-element array.
/// Typical values are [4, 3] or [16, 9]
/// </summary>
[JsonProperty("aspect_ratio")]
public int[] AspectRatio { get; set; }
/// <summary>
/// Gets or sets the length of the video, in milliseconds.
/// </summary>
[JsonProperty("duration_millis")]
public int? DurationMillis { get; set; }
/// <summary>
/// Gets or sets the different encodings/streams of the video.
/// </summary>
[JsonProperty("variants")]
public VideoVariant[] Variants { get; set; }
}
/// <summary>
/// Represents a variant of the video.
/// </summary>
public class VideoVariant : CoreBase
{
/// <summary>
/// Gets or sets the bitrate of this variant.
/// </summary>
[JsonProperty("bitrate")]
public int? Bitrate { get; set; }
/// <summary>
/// Gets or sets the MIME type of this variant.
/// </summary>
[JsonProperty("content_type")]
public string ContentType { get; set; }
/// <summary>
/// Gets or sets the URL of the video or playlist.
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
}
/// <summary>
/// Represents a URL object that contains the string for display and the raw URL.
/// </summary>
public class UrlEntity : Entity
{
/// <summary>
/// Gets or sets the URL to display on clients.
/// </summary>
[JsonProperty("display_url")]
public string DisplayUrl { get; set; }
/// <summary>
/// Gets or sets the expanded version of <see cref="DisplayUrl"/>.
/// </summary>
// Note that Twitter accepts invalid URLs, for example, "http://..com"
[JsonProperty("expanded_url")]
public string ExpandedUrl { get; set; }
/// <summary>
/// Gets or sets the wrapped URL, corresponding to the value embedded directly into the raw Tweet text, and the values for the indices parameter.
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
}
/// <summary>
/// Represents a mention object that contains the user information.
/// </summary>
public class UserMentionEntity : Entity
{
/// <summary>
/// Nullable.
/// Gets or sets the ID of the mentioned user.
/// </summary>
[JsonProperty("id")]
public long? Id { get; set; }
/// <summary>
/// Gets or sets display name of the referenced user.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets screen name of the referenced user.
/// </summary>
[JsonProperty("screen_name")]
public string ScreenName { get; set; }
/// <summary>
/// Returns the ID of this instance.
/// </summary>
/// <returns>The ID of this instance.</returns>
public override string ToString()
{
return this.Id?.ToString("D");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
/// <summary>
/// Named pipe server
/// </summary>
public sealed partial class NamedPipeServerStream : PipeStream
{
// Use the maximum number of server instances that the system resources allow
private const int MaxAllowedServerInstances = -1;
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName)
: this(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, HandleInheritability.None)
{
}
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName, PipeDirection direction)
: this(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, HandleInheritability.None)
{
}
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances)
: this(pipeName, direction, maxNumberOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, HandleInheritability.None)
{
}
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, PipeOptions.None, 0, 0, HandleInheritability.None)
{
}
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, 0, 0, HandleInheritability.None)
{
}
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, HandleInheritability.None)
{
}
/// <summary>
/// Full named pipe server constructor
/// </summary>
/// <param name="pipeName">Pipe name</param>
/// <param name="direction">Pipe direction: In, Out or InOut (duplex).
/// Win32 note: this gets OR'd into dwOpenMode to CreateNamedPipe
/// </param>
/// <param name="maxNumberOfServerInstances">Maximum number of server instances. Specify a fixed value between
/// 1 and 254 (Windows)/greater than 1 (Unix), or use NamedPipeServerStream.MaxAllowedServerInstances to use the
/// maximum amount allowed by system resources.</param>
/// <param name="transmissionMode">Byte mode or message mode.
/// Win32 note: this gets used for dwPipeMode. CreateNamedPipe allows you to specify PIPE_TYPE_BYTE/MESSAGE
/// and PIPE_READMODE_BYTE/MESSAGE independently, but this sets type and readmode to match.
/// </param>
/// <param name="options">PipeOption enum: None, Asynchronous, or Writethrough
/// Win32 note: this gets passed in with dwOpenMode to CreateNamedPipe. Asynchronous corresponds to
/// FILE_FLAG_OVERLAPPED option. PipeOptions enum doesn't expose FIRST_PIPE_INSTANCE option because
/// this sets that automatically based on the number of instances specified.
/// </param>
/// <param name="inBufferSize">Incoming buffer size, 0 or higher.
/// Note: this size is always advisory; OS uses a suggestion.
/// </param>
/// <param name="outBufferSize">Outgoing buffer size, 0 or higher (see above)</param>
/// <param name="pipeSecurity">PipeSecurity, or null for default security descriptor</param>
/// <param name="inheritability">Whether handle is inheritable</param>
/// <param name="additionalAccessRights">Combination (logical OR) of PipeAccessRights.TakeOwnership,
/// PipeAccessRights.AccessSystemSecurity, and PipeAccessRights.ChangePermissions</param>
[SecuritySafeCritical]
private NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
HandleInheritability inheritability)
: base(direction, transmissionMode, outBufferSize)
{
if (pipeName == null)
{
throw new ArgumentNullException(nameof(pipeName));
}
if (pipeName.Length == 0)
{
throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
}
if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
{
throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_OptionsInvalid);
}
if (inBufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(inBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
ValidateMaxNumberOfServerInstances(maxNumberOfServerInstances);
// inheritability will always be None since this private constructor is only called from other constructors from which
// inheritability is always set to None. Desktop has a public constructor to allow setting it to something else, but Core
// doesnt.
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
{
throw new ArgumentOutOfRangeException(nameof(inheritability), SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
}
Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode,
options, inBufferSize, outBufferSize, inheritability);
}
// Create a NamedPipeServerStream from an existing server pipe handle.
[SecuritySafeCritical]
public NamedPipeServerStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle)
: base(direction, PipeTransmissionMode.Byte, 0)
{
if (safePipeHandle == null)
{
throw new ArgumentNullException(nameof(safePipeHandle));
}
if (safePipeHandle.IsInvalid)
{
throw new ArgumentException(SR.Argument_InvalidHandle, nameof(safePipeHandle));
}
ValidateHandleIsPipe(safePipeHandle);
InitializeHandle(safePipeHandle, true, isAsync);
if (isConnected)
{
State = PipeState.Connected;
}
}
~NamedPipeServerStream()
{
Dispose(false);
}
public Task WaitForConnectionAsync()
{
return WaitForConnectionAsync(CancellationToken.None);
}
// Server can only connect from Disconnected state
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")]
private void CheckConnectOperationsServer()
{
// we're not checking whether already connected; this allows us to throw IOException
// "pipe is being closed" if other side is closing (as does win32) or no-op if
// already connected
if (State == PipeState.Closed)
{
throw Error.GetPipeNotOpen();
}
if (InternalHandle != null && InternalHandle.IsClosed) // only check IsClosed if we have a handle
{
throw Error.GetPipeNotOpen();
}
if (State == PipeState.Broken)
{
throw new IOException(SR.IO_PipeBroken);
}
}
// Server is allowed to disconnect from connected and broken states
[SecurityCritical]
private void CheckDisconnectOperations()
{
if (State == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (State == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyDisconnected);
}
if (InternalHandle == null && CheckOperationsRequiresSetHandle)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if ((State == PipeState.Closed) || (InternalHandle != null && InternalHandle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
}
#if RunAs
// Users will use this delegate to specify a method to call while impersonating the client
// (see NamedPipeServerStream.RunAsClient).
public delegate void PipeStreamImpersonationWorker();
#endif
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Actual Sessions
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class TXAS : EduHubEntity
{
#region Navigation Property Cache
private SU Cache_SUBJECT_SU;
private SF Cache_TEACHER_SF;
private SM Cache_LOCATION_SM;
private SCL Cache_SCL_LINK_SCL;
#endregion
#region Foreign Navigation Properties
private IReadOnlyList<SXAS> Cache_TID_SXAS_TXAS_ID;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Transaction ID (internal)
/// </summary>
public int TID { get; internal set; }
/// <summary>
/// TID in corresponding THTQ record
/// </summary>
public int? THTQ_TID { get; internal set; }
/// <summary>
/// Actual instance of a class / session
/// [Uppercase Alphanumeric (9)]
/// </summary>
public string CLASS_SESSION { get; internal set; }
/// <summary>
/// Subject for this session
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJECT { get; internal set; }
/// <summary>
/// Class for this session
/// </summary>
public short? CLASS { get; internal set; }
/// <summary>
/// Staff code of teacher for this session
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string TEACHER { get; internal set; }
/// <summary>
/// Room code of room for this session
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string LOCATION { get; internal set; }
/// <summary>
/// Period number within the day
/// </summary>
public short? PERIOD_NO { get; internal set; }
/// <summary>
/// Day number in the current timetable cycle
/// </summary>
public short? DAY_NO { get; internal set; }
/// <summary>
/// Date of this session
/// </summary>
public DateTime? SESSION_DATE { get; internal set; }
/// <summary>
/// Actual Period Description from TH
/// [Alphanumeric (10)]
/// </summary>
public string PERIOD_DESC { get; internal set; }
/// <summary>
/// Session start time (hh:mm)
/// </summary>
public short? START_TIME { get; internal set; }
/// <summary>
/// Session finish time (hh:mm)
/// </summary>
public short? FINISH_TIME { get; internal set; }
/// <summary>
/// Has this roll been marked? (Y/N) Prompted when form closed
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string ROLL_MARKED { get; internal set; }
/// <summary>
/// Class code in SCL
/// [Uppercase Alphanumeric (17)]
/// </summary>
public string SCL_LINK { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last write operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// SU (Subjects) related entity by [TXAS.SUBJECT]->[SU.SUKEY]
/// Subject for this session
/// </summary>
public SU SUBJECT_SU
{
get
{
if (SUBJECT == null)
{
return null;
}
if (Cache_SUBJECT_SU == null)
{
Cache_SUBJECT_SU = Context.SU.FindBySUKEY(SUBJECT);
}
return Cache_SUBJECT_SU;
}
}
/// <summary>
/// SF (Staff) related entity by [TXAS.TEACHER]->[SF.SFKEY]
/// Staff code of teacher for this session
/// </summary>
public SF TEACHER_SF
{
get
{
if (TEACHER == null)
{
return null;
}
if (Cache_TEACHER_SF == null)
{
Cache_TEACHER_SF = Context.SF.FindBySFKEY(TEACHER);
}
return Cache_TEACHER_SF;
}
}
/// <summary>
/// SM (Rooms) related entity by [TXAS.LOCATION]->[SM.ROOM]
/// Room code of room for this session
/// </summary>
public SM LOCATION_SM
{
get
{
if (LOCATION == null)
{
return null;
}
if (Cache_LOCATION_SM == null)
{
Cache_LOCATION_SM = Context.SM.FindByROOM(LOCATION);
}
return Cache_LOCATION_SM;
}
}
/// <summary>
/// SCL (Subject Classes) related entity by [TXAS.SCL_LINK]->[SCL.SCLKEY]
/// Class code in SCL
/// </summary>
public SCL SCL_LINK_SCL
{
get
{
if (SCL_LINK == null)
{
return null;
}
if (Cache_SCL_LINK_SCL == null)
{
Cache_SCL_LINK_SCL = Context.SCL.FindBySCLKEY(SCL_LINK);
}
return Cache_SCL_LINK_SCL;
}
}
#endregion
#region Foreign Navigation Properties
/// <summary>
/// SXAS (Student Scheduled Sessions) related entities by [TXAS.TID]->[SXAS.TXAS_ID]
/// Transaction ID (internal)
/// </summary>
public IReadOnlyList<SXAS> TID_SXAS_TXAS_ID
{
get
{
if (Cache_TID_SXAS_TXAS_ID == null &&
!Context.SXAS.TryFindByTXAS_ID(TID, out Cache_TID_SXAS_TXAS_ID))
{
Cache_TID_SXAS_TXAS_ID = new List<SXAS>().AsReadOnly();
}
return Cache_TID_SXAS_TXAS_ID;
}
}
#endregion
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Encapsulates initialization and shutdown of gRPC library.
/// </summary>
public class GrpcEnvironment
{
const int MinDefaultThreadPoolSize = 4;
const int DefaultBatchContextPoolSharedCapacity = 10000;
const int DefaultBatchContextPoolThreadLocalCapacity = 64;
const int DefaultRequestCallContextPoolSharedCapacity = 10000;
const int DefaultRequestCallContextPoolThreadLocalCapacity = 64;
static object staticLock = new object();
static GrpcEnvironment instance;
static int refCount;
static int? customThreadPoolSize;
static int? customCompletionQueueCount;
static bool inlineHandlers;
static int batchContextPoolSharedCapacity = DefaultBatchContextPoolSharedCapacity;
static int batchContextPoolThreadLocalCapacity = DefaultBatchContextPoolThreadLocalCapacity;
static int requestCallContextPoolSharedCapacity = DefaultRequestCallContextPoolSharedCapacity;
static int requestCallContextPoolThreadLocalCapacity = DefaultRequestCallContextPoolThreadLocalCapacity;
static readonly HashSet<Channel> registeredChannels = new HashSet<Channel>();
static readonly HashSet<Server> registeredServers = new HashSet<Server>();
static ILogger logger = new LogLevelFilterLogger(new ConsoleLogger(), LogLevel.Off, true);
readonly IObjectPool<BatchContextSafeHandle> batchContextPool;
readonly IObjectPool<RequestCallContextSafeHandle> requestCallContextPool;
readonly GrpcThreadPool threadPool;
readonly DebugStats debugStats = new DebugStats();
readonly AtomicCounter cqPickerCounter = new AtomicCounter();
bool isShutdown;
/// <summary>
/// Returns a reference-counted instance of initialized gRPC environment.
/// Subsequent invocations return the same instance unless reference count has dropped to zero previously.
/// </summary>
internal static GrpcEnvironment AddRef()
{
ShutdownHooks.Register();
lock (staticLock)
{
refCount++;
if (instance == null)
{
instance = new GrpcEnvironment();
}
return instance;
}
}
/// <summary>
/// Decrements the reference count for currently active environment and asynchronously shuts down the gRPC environment if reference count drops to zero.
/// </summary>
internal static async Task ReleaseAsync()
{
GrpcEnvironment instanceToShutdown = null;
lock (staticLock)
{
GrpcPreconditions.CheckState(refCount > 0);
refCount--;
if (refCount == 0)
{
instanceToShutdown = instance;
instance = null;
}
}
if (instanceToShutdown != null)
{
await instanceToShutdown.ShutdownAsync().ConfigureAwait(false);
}
}
internal static int GetRefCount()
{
lock (staticLock)
{
return refCount;
}
}
internal static void RegisterChannel(Channel channel)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(channel);
registeredChannels.Add(channel);
}
}
internal static void UnregisterChannel(Channel channel)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(channel);
GrpcPreconditions.CheckArgument(registeredChannels.Remove(channel), "Channel not found in the registered channels set.");
}
}
internal static void RegisterServer(Server server)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(server);
registeredServers.Add(server);
}
}
internal static void UnregisterServer(Server server)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(server);
GrpcPreconditions.CheckArgument(registeredServers.Remove(server), "Server not found in the registered servers set.");
}
}
/// <summary>
/// Requests shutdown of all channels created by the current process.
/// </summary>
public static Task ShutdownChannelsAsync()
{
HashSet<Channel> snapshot = null;
lock (staticLock)
{
snapshot = new HashSet<Channel>(registeredChannels);
}
return Task.WhenAll(snapshot.Select((channel) => channel.ShutdownAsync()));
}
/// <summary>
/// Requests immediate shutdown of all servers created by the current process.
/// </summary>
public static Task KillServersAsync()
{
HashSet<Server> snapshot = null;
lock (staticLock)
{
snapshot = new HashSet<Server>(registeredServers);
}
return Task.WhenAll(snapshot.Select((server) => server.KillAsync()));
}
/// <summary>
/// Gets application-wide logger used by gRPC.
/// </summary>
/// <value>The logger.</value>
public static ILogger Logger
{
get
{
return logger;
}
}
/// <summary>
/// Sets the application-wide logger that should be used by gRPC.
/// </summary>
public static void SetLogger(ILogger customLogger)
{
GrpcPreconditions.CheckNotNull(customLogger, "customLogger");
logger = customLogger;
}
/// <summary>
/// Sets the number of threads in the gRPC thread pool that polls for internal RPC events.
/// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// Setting thread pool size is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetThreadPoolSize(int threadCount)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(threadCount > 0, "threadCount needs to be a positive number");
customThreadPoolSize = threadCount;
}
}
/// <summary>
/// Sets the number of completion queues in the gRPC thread pool that polls for internal RPC events.
/// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// Setting the number of completions queues is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetCompletionQueueCount(int completionQueueCount)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(completionQueueCount > 0, "threadCount needs to be a positive number");
customCompletionQueueCount = completionQueueCount;
}
}
/// <summary>
/// By default, gRPC's internal event handlers get offloaded to .NET default thread pool thread (<c>inlineHandlers=false</c>).
/// Setting <c>inlineHandlers</c> to <c>true</c> will allow scheduling the event handlers directly to
/// <c>GrpcThreadPool</c> internal threads. That can lead to significant performance gains in some situations,
/// but requires user to never block in async code (incorrectly written code can easily lead to deadlocks).
/// Inlining handlers is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// Note: <c>inlineHandlers=true</c> was the default in gRPC C# v1.4.x and earlier.
/// </summary>
public static void SetHandlerInlining(bool inlineHandlers)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcEnvironment.inlineHandlers = inlineHandlers;
}
}
/// <summary>
/// Sets the parameters for a pool that caches batch context instances. Reusing batch context instances
/// instead of creating a new one for every C core operation helps reducing the GC pressure.
/// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// This is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetBatchContextPoolParams(int sharedCapacity, int threadLocalCapacity)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(sharedCapacity >= 0, "Shared capacity needs to be a non-negative number");
GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0, "Thread local capacity needs to be a non-negative number");
batchContextPoolSharedCapacity = sharedCapacity;
batchContextPoolThreadLocalCapacity = threadLocalCapacity;
}
}
/// <summary>
/// Sets the parameters for a pool that caches request call context instances. Reusing request call context instances
/// instead of creating a new one for every requested call in C core helps reducing the GC pressure.
/// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// This is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetRequestCallContextPoolParams(int sharedCapacity, int threadLocalCapacity)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(sharedCapacity >= 0, "Shared capacity needs to be a non-negative number");
GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0, "Thread local capacity needs to be a non-negative number");
requestCallContextPoolSharedCapacity = sharedCapacity;
requestCallContextPoolThreadLocalCapacity = threadLocalCapacity;
}
}
/// <summary>
/// Occurs when <c>GrpcEnvironment</c> is about the start the shutdown logic.
/// If <c>GrpcEnvironment</c> is later initialized and shutdown, the event will be fired again (unless unregistered first).
/// </summary>
public static event EventHandler ShuttingDown;
/// <summary>
/// Creates gRPC environment.
/// </summary>
private GrpcEnvironment()
{
GrpcNativeInit();
batchContextPool = new DefaultObjectPool<BatchContextSafeHandle>(() => BatchContextSafeHandle.Create(), batchContextPoolSharedCapacity, batchContextPoolThreadLocalCapacity);
requestCallContextPool = new DefaultObjectPool<RequestCallContextSafeHandle>(() => RequestCallContextSafeHandle.Create(), requestCallContextPoolSharedCapacity, requestCallContextPoolThreadLocalCapacity);
threadPool = new GrpcThreadPool(this, GetThreadPoolSizeOrDefault(), GetCompletionQueueCountOrDefault(), inlineHandlers);
threadPool.Start();
}
/// <summary>
/// Gets the completion queues used by this gRPC environment.
/// </summary>
internal IReadOnlyCollection<CompletionQueueSafeHandle> CompletionQueues
{
get
{
return this.threadPool.CompletionQueues;
}
}
internal IObjectPool<BatchContextSafeHandle> BatchContextPool => batchContextPool;
internal IObjectPool<RequestCallContextSafeHandle> RequestCallContextPool => requestCallContextPool;
internal bool IsAlive
{
get
{
return this.threadPool.IsAlive;
}
}
/// <summary>
/// Picks a completion queue in a round-robin fashion.
/// Shouldn't be invoked on a per-call basis (used at per-channel basis).
/// </summary>
internal CompletionQueueSafeHandle PickCompletionQueue()
{
var cqIndex = (int) ((cqPickerCounter.Increment() - 1) % this.threadPool.CompletionQueues.Count);
return this.threadPool.CompletionQueues.ElementAt(cqIndex);
}
/// <summary>
/// Gets the completion queue used by this gRPC environment.
/// </summary>
internal DebugStats DebugStats
{
get
{
return this.debugStats;
}
}
/// <summary>
/// Gets version of gRPC C core.
/// </summary>
internal static string GetCoreVersionString()
{
var ptr = NativeMethods.Get().grpcsharp_version_string(); // the pointer is not owned
return Marshal.PtrToStringAnsi(ptr);
}
internal static void GrpcNativeInit()
{
NativeMethods.Get().grpcsharp_init();
}
internal static void GrpcNativeShutdown()
{
NativeMethods.Get().grpcsharp_shutdown();
}
/// <summary>
/// Shuts down this environment.
/// </summary>
private async Task ShutdownAsync()
{
if (isShutdown)
{
throw new InvalidOperationException("ShutdownAsync has already been called");
}
await Task.Run(() => ShuttingDown?.Invoke(this, null)).ConfigureAwait(false);
await threadPool.StopAsync().ConfigureAwait(false);
requestCallContextPool.Dispose();
batchContextPool.Dispose();
GrpcNativeShutdown();
isShutdown = true;
debugStats.CheckOK();
}
private int GetThreadPoolSizeOrDefault()
{
if (customThreadPoolSize.HasValue)
{
return customThreadPoolSize.Value;
}
// In systems with many cores, use half of the cores for GrpcThreadPool
// and the other half for .NET thread pool. This heuristic definitely needs
// more work, but seems to work reasonably well for a start.
return Math.Max(MinDefaultThreadPoolSize, Environment.ProcessorCount / 2);
}
private int GetCompletionQueueCountOrDefault()
{
if (customCompletionQueueCount.HasValue)
{
return customCompletionQueueCount.Value;
}
// by default, create a completion queue for each thread
return GetThreadPoolSizeOrDefault();
}
private static class ShutdownHooks
{
static object staticLock = new object();
static bool hooksRegistered;
public static void Register()
{
lock (staticLock)
{
if (!hooksRegistered)
{
// Under normal circumstances, the user is expected to shutdown all
// the gRPC channels and servers before the application exits. The following
// hooks provide some extra handling for cases when this is not the case,
// in the effort to achieve a reasonable behavior on shutdown.
#if NETSTANDARD1_5
// No action required at shutdown on .NET Core
// - In-progress P/Invoke calls (such as grpc_completion_queue_next) don't seem
// to prevent a .NET core application from terminating, so no special handling
// is needed.
// - .NET core doesn't run finalizers on shutdown, so there's no risk of getting
// a crash because grpc_*_destroy methods for native objects being invoked
// in wrong order.
// TODO(jtattermusch): Verify that the shutdown hooks are still not needed
// once we add support for new platforms using netstandard (e.g. Xamarin).
#else
// On desktop .NET framework and Mono, we need to register for a shutdown
// event to explicitly shutdown the GrpcEnvironment.
// - On Desktop .NET framework, we need to do a proper shutdown to prevent a crash
// when the framework attempts to run the finalizers for SafeHandle object representing the native
// grpc objects. The finalizers calls the native grpc_*_destroy methods (e.g. grpc_server_destroy)
// in a random order, which is not supported by gRPC.
// - On Mono, the process would hang as the GrpcThreadPool threads are sleeping
// in grpc_completion_queue_next P/Invoke invocation and mono won't let the
// process shutdown until the P/Invoke calls return. We achieve that by shutting down
// the completion queue(s) which associated with the GrpcThreadPool, which will
// cause the grpc_completion_queue_next calls to return immediately.
AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { HandleShutdown(); };
AppDomain.CurrentDomain.DomainUnload += (sender, eventArgs) => { HandleShutdown(); };
#endif
}
hooksRegistered = true;
}
}
/// <summary>
/// Handler for AppDomain.DomainUnload, AppDomain.ProcessExit and AssemblyLoadContext.Unloading hooks.
/// </summary>
private static void HandleShutdown()
{
Task.WaitAll(GrpcEnvironment.ShutdownChannelsAsync(), GrpcEnvironment.KillServersAsync());
}
}
}
}
| |
// 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.
// Do not remove this, it is needed to retain calls to these conditional methods in release builds
#define DEBUG
namespace System.Diagnostics
{
/// <summary>
/// Provides a set of properties and methods for debugging code.
/// </summary>
static partial class Debug
{
private static readonly object s_lock = new object();
public static bool AutoFlush { get { return true; } set { } }
[ThreadStatic]
private static int s_indentLevel;
public static int IndentLevel
{
get
{
return s_indentLevel;
}
set
{
s_indentLevel = value < 0 ? 0 : value;
}
}
private static int s_indentSize = 4;
public static int IndentSize
{
get
{
return s_indentSize;
}
set
{
s_indentSize = value < 0 ? 0 : value;
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Close() { }
[System.Diagnostics.Conditional("DEBUG")]
public static void Flush() { }
[System.Diagnostics.Conditional("DEBUG")]
public static void Indent()
{
IndentLevel++;
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Unindent()
{
IndentLevel--;
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Print(string message)
{
Write(message);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Print(string format, params object[] args)
{
Write(string.Format(null, format, args));
}
private static readonly object s_ForLock = new Object();
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert(bool condition)
{
Assert(condition, string.Empty, string.Empty);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert(bool condition, string message)
{
Assert(condition, message, string.Empty);
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Security.SecuritySafeCritical]
public static void Assert(bool condition, string message, string detailMessage)
{
if (!condition)
{
string stackTrace;
try
{
stackTrace = Environment.StackTrace;
}
catch
{
stackTrace = "";
}
WriteLine(FormatAssert(stackTrace, message, detailMessage));
s_logger.ShowAssertDialog(stackTrace, message, detailMessage);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Fail(string message)
{
Assert(false, message, string.Empty);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Fail(string message, string detailMessage)
{
Assert(false, message, detailMessage);
}
private static string FormatAssert(string stackTrace, string message, string detailMessage)
{
var newLine = GetIndentString() + Environment.NewLine;
return SR.DebugAssertBanner + newLine
+ SR.DebugAssertShortMessage + newLine
+ message + newLine
+ SR.DebugAssertLongMessage + newLine
+ detailMessage + newLine
+ stackTrace;
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert(bool condition, string message, string detailMessageFormat, params object[] args)
{
Assert(condition, message, string.Format(detailMessageFormat, args));
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(string message)
{
Write(message + Environment.NewLine);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(string message)
{
lock (s_lock)
{
if (message == null)
{
WriteCore(string.Empty);
return;
}
if (s_needIndent)
{
message = GetIndentString() + message;
s_needIndent = false;
}
WriteCore(message);
if (message.EndsWith(Environment.NewLine))
{
s_needIndent = true;
}
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(object value)
{
WriteLine(value?.ToString());
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(object value, string category)
{
WriteLine(value?.ToString(), category);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(string format, params object[] args)
{
WriteLine(string.Format(null, format, args));
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(string message, string category)
{
if (category == null)
{
WriteLine(message);
}
else
{
WriteLine(category + ":" + message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(object value)
{
Write(value?.ToString());
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(string message, string category)
{
if (category == null)
{
Write(message);
}
else
{
Write(category + ":" + message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(object value, string category)
{
Write(value?.ToString(), category);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, string message)
{
if (condition)
{
Write(message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, object value)
{
if (condition)
{
Write(value);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, string message, string category)
{
if (condition)
{
Write(message, category);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, object value, string category)
{
if (condition)
{
Write(value, category);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, object value)
{
if (condition)
{
WriteLine(value);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, object value, string category)
{
if (condition)
{
WriteLine(value, category);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, string message)
{
if (condition)
{
WriteLine(message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, string message, string category)
{
if (condition)
{
WriteLine(message, category);
}
}
private static bool s_needIndent;
private static string s_indentString;
private static string GetIndentString()
{
int indentCount = IndentSize * IndentLevel;
if (s_indentString?.Length == indentCount)
{
return s_indentString;
}
return s_indentString = new string(' ', indentCount);
}
private static void WriteCore(string message)
{
s_logger.WriteCore(message);
}
internal interface IDebugLogger
{
void ShowAssertDialog(string stackTrace, string message, string detailMessage);
void WriteCore(string message);
}
private sealed class DebugAssertException : Exception
{
internal DebugAssertException(string message, string detailMessage, string stackTrace) :
base(message + Environment.NewLine + detailMessage + Environment.NewLine + stackTrace)
{
}
}
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using IdentityServerWithEfCoreDemo.EntityFrameworkCore;
namespace IdentityServerWithEfCoreDemo.Migrations
{
[DbContext(typeof(IdentityServerWithEfCoreDemoDbContext))]
[Migration("20170424115119_Initial_Migrations")]
partial class Initial_Migrations
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.1")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration")
.HasColumnType("int");
b.Property<DateTime>("ExecutionTime")
.HasColumnType("datetime2");
b.Property<int?>("ImpersonatorTenantId")
.HasColumnType("int");
b.Property<long?>("ImpersonatorUserId")
.HasColumnType("bigint");
b.Property<string>("MethodName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<string>("ServiceName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsGranted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(450)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<int?>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.HasColumnType("nvarchar(450)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastLoginTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<long?>("UserLinkId")
.HasColumnType("bigint");
b.Property<string>("UserName")
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(450)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("LoginProvider")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<byte>("Result")
.HasColumnType("tinyint");
b.Property<string>("TenancyName")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("UserNameOrEmailAddress")
.HasColumnType("nvarchar(255)")
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long>("OrganizationUnitId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsAbandoned")
.HasColumnType("bit");
b.Property<string>("JobArgs")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime")
.HasColumnType("datetime2");
b.Property<DateTime>("NextTryTime")
.HasColumnType("datetime2");
b.Property<byte>("Priority")
.HasColumnType("tinyint");
b.Property<short>("TryCount")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("Icon")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<string>("TenantIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int>("State")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<Guid>("TenantNotificationId")
.HasColumnType("uniqueidentifier");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(95)")
.HasMaxLength(95);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<long?>("ParentId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("IdentityServerWithEfCoreDemo.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDefault")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsStatic")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("IdentityServerWithEfCoreDemo.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("AuthenticationSource")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsEmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsLockoutEnabled")
.HasColumnType("bit");
b.Property<bool>("IsPhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsTwoFactorEnabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastLoginTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LockoutEndDateUtc")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("IdentityServerWithEfCoreDemo.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ConnectionString")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("EditionId")
.HasColumnType("int");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId")
.HasColumnType("int");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("TenantId")
.HasColumnType("int");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Roles.Role")
.WithMany("Claims")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User")
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("IdentityServerWithEfCoreDemo.Authorization.Roles.Role", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("IdentityServerWithEfCoreDemo.Authorization.Users.User", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("IdentityServerWithEfCoreDemo.MultiTenancy.Tenant", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Roles.Role")
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("IdentityServerWithEfCoreDemo.Authorization.Users.User")
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace CalorieCounter.API.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
namespace Bog.Web.Dashboard.Areas.HelpPage
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator" /> class.
/// </summary>
public HelpPageSampleGenerator()
{
this.ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
this.ActionSamples = new Dictionary<HelpPageSampleKey, object>();
this.SampleObjects = new Dictionary<Type, object>();
}
#endregion
#region Public Properties
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage" /> or
/// <see cref="HttpResponseMessage" />.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
#endregion
#region Public Methods and Operators
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">
/// Name of the controller.
/// </param>
/// <param name="actionName">
/// Name of the action.
/// </param>
/// <param name="parameterNames">
/// The parameter names.
/// </param>
/// <param name="type">
/// The CLR type.
/// </param>
/// <param name="formatter">
/// The formatter.
/// </param>
/// <param name="mediaType">
/// The media type.
/// </param>
/// <param name="sampleDirection">
/// The value indicating whether the sample is for a request or for a response.
/// </param>
/// <returns>
/// The sample that matches the parameters.
/// </returns>
public virtual object GetActionSample(
string controllerName,
string actionName,
IEnumerable<string> parameterNames,
Type type,
MediaTypeFormatter formatter,
MediaTypeHeaderValue mediaType,
SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (
this.ActionSamples.TryGetValue(
new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames),
out sample)
|| this.ActionSamples.TryGetValue(
new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }),
out sample) || this.ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">
/// The <see cref="ApiDescription"/>.
/// </param>
/// <param name="sampleDirection">
/// The value indicating whether the sample is for a request or for a response.
/// </param>
/// <returns>
/// The samples keyed by media type.
/// </returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(
ApiDescription api,
SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = this.ResolveType(
api,
controllerName,
actionName,
parameterNames,
sampleDirection,
out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
IEnumerable<KeyValuePair<HelpPageSampleKey, object>> actionSamples = this.GetAllActionSamples(
controllerName,
actionName,
parameterNames,
sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = this.GetSampleObject(type);
foreach (MediaTypeFormatter formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = this.GetActionSample(
controllerName,
actionName,
parameterNames,
type,
formatter,
mediaType,
sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = this.WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one
/// using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// The sample object.
/// </returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!this.SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
var objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">
/// The <see cref="ApiDescription"/>.
/// </param>
/// <returns>
/// The samples keyed by media type.
/// </returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return this.GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">
/// The <see cref="ApiDescription"/>.
/// </param>
/// <returns>
/// The samples keyed by media type.
/// </returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return this.GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or
/// <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">
/// The <see cref="ApiDescription"/>.
/// </param>
/// <param name="controllerName">
/// Name of the controller.
/// </param>
/// <param name="actionName">
/// Name of the action.
/// </param>
/// <param name="parameterNames">
/// The parameter names.
/// </param>
/// <param name="sampleDirection">
/// The value indicating whether the sample is for a request or a response.
/// </param>
/// <param name="formatters">
/// The formatters.
/// </param>
/// <returns>
/// The <see cref="Type"/>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters",
Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(
ApiDescription api,
string controllerName,
string actionName,
IEnumerable<string> parameterNames,
SampleDirection sampleDirection,
out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (
this.ActualHttpMessageTypes.TryGetValue(
new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames),
out type)
|| this.ActualHttpMessageTypes.TryGetValue(
new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }),
out type))
{
// Re-compute the supported formatters based on type
var newFormatters = new Collection<MediaTypeFormatter>();
foreach (MediaTypeFormatter formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter =
api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null
? null
: requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">
/// The formatter.
/// </param>
/// <param name="value">
/// The value.
/// </param>
/// <param name="type">
/// The type.
/// </param>
/// <param name="mediaType">
/// Type of the media.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(
MediaTypeFormatter formatter,
object value,
Type type,
MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = string.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
var reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample =
new InvalidSample(
string.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample =
new InvalidSample(
string.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
#endregion
#region Methods
/// <summary>
/// The is format supported.
/// </summary>
/// <param name="sampleDirection">
/// The sample direction.
/// </param>
/// <param name="formatter">
/// The formatter.
/// </param>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
/// <summary>
/// The try format json.
/// </summary>
/// <param name="str">
/// The str.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
/// <summary>
/// The try format xml.
/// </summary>
/// <param name="str">
/// The str.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
/// <summary>
/// The wrap sample if string.
/// </summary>
/// <param name="sample">
/// The sample.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
private static object WrapSampleIfString(object sample)
{
var stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
/// <summary>
/// The get all action samples.
/// </summary>
/// <param name="controllerName">
/// The controller name.
/// </param>
/// <param name="actionName">
/// The action name.
/// </param>
/// <param name="parameterNames">
/// The parameter names.
/// </param>
/// <param name="sampleDirection">
/// The sample direction.
/// </param>
/// <returns>
/// The <see cref="IEnumerable"/>.
/// </returns>
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(
string controllerName,
string actionName,
IEnumerable<string> parameterNames,
SampleDirection sampleDirection)
{
var parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in this.ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (string.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase)
&& string.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase)
&& (sampleKey.ParameterNames.SetEquals(new[] { "*" })
|| parameterNamesSet.SetEquals(sampleKey.ParameterNames))
&& sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
#endregion
}
}
| |
/* NOTE: these values and descriptions are copied from the .NET Micro Framework source (Apache 2.0 license). Copyright (c) Microsoft. */
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
namespace Netduino.IP
{
public enum SocketError : int
{
/// <devdoc>
/// <para>
/// The operation completed succesfully.
/// </para>
/// </devdoc>
Success = 0,
/// <devdoc>
/// <para>
/// The socket has an error.
/// </para>
/// </devdoc>
SocketError = (-1),
/*
* Windows Sockets definitions of regular Microsoft C error constants
*/
/// <devdoc>
/// <para>
/// A blocking socket call was canceled.
/// </para>
/// </devdoc>
Interrupted = (10000 + 4), //WSAEINTR
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
//WSAEBADF = (10000+9), //
/// <devdoc>
/// <para>
/// Permission denied.
/// </para>
/// </devdoc>
AccessDenied = (10000 + 13), //WSAEACCES
/// <devdoc>
/// <para>
/// Bad address.
/// </para>
/// </devdoc>
Fault = (10000 + 14), //WSAEFAULT
/// <devdoc>
/// <para>
/// Invalid argument.
/// </para>
/// </devdoc>
InvalidArgument = (10000 + 22), //WSAEINVAL
/// <devdoc>
/// <para>
/// Too many open
/// files.
/// </para>
/// </devdoc>
TooManyOpenSockets = (10000 + 24), //WSAEMFILE
/*
* Windows Sockets definitions of regular Berkeley error constants
*/
/// <devdoc>
/// <para>
/// Resource temporarily unavailable.
/// </para>
/// </devdoc>
WouldBlock = (10000 + 35), //WSAEWOULDBLOCK
/// <devdoc>
/// <para>
/// Operation now in progress.
/// </para>
/// </devdoc>
InProgress = (10000 + 36), // WSAEINPROGRESS
/// <devdoc>
/// <para>
/// Operation already in progress.
/// </para>
/// </devdoc>
AlreadyInProgress = (10000 + 37), //WSAEALREADY
/// <devdoc>
/// <para>
/// Socket operation on nonsocket.
/// </para>
/// </devdoc>
NotSocket = (10000 + 38), //WSAENOTSOCK
/// <devdoc>
/// <para>
/// Destination address required.
/// </para>
/// </devdoc>
DestinationAddressRequired = (10000 + 39), //WSAEDESTADDRREQ
/// <devdoc>
/// <para>
/// Message too long.
/// </para>
/// </devdoc>
MessageSize = (10000 + 40), //WSAEMSGSIZE
/// <devdoc>
/// <para>
/// Protocol wrong type for socket.
/// </para>
/// </devdoc>
ProtocolType = (10000 + 41), //WSAEPROTOTYPE
/// <devdoc>
/// <para>
/// Bad protocol option.
/// </para>
/// </devdoc>
ProtocolOption = (10000 + 42), //WSAENOPROTOOPT
/// <devdoc>
/// <para>
/// Protocol not supported.
/// </para>
/// </devdoc>
ProtocolNotSupported = (10000 + 43), //WSAEPROTONOSUPPORT
/// <devdoc>
/// <para>
/// Socket type not supported.
/// </para>
/// </devdoc>
SocketNotSupported = (10000 + 44), //WSAESOCKTNOSUPPORT
/// <devdoc>
/// <para>
/// Operation not supported.
/// </para>
/// </devdoc>
OperationNotSupported = (10000 + 45), //WSAEOPNOTSUPP
/// <devdoc>
/// <para>
/// Protocol family not supported.
/// </para>
/// </devdoc>
ProtocolFamilyNotSupported = (10000 + 46), //WSAEPFNOSUPPORT
/// <devdoc>
/// <para>
/// Address family not supported by protocol family.
/// </para>
/// </devdoc>
AddressFamilyNotSupported = (10000 + 47), //WSAEAFNOSUPPORT
/// <devdoc>
/// Address already in use.
/// </devdoc>
AddressAlreadyInUse = (10000 + 48), // WSAEADDRINUSE
/// <devdoc>
/// <para>
/// Cannot assign requested address.
/// </para>
/// </devdoc>
AddressNotAvailable = (10000 + 49), //WSAEADDRNOTAVAIL
/// <devdoc>
/// <para>
/// Network is down.
/// </para>
/// </devdoc>
NetworkDown = (10000 + 50), //WSAENETDOWN
/// <devdoc>
/// <para>
/// Network is unreachable.
/// </para>
/// </devdoc>
NetworkUnreachable = (10000 + 51), //WSAENETUNREACH
/// <devdoc>
/// <para>
/// Network dropped connection on reset.
/// </para>
/// </devdoc>
NetworkReset = (10000 + 52), //WSAENETRESET
/// <devdoc>
/// <para>
/// Software caused connection to abort.
/// </para>
/// </devdoc>
ConnectionAborted = (10000 + 53), //WSAECONNABORTED
/// <devdoc>
/// <para>
/// Connection reset by peer.
/// </para>
/// </devdoc>
ConnectionReset = (10000 + 54), //WSAECONNRESET
/// <devdoc>
/// No buffer space available.
/// </devdoc>
NoBufferSpaceAvailable = (10000 + 55), //WSAENOBUFS
/// <devdoc>
/// <para>
/// Socket is already connected.
/// </para>
/// </devdoc>
IsConnected = (10000 + 56), //WSAEISCONN
/// <devdoc>
/// <para>
/// Socket is not connected.
/// </para>
/// </devdoc>
NotConnected = (10000 + 57), //WSAENOTCONN
/// <devdoc>
/// <para>
/// Cannot send after socket shutdown.
/// </para>
/// </devdoc>
Shutdown = (10000 + 58), //WSAESHUTDOWN
/// <devdoc>
/// <para>
/// Connection timed out.
/// </para>
/// </devdoc>
TimedOut = (10000 + 60), //WSAETIMEDOUT
/// <devdoc>
/// <para>
/// Connection refused.
/// </para>
/// </devdoc>
ConnectionRefused = (10000 + 61), //WSAECONNREFUSED
/// <devdoc>
/// <para>
/// Host is down.
/// </para>
/// </devdoc>
HostDown = (10000 + 64), //WSAEHOSTDOWN
/// <devdoc>
/// <para>
/// No route to host.
/// </para>
/// </devdoc>
HostUnreachable = (10000 + 65), //WSAEHOSTUNREACH
/// <devdoc>
/// <para>
/// Too many processes.
/// </para>
/// </devdoc>
ProcessLimit = (10000 + 67), //WSAEPROCLIM
/// <devdoc>
/// <para>
/// [To be supplied.]
/// </para>
/// </devdoc>
/*
* Extended Windows Sockets error constant definitions
*/
/// <devdoc>
/// <para>
/// Network subsystem is unavailable.
/// </para>
/// </devdoc>
SystemNotReady = (10000 + 91), //WSASYSNOTREADY
/// <devdoc>
/// <para>
/// Winsock.dll out of range.
/// </para>
/// </devdoc>
VersionNotSupported = (10000 + 92), //WSAVERNOTSUPPORTED
/// <devdoc>
/// <para>
/// Successful startup not yet performed.
/// </para>
/// </devdoc>
NotInitialized = (10000 + 93), //WSANOTINITIALISED
// WSAEREMOTE = (10000+71),
/// <devdoc>
/// <para>
/// Graceful shutdown in progress.
/// </para>
/// </devdoc>
Disconnecting = (10000 + 101), //WSAEDISCON
TypeNotFound = (10000 + 109), //WSATYPE_NOT_FOUND
/*
* Error return codes from gethostbyname() and gethostbyaddr()
* = (when using the resolver). Note that these errors are
* retrieved via WSAGetLastError() and must therefore follow
* the rules for avoiding clashes with error numbers from
* specific implementations or language run-time systems.
* For this reason the codes are based at 10000+1001.
* Note also that [WSA]NO_ADDRESS is defined only for
* compatibility purposes.
*/
/// <devdoc>
/// <para>
/// Host not found (Authoritative Answer: Host not found).
/// </para>
/// </devdoc>
HostNotFound = (10000 + 1001), //WSAHOST_NOT_FOUND
/// <devdoc>
/// <para>
/// Nonauthoritative host not found (Non-Authoritative: Host not found, or SERVERFAIL).
/// </para>
/// </devdoc>
TryAgain = (10000 + 1002), //WSATRY_AGAIN
/// <devdoc>
/// <para>
/// This is a nonrecoverable error (Non recoverable errors, FORMERR, REFUSED, NOTIMP).
/// </para>
/// </devdoc>
NoRecovery = (10000 + 1003), //WSANO_RECOVERY
/// <devdoc>
/// <para>
/// Valid name, no data record of requested type.
/// </para>
/// </devdoc>
NoData = (10000 + 1004), //WSANO_DATA
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Common.Logging;
using Rhino.ServiceBus.Utils;
using Rhino.ServiceBus.Exceptions;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.MessageModules;
using Rhino.ServiceBus.Messages;
using Rhino.ServiceBus.Sagas;
namespace Rhino.ServiceBus.Impl
{
public class DefaultServiceBus : IStartableServiceBus
{
private readonly IServiceLocator serviceLocator;
private readonly ILog logger = LogManager.GetLogger(typeof(DefaultServiceBus));
private readonly IMessageModule[] modules;
private readonly IReflection reflection;
private readonly ISubscriptionStorage subscriptionStorage;
private readonly ITransport transport;
private readonly MessageOwnersSelector messageOwners;
[ThreadStatic] public static object currentMessage;
private readonly IEndpointRouter endpointRouter;
private IEnumerable<IServiceBusAware> serviceBusAware = new IServiceBusAware[0];
public DefaultServiceBus(
IServiceLocator serviceLocator,
ITransport transport,
ISubscriptionStorage subscriptionStorage,
IReflection reflection,
IMessageModule[] modules,
MessageOwner[] messageOwners,
IEndpointRouter endpointRouter)
{
this.transport = transport;
this.endpointRouter = endpointRouter;
this.messageOwners = new MessageOwnersSelector(messageOwners, endpointRouter);
this.subscriptionStorage = subscriptionStorage;
this.reflection = reflection;
this.modules = modules;
this.serviceLocator = serviceLocator;
}
public IMessageModule[] Modules
{
get { return modules; }
}
public event Action<Reroute> ReroutedEndpoint;
public void Publish(params object[] messages)
{
if (PublishInternal(messages) == false)
throw new MessagePublicationException("There were no subscribers for (" +
messages.First() + ")"
);
}
public void Notify(params object[] messages)
{
PublishInternal(messages);
}
public void Reply(params object[] messages)
{
if (messages == null)
throw new ArgumentNullException("messages");
if (messages.Length == 0)
throw new MessagePublicationException("Cannot reply with an empty message batch");
transport.Reply(messages);
}
public void Send(Endpoint endpoint, params object[] messages)
{
if (messages == null)
throw new ArgumentNullException("messages");
if (messages.Length == 0)
throw new MessagePublicationException("Cannot send empty message batch");
transport.Send(endpoint, messages);
}
public void Send(params object[] messages)
{
Send(messageOwners.GetEndpointForMessageBatch(messages), messages);
}
public void ConsumeMessages(params object[] messages)
{
foreach (var message in messages)
{
var currentMessageInfo = new CurrentMessageInformation
{
AllMessages = messages,
Message = message,
MessageId = Guid.NewGuid(),
Destination = transport.Endpoint.Uri,
Source = transport.Endpoint.Uri,
TransportMessageId = "ConsumeMessages"
};
Transport_OnMessageArrived(currentMessageInfo);
}
}
public IDisposable AddInstanceSubscription(IMessageConsumer consumer)
{
var information = new InstanceSubscriptionInformation
{
Consumer = consumer,
InstanceSubscriptionKey = Guid.NewGuid(),
ConsumedMessages = reflection.GetMessagesConsumed(consumer),
};
subscriptionStorage.AddLocalInstanceSubscription(consumer);
SubscribeInstanceSubscription(information);
return new DisposableAction(() =>
{
subscriptionStorage.RemoveLocalInstanceSubscription(information.Consumer);
UnsubscribeInstanceSubscription(information);
information.Dispose();
});
}
public Endpoint Endpoint
{
get { return transport.Endpoint; }
}
public CurrentMessageInformation CurrentMessageInformation
{
get { return transport.CurrentMessageInformation; }
}
public void Dispose()
{
foreach(var aware in serviceBusAware)
aware.BusDisposing(this);
transport.Dispose();
transport.MessageArrived -= Transport_OnMessageArrived;
foreach (IMessageModule module in modules)
{
module.Stop(transport, this);
}
var subscriptionAsModule = subscriptionStorage as IMessageModule;
if (subscriptionAsModule != null)
subscriptionAsModule.Stop(transport, this);
var disposableSubscriptionStorage = subscriptionStorage as IDisposable;
if (disposableSubscriptionStorage != null)
disposableSubscriptionStorage.Dispose();
foreach(var aware in serviceBusAware)
aware.BusDisposed(this);
}
public void Start()
{
serviceBusAware = serviceLocator.ResolveAll<IServiceBusAware>();
foreach(var aware in serviceBusAware)
aware.BusStarting(this);
logger.DebugFormat("Starting the bus for {0}", Endpoint);
var subscriptionAsModule = subscriptionStorage as IMessageModule;
if (subscriptionAsModule != null)
{
logger.DebugFormat("Initating subscription storage as message module: {0}", subscriptionAsModule);
subscriptionAsModule.Init(transport, this);
}
foreach (var module in modules)
{
logger.DebugFormat("Initating message module: {0}", module);
module.Init(transport, this);
}
transport.MessageArrived += Transport_OnMessageArrived;
transport.AdministrativeMessageArrived += Transport_OnAdministrativeMessageArrived;
subscriptionStorage.Initialize();
transport.Start();
AutomaticallySubscribeConsumerMessages();
foreach(var aware in serviceBusAware)
aware.BusStarted(this);
}
private bool Transport_OnAdministrativeMessageArrived(CurrentMessageInformation info)
{
var route = info.Message as Reroute;
if (route == null)
return false;
endpointRouter.RemapEndpoint(route.OriginalEndPoint, route.NewEndPoint);
var reroutedEndpoint = ReroutedEndpoint;
if(reroutedEndpoint!=null)
reroutedEndpoint(route);
return true;
}
public void Subscribe(Type type)
{
foreach (var owner in messageOwners.Of(type))
{
logger.InfoFormat("Subscribing {0} on {1}", type.FullName, owner.Endpoint);
var endpoint = endpointRouter.GetRoutedEndpoint(owner.Endpoint);
endpoint.Transactional = owner.Transactional;
Send(endpoint, new AddSubscription
{
Endpoint = Endpoint,
Type = type.FullName
});
}
}
public void Subscribe<T>()
{
Subscribe(typeof(T));
}
public void Unsubscribe<T>()
{
Unsubscribe(typeof(T));
}
public void Unsubscribe(Type type)
{
foreach (var owner in messageOwners.Of(type))
{
var endpoint = endpointRouter.GetRoutedEndpoint(owner.Endpoint);
endpoint.Transactional = owner.Transactional;
Send(endpoint, new RemoveSubscription
{
Endpoint = Endpoint,
Type = type.FullName
});
}
}
private void SubscribeInstanceSubscription(InstanceSubscriptionInformation information)
{
foreach (var message in information.ConsumedMessages)
{
bool subscribed = false;
foreach (var owner in messageOwners.Of(message))
{
logger.DebugFormat("Instance subscribition for {0} on {1}",
message.FullName,
owner.Endpoint);
subscribed = true;
var endpoint = endpointRouter.GetRoutedEndpoint(owner.Endpoint);
endpoint.Transactional = owner.Transactional;
Send(endpoint, new AddInstanceSubscription
{
Endpoint = Endpoint.Uri.ToString(),
Type = message.FullName,
InstanceSubscriptionKey = information.InstanceSubscriptionKey
});
}
if(subscribed ==false)
throw new SubscriptionException("Could not find any owner for message " + message +
" that we could subscribe for");
}
}
public void UnsubscribeInstanceSubscription(InstanceSubscriptionInformation information)
{
foreach (var message in information.ConsumedMessages)
{
foreach (var owner in messageOwners.Of(message))
{
var endpoint = endpointRouter.GetRoutedEndpoint(owner.Endpoint);
endpoint.Transactional = owner.Transactional;
Send(endpoint, new RemoveInstanceSubscription
{
Endpoint = Endpoint.Uri.ToString(),
Type = message.FullName,
InstanceSubscriptionKey = information.InstanceSubscriptionKey
});
}
}
}
/// <summary>
/// Send the message with a built in delay in its processing
/// </summary>
/// <param name="endpoint">The endpoint.</param>
/// <param name="time">The time.</param>
/// <param name="msgs">The messages.</param>
public void DelaySend(Endpoint endpoint, DateTime time, params object[] msgs)
{
transport.Send(endpoint, time, msgs);
}
/// <summary>
/// Send the message with a built in delay in its processing
/// </summary>
/// <param name="time">The time.</param>
/// <param name="msgs">The messages.</param>
public void DelaySend(DateTime time, params object[] msgs)
{
DelaySend(messageOwners.GetEndpointForMessageBatch(msgs), time, msgs);
}
private void AutomaticallySubscribeConsumerMessages()
{
var handlers = serviceLocator.GetAllHandlersFor(typeof(IMessageConsumer));
foreach (var handler in handlers)
{
var msgs = reflection.GetMessagesConsumed(handler.Implementation,
type => type == typeof(OccasionalConsumerOf<>)
|| type == typeof(Consumer<>.SkipAutomaticSubscription));
foreach (var msg in msgs)
{
Subscribe(msg);
}
}
}
private bool PublishInternal(object[] messages)
{
if (messages == null)
throw new ArgumentNullException("messages");
bool sentMsg = false;
if (messages.Length == 0)
throw new MessagePublicationException("Cannot publish an empty message batch");
var subscriptions = new HashSet<Uri>();
foreach (var message in messages)
{
Type messageType = message.GetType();
while (messageType != null)
{
subscriptions.UnionWith(subscriptionStorage.GetSubscriptionsFor(messageType));
foreach (Type interfaceType in messageType.GetInterfaces())
{
subscriptions.UnionWith(subscriptionStorage.GetSubscriptionsFor(interfaceType));
}
messageType = messageType.BaseType;
}
}
foreach (Uri subscription in subscriptions)
{
transport.Send(endpointRouter.GetRoutedEndpoint(subscription), messages);
sentMsg = true;
}
return sentMsg;
}
public bool Transport_OnMessageArrived(CurrentMessageInformation msg)
{
var consumers = GatherConsumers(msg);
if (consumers.Length == 0)
{
logger.ErrorFormat("Got message {0}, but had no consumers for it", msg.Message);
return false;
}
try
{
currentMessage = msg.Message;
foreach (var consumer in consumers)
{
logger.DebugFormat("Invoking consume on {0} for message {1}, from '{2}' to '{3}'",
consumer,
msg.Message,
msg.Source,
msg.Destination);
var sp = Stopwatch.StartNew();
try
{
reflection.InvokeConsume(consumer, msg.Message);
}
catch (Exception e)
{
if(logger.IsDebugEnabled)
{
var message = string.Format("Consumer {0} failed to process message {1}",
consumer,
msg.Message
);
logger.Debug(message,e);
}
throw;
}
finally
{
sp.Stop();
var elapsed = sp.Elapsed;
logger.DebugFormat("Consumer {0} finished processing {1} in {2}", consumer, msg.Message, elapsed);
}
var sagaEntity = consumer as IAccessibleSaga;
if (sagaEntity == null)
continue;
PersistSagaInstance(sagaEntity);
}
return true;
}
finally
{
currentMessage = null;
foreach (var consumer in consumers)
{
serviceLocator.Release(consumer);
}
}
}
private void PersistSagaInstance(IAccessibleSaga saga)
{
Type persisterType = reflection.GetGenericTypeOf(typeof(ISagaPersister<>), saga);
object persister = serviceLocator.Resolve(persisterType);
if (saga.IsCompleted)
reflection.InvokeSagaPersisterComplete(persister, saga);
else
reflection.InvokeSagaPersisterSave(persister, saga);
}
public object[] GatherConsumers(CurrentMessageInformation msg)
{
var message = msg.Message;
object[] sagas = GetSagasFor(message);
var sagaMessage = message as ISagaMessage;
var msgType = message.GetType();
object[] instanceConsumers = subscriptionStorage
.GetInstanceSubscriptions(msgType);
var consumerTypes = reflection.GetGenericTypesOfWithBaseTypes(typeof(ConsumerOf<>), message);
var occasionalConsumerTypes = reflection.GetGenericTypesOfWithBaseTypes(typeof(OccasionalConsumerOf<>), message);
var consumers = GetAllNonOccasionalConsumers(consumerTypes, occasionalConsumerTypes, sagas);
for (var i = 0; i < consumers.Length; i++)
{
var saga = consumers[i] as IAccessibleSaga;
if (saga == null)
continue;
// if there is an existing saga, we skip the new one
var type = saga.GetType();
if (sagas.Any(type.IsInstanceOfType))
{
serviceLocator.Release(consumers[i]);
consumers[i] = null;
continue;
}
// we do not create new sagas if the saga is not initiated by
// the message
var initiatedBy = reflection.GetGenericTypeOf(typeof(InitiatedBy<>), msgType);
if (initiatedBy.IsInstanceOfType(saga) == false)
{
serviceLocator.Release(consumers[i]);
consumers[i] = null;
continue;
}
saga.Id = sagaMessage != null ?
sagaMessage.CorrelationId :
GuidCombGenerator.Generate();
}
return instanceConsumers
.Union(sagas)
.Union(consumers.Where(x => x != null))
.ToArray();
}
/// <summary>
/// Here we don't use ResolveAll from Windsor because we want to get an error
/// if a component exists which isn't valid
/// </summary>
private object[] GetAllNonOccasionalConsumers(IEnumerable<Type> consumerTypes, IEnumerable<Type> occasionalConsumerTypes, IEnumerable<object> instanceOfTypesToSkipResolving)
{
var allHandlers = new List<IHandler>();
foreach (var consumerType in consumerTypes)
{
var handlers = serviceLocator.GetAllHandlersFor(consumerType);
allHandlers.AddRange(handlers);
}
var consumers = new List<object>(allHandlers.Count);
consumers.AddRange(from handler in allHandlers
let implementation = handler.Implementation
let occasionalConsumerFound = occasionalConsumerTypes.Any(occasionalConsumerType => occasionalConsumerType.IsAssignableFrom(implementation))
where !occasionalConsumerFound
where !instanceOfTypesToSkipResolving.Any(x => x.GetType() == implementation)
select handler.Resolve());
return consumers.ToArray();
}
private object[] GetSagasFor(object message)
{
var instances = new List<object>();
Type orchestratesType = reflection.GetGenericTypeOf(typeof(Orchestrates<>), message);
Type initiatedByType = reflection.GetGenericTypeOf(typeof(InitiatedBy<>), message);
var handlers = serviceLocator.GetAllHandlersFor(orchestratesType)
.Union(serviceLocator.GetAllHandlersFor(initiatedByType));
foreach (IHandler sagaHandler in handlers)
{
Type sagaType = sagaHandler.Implementation;
//first try to execute any saga finders.
Type sagaFinderType = reflection.GetGenericTypeOf(typeof(ISagaFinder<,>), sagaType, reflection.GetUnproxiedType(message));
var sagaFinderHandlers = serviceLocator.GetAllHandlersFor(sagaFinderType);
foreach (var sagaFinderHandler in sagaFinderHandlers)
{
try
{
var sagaFinder = sagaFinderHandler.Resolve();
var saga = reflection.InvokeSagaFinderFindBy(sagaFinder, message);
if (saga != null)
instances.Add(saga);
}
finally
{
serviceLocator.Release(sagaFinderHandler);
}
}
//we will try to use an ISagaMessage's Correlation id next.
var sagaMessage = message as ISagaMessage;
if (sagaMessage == null)
continue;
Type sagaPersisterType = reflection.GetGenericTypeOf(typeof(ISagaPersister<>),
sagaType);
object sagaPersister = serviceLocator.Resolve(sagaPersisterType);
try
{
object sagas = reflection.InvokeSagaPersisterGet(sagaPersister, sagaMessage.CorrelationId);
if (sagas == null)
continue;
instances.Add(sagas);
}
finally
{
serviceLocator.Release(sagaPersister);
}
}
return instances.ToArray();
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// VM appliance
/// First published in XenServer 6.0.
/// </summary>
public partial class VM_appliance : XenObject<VM_appliance>
{
public VM_appliance()
{
}
public VM_appliance(string uuid,
string name_label,
string name_description,
List<vm_appliance_operation> allowed_operations,
Dictionary<string, vm_appliance_operation> current_operations,
List<XenRef<VM>> VMs)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.VMs = VMs;
}
/// <summary>
/// Creates a new VM_appliance from a Proxy_VM_appliance.
/// </summary>
/// <param name="proxy"></param>
public VM_appliance(Proxy_VM_appliance proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VM_appliance update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
VMs = update.VMs;
}
internal void UpdateFromProxy(Proxy_VM_appliance proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<vm_appliance_operation>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_vm_appliance_operation(proxy.current_operations);
VMs = proxy.VMs == null ? null : XenRef<VM>.Create(proxy.VMs);
}
public Proxy_VM_appliance ToProxy()
{
Proxy_VM_appliance result_ = new Proxy_VM_appliance();
result_.uuid = (uuid != null) ? uuid : "";
result_.name_label = (name_label != null) ? name_label : "";
result_.name_description = (name_description != null) ? name_description : "";
result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {};
result_.current_operations = Maps.convert_to_proxy_string_vm_appliance_operation(current_operations);
result_.VMs = (VMs != null) ? Helper.RefListToStringArray(VMs) : new string[] {};
return result_;
}
/// <summary>
/// Creates a new VM_appliance from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VM_appliance(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
name_label = Marshalling.ParseString(table, "name_label");
name_description = Marshalling.ParseString(table, "name_description");
allowed_operations = Helper.StringArrayToEnumList<vm_appliance_operation>(Marshalling.ParseStringArray(table, "allowed_operations"));
current_operations = Maps.convert_from_proxy_string_vm_appliance_operation(Marshalling.ParseHashTable(table, "current_operations"));
VMs = Marshalling.ParseSetRef<VM>(table, "VMs");
}
public bool DeepEquals(VM_appliance other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._VMs, other._VMs);
}
public override string SaveChanges(Session session, string opaqueRef, VM_appliance server)
{
if (opaqueRef == null)
{
Proxy_VM_appliance p = this.ToProxy();
return session.proxy.vm_appliance_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
VM_appliance.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
VM_appliance.set_name_description(session, opaqueRef, _name_description);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static VM_appliance get_record(Session session, string _vm_appliance)
{
return new VM_appliance((Proxy_VM_appliance)session.proxy.vm_appliance_get_record(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse());
}
/// <summary>
/// Get a reference to the VM_appliance instance with the specified UUID.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VM_appliance> get_by_uuid(Session session, string _uuid)
{
return XenRef<VM_appliance>.Create(session.proxy.vm_appliance_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Create a new VM_appliance instance, and return its handle.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<VM_appliance> create(Session session, VM_appliance _record)
{
return XenRef<VM_appliance>.Create(session.proxy.vm_appliance_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new VM_appliance instance, and return its handle.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, VM_appliance _record)
{
return XenRef<Task>.Create(session.proxy.async_vm_appliance_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified VM_appliance instance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void destroy(Session session, string _vm_appliance)
{
session.proxy.vm_appliance_destroy(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse();
}
/// <summary>
/// Destroy the specified VM_appliance instance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_destroy(Session session, string _vm_appliance)
{
return XenRef<Task>.Create(session.proxy.async_vm_appliance_destroy(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse());
}
/// <summary>
/// Get all the VM_appliance instances with the given label.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<VM_appliance>> get_by_name_label(Session session, string _label)
{
return XenRef<VM_appliance>.Create(session.proxy.vm_appliance_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse());
}
/// <summary>
/// Get the uuid field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static string get_uuid(Session session, string _vm_appliance)
{
return (string)session.proxy.vm_appliance_get_uuid(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse();
}
/// <summary>
/// Get the name/label field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static string get_name_label(Session session, string _vm_appliance)
{
return (string)session.proxy.vm_appliance_get_name_label(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse();
}
/// <summary>
/// Get the name/description field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static string get_name_description(Session session, string _vm_appliance)
{
return (string)session.proxy.vm_appliance_get_name_description(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static List<vm_appliance_operation> get_allowed_operations(Session session, string _vm_appliance)
{
return Helper.StringArrayToEnumList<vm_appliance_operation>(session.proxy.vm_appliance_get_allowed_operations(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse());
}
/// <summary>
/// Get the current_operations field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static Dictionary<string, vm_appliance_operation> get_current_operations(Session session, string _vm_appliance)
{
return Maps.convert_from_proxy_string_vm_appliance_operation(session.proxy.vm_appliance_get_current_operations(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse());
}
/// <summary>
/// Get the VMs field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static List<XenRef<VM>> get_VMs(Session session, string _vm_appliance)
{
return XenRef<VM>.Create(session.proxy.vm_appliance_get_vms(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse());
}
/// <summary>
/// Set the name/label field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _vm_appliance, string _label)
{
session.proxy.vm_appliance_set_name_label(session.uuid, (_vm_appliance != null) ? _vm_appliance : "", (_label != null) ? _label : "").parse();
}
/// <summary>
/// Set the name/description field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _vm_appliance, string _description)
{
session.proxy.vm_appliance_set_name_description(session.uuid, (_vm_appliance != null) ? _vm_appliance : "", (_description != null) ? _description : "").parse();
}
/// <summary>
/// Start all VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_paused">Instantiate all VMs belonging to this appliance in paused state if set to true.</param>
public static void start(Session session, string _vm_appliance, bool _paused)
{
session.proxy.vm_appliance_start(session.uuid, (_vm_appliance != null) ? _vm_appliance : "", _paused).parse();
}
/// <summary>
/// Start all VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_paused">Instantiate all VMs belonging to this appliance in paused state if set to true.</param>
public static XenRef<Task> async_start(Session session, string _vm_appliance, bool _paused)
{
return XenRef<Task>.Create(session.proxy.async_vm_appliance_start(session.uuid, (_vm_appliance != null) ? _vm_appliance : "", _paused).parse());
}
/// <summary>
/// Perform a clean shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void clean_shutdown(Session session, string _vm_appliance)
{
session.proxy.vm_appliance_clean_shutdown(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse();
}
/// <summary>
/// Perform a clean shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_clean_shutdown(Session session, string _vm_appliance)
{
return XenRef<Task>.Create(session.proxy.async_vm_appliance_clean_shutdown(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse());
}
/// <summary>
/// Perform a hard shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void hard_shutdown(Session session, string _vm_appliance)
{
session.proxy.vm_appliance_hard_shutdown(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse();
}
/// <summary>
/// Perform a hard shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_hard_shutdown(Session session, string _vm_appliance)
{
return XenRef<Task>.Create(session.proxy.async_vm_appliance_hard_shutdown(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse());
}
/// <summary>
/// For each VM in the appliance, try to shut it down cleanly. If this fails, perform a hard shutdown of the VM.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void shutdown(Session session, string _vm_appliance)
{
session.proxy.vm_appliance_shutdown(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse();
}
/// <summary>
/// For each VM in the appliance, try to shut it down cleanly. If this fails, perform a hard shutdown of the VM.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_shutdown(Session session, string _vm_appliance)
{
return XenRef<Task>.Create(session.proxy.async_vm_appliance_shutdown(session.uuid, (_vm_appliance != null) ? _vm_appliance : "").parse());
}
/// <summary>
/// Assert whether all SRs required to recover this VM appliance are available.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
public static void assert_can_be_recovered(Session session, string _vm_appliance, string _session_to)
{
session.proxy.vm_appliance_assert_can_be_recovered(session.uuid, (_vm_appliance != null) ? _vm_appliance : "", (_session_to != null) ? _session_to : "").parse();
}
/// <summary>
/// Assert whether all SRs required to recover this VM appliance are available.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
public static XenRef<Task> async_assert_can_be_recovered(Session session, string _vm_appliance, string _session_to)
{
return XenRef<Task>.Create(session.proxy.async_vm_appliance_assert_can_be_recovered(session.uuid, (_vm_appliance != null) ? _vm_appliance : "", (_session_to != null) ? _session_to : "").parse());
}
/// <summary>
/// Get the list of SRs required by the VM appliance to recover.
/// First published in XenServer 6.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the list of SRs have to be recovered .</param>
public static List<XenRef<SR>> get_SRs_required_for_recovery(Session session, string _vm_appliance, string _session_to)
{
return XenRef<SR>.Create(session.proxy.vm_appliance_get_srs_required_for_recovery(session.uuid, (_vm_appliance != null) ? _vm_appliance : "", (_session_to != null) ? _session_to : "").parse());
}
/// <summary>
/// Get the list of SRs required by the VM appliance to recover.
/// First published in XenServer 6.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the list of SRs have to be recovered .</param>
public static XenRef<Task> async_get_SRs_required_for_recovery(Session session, string _vm_appliance, string _session_to)
{
return XenRef<Task>.Create(session.proxy.async_vm_appliance_get_srs_required_for_recovery(session.uuid, (_vm_appliance != null) ? _vm_appliance : "", (_session_to != null) ? _session_to : "").parse());
}
/// <summary>
/// Recover the VM appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
/// <param name="_force">Whether the VMs should replace newer versions of themselves.</param>
public static void recover(Session session, string _vm_appliance, string _session_to, bool _force)
{
session.proxy.vm_appliance_recover(session.uuid, (_vm_appliance != null) ? _vm_appliance : "", (_session_to != null) ? _session_to : "", _force).parse();
}
/// <summary>
/// Recover the VM appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
/// <param name="_force">Whether the VMs should replace newer versions of themselves.</param>
public static XenRef<Task> async_recover(Session session, string _vm_appliance, string _session_to, bool _force)
{
return XenRef<Task>.Create(session.proxy.async_vm_appliance_recover(session.uuid, (_vm_appliance != null) ? _vm_appliance : "", (_session_to != null) ? _session_to : "", _force).parse());
}
/// <summary>
/// Return a list of all the VM_appliances known to the system.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VM_appliance>> get_all(Session session)
{
return XenRef<VM_appliance>.Create(session.proxy.vm_appliance_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the VM_appliance Records at once, in a single XML RPC call
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VM_appliance>, VM_appliance> get_all_records(Session session)
{
return XenRef<VM_appliance>.Create<Proxy_VM_appliance>(session.proxy.vm_appliance_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label;
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description;
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<vm_appliance_operation> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
Changed = true;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<vm_appliance_operation> _allowed_operations;
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, vm_appliance_operation> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
Changed = true;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, vm_appliance_operation> _current_operations;
/// <summary>
/// all VMs in this appliance
/// </summary>
public virtual List<XenRef<VM>> VMs
{
get { return _VMs; }
set
{
if (!Helper.AreEqual(value, _VMs))
{
_VMs = value;
Changed = true;
NotifyPropertyChanged("VMs");
}
}
}
private List<XenRef<VM>> _VMs;
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* 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.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;
namespace HostMe.Sdk.Model
{
/// <summary>
/// PositionMessage
/// </summary>
[DataContract]
public partial class PositionMessage : IEquatable<PositionMessage>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="PositionMessage" /> class.
/// </summary>
[JsonConstructorAttribute]
protected PositionMessage() { }
/// <summary>
/// Initializes a new instance of the <see cref="PositionMessage" /> class.
/// </summary>
/// <param name="MinPos">MinPos (required).</param>
/// <param name="MaxPos">MaxPos (required).</param>
/// <param name="MessageTemplate">MessageTemplate.</param>
public PositionMessage(int? MinPos = null, int? MaxPos = null, string MessageTemplate = null)
{
// to ensure "MinPos" is required (not null)
if (MinPos == null)
{
throw new InvalidDataException("MinPos is a required property for PositionMessage and cannot be null");
}
else
{
this.MinPos = MinPos;
}
// to ensure "MaxPos" is required (not null)
if (MaxPos == null)
{
throw new InvalidDataException("MaxPos is a required property for PositionMessage and cannot be null");
}
else
{
this.MaxPos = MaxPos;
}
this.MessageTemplate = MessageTemplate;
}
/// <summary>
/// Gets or Sets MinPos
/// </summary>
[DataMember(Name="minPos", EmitDefaultValue=true)]
public int? MinPos { get; set; }
/// <summary>
/// Gets or Sets MaxPos
/// </summary>
[DataMember(Name="maxPos", EmitDefaultValue=true)]
public int? MaxPos { get; set; }
/// <summary>
/// Gets or Sets MessageTemplate
/// </summary>
[DataMember(Name="messageTemplate", EmitDefaultValue=true)]
public string MessageTemplate { 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 PositionMessage {\n");
sb.Append(" MinPos: ").Append(MinPos).Append("\n");
sb.Append(" MaxPos: ").Append(MaxPos).Append("\n");
sb.Append(" MessageTemplate: ").Append(MessageTemplate).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 PositionMessage);
}
/// <summary>
/// Returns true if PositionMessage instances are equal
/// </summary>
/// <param name="other">Instance of PositionMessage to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PositionMessage other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.MinPos == other.MinPos ||
this.MinPos != null &&
this.MinPos.Equals(other.MinPos)
) &&
(
this.MaxPos == other.MaxPos ||
this.MaxPos != null &&
this.MaxPos.Equals(other.MaxPos)
) &&
(
this.MessageTemplate == other.MessageTemplate ||
this.MessageTemplate != null &&
this.MessageTemplate.Equals(other.MessageTemplate)
);
}
/// <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.MinPos != null)
hash = hash * 59 + this.MinPos.GetHashCode();
if (this.MaxPos != null)
hash = hash * 59 + this.MaxPos.GetHashCode();
if (this.MessageTemplate != null)
hash = hash * 59 + this.MessageTemplate.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// MinPos (int?) maximum
if(this.MinPos > (int?)2.147483647E9)
{
yield return new ValidationResult("Invalid value for MinPos, must be a value less than or equal to 2.147483647E9.", new [] { "MinPos" });
}
// MinPos (int?) minimum
if(this.MinPos < (int?)0.0)
{
yield return new ValidationResult("Invalid value for MinPos, must be a value greater than or equal to 0.0.", new [] { "MinPos" });
}
// MaxPos (int?) maximum
if(this.MaxPos > (int?)2.147483647E9)
{
yield return new ValidationResult("Invalid value for MaxPos, must be a value less than or equal to 2.147483647E9.", new [] { "MaxPos" });
}
// MaxPos (int?) minimum
if(this.MaxPos < (int?)0.0)
{
yield return new ValidationResult("Invalid value for MaxPos, must be a value greater than or equal to 0.0.", new [] { "MaxPos" });
}
yield break;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: bgs/low/pb/client/content_handle_types.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Bgs.Protocol {
/// <summary>Holder for reflection information generated from bgs/low/pb/client/content_handle_types.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class ContentHandleTypesReflection {
#region Descriptor
/// <summary>File descriptor for bgs/low/pb/client/content_handle_types.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ContentHandleTypesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CixiZ3MvbG93L3BiL2NsaWVudC9jb250ZW50X2hhbmRsZV90eXBlcy5wcm90",
"bxIMYmdzLnByb3RvY29sIk8KDUNvbnRlbnRIYW5kbGUSDgoGcmVnaW9uGAEg",
"ASgHEg0KBXVzYWdlGAIgASgHEgwKBGhhc2gYAyABKAwSEQoJcHJvdG9fdXJs",
"GAQgASgJQiUKDWJuZXQucHJvdG9jb2xCEkNvbnRlbnRIYW5kbGVQcm90b0gC",
"YgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.ContentHandle), global::Bgs.Protocol.ContentHandle.Parser, new[]{ "Region", "Usage", "Hash", "ProtoUrl" }, null, null, null)
}));
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ContentHandle : pb::IMessage<ContentHandle> {
private static readonly pb::MessageParser<ContentHandle> _parser = new pb::MessageParser<ContentHandle>(() => new ContentHandle());
public static pb::MessageParser<ContentHandle> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.ContentHandleTypesReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ContentHandle() {
OnConstruction();
}
partial void OnConstruction();
public ContentHandle(ContentHandle other) : this() {
region_ = other.region_;
usage_ = other.usage_;
hash_ = other.hash_;
protoUrl_ = other.protoUrl_;
}
public ContentHandle Clone() {
return new ContentHandle(this);
}
/// <summary>Field number for the "region" field.</summary>
public const int RegionFieldNumber = 1;
private uint region_;
public uint Region {
get { return region_; }
set {
region_ = value;
}
}
/// <summary>Field number for the "usage" field.</summary>
public const int UsageFieldNumber = 2;
private uint usage_;
public uint Usage {
get { return usage_; }
set {
usage_ = value;
}
}
/// <summary>Field number for the "hash" field.</summary>
public const int HashFieldNumber = 3;
private pb::ByteString hash_ = pb::ByteString.Empty;
public pb::ByteString Hash {
get { return hash_; }
set {
hash_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "proto_url" field.</summary>
public const int ProtoUrlFieldNumber = 4;
private string protoUrl_ = "";
public string ProtoUrl {
get { return protoUrl_; }
set {
protoUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as ContentHandle);
}
public bool Equals(ContentHandle other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Region != other.Region) return false;
if (Usage != other.Usage) return false;
if (Hash != other.Hash) return false;
if (ProtoUrl != other.ProtoUrl) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= Region.GetHashCode();
hash ^= Usage.GetHashCode();
hash ^= Hash.GetHashCode();
if (ProtoUrl.Length != 0) hash ^= ProtoUrl.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
{
output.WriteRawTag(13);
output.WriteFixed32(Region);
}
{
output.WriteRawTag(21);
output.WriteFixed32(Usage);
}
{
output.WriteRawTag(26);
output.WriteBytes(Hash);
}
if (ProtoUrl.Length != 0) {
output.WriteRawTag(34);
output.WriteString(ProtoUrl);
}
}
public int CalculateSize() {
int size = 0;
{
size += 1 + 4;
}
{
size += 1 + 4;
}
{
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Hash);
}
if (ProtoUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProtoUrl);
}
return size;
}
public void MergeFrom(ContentHandle other) {
if (other == null) {
return;
}
if (other.Region != 0) {
Region = other.Region;
}
if (other.Usage != 0) {
Usage = other.Usage;
}
if (other.Hash.Length != 0) {
Hash = other.Hash;
}
if (other.ProtoUrl.Length != 0) {
ProtoUrl = other.ProtoUrl;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 13: {
Region = input.ReadFixed32();
break;
}
case 21: {
Usage = input.ReadFixed32();
break;
}
case 26: {
Hash = input.ReadBytes();
break;
}
case 34: {
ProtoUrl = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System.Collections;
using ChainUtils.BouncyCastle.Asn1.X9;
using ChainUtils.BouncyCastle.Math;
using ChainUtils.BouncyCastle.Math.EC;
using ChainUtils.BouncyCastle.Utilities;
using ChainUtils.BouncyCastle.Utilities.Collections;
using ChainUtils.BouncyCastle.Utilities.Encoders;
namespace ChainUtils.BouncyCastle.Asn1.TeleTrust
{
/**
* elliptic curves defined in "ECC Brainpool Standard Curves and Curve Generation"
* http://www.ecc-brainpool.org/download/draft_pkix_additional_ecc_dp.txt
*/
public class TeleTrusTNamedCurves
{
private static ECCurve ConfigureCurve(ECCurve curve)
{
return curve;
}
internal class BrainpoolP160r1Holder
: X9ECParametersHolder
{
private BrainpoolP160r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP160r1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("E95E4A5F737059DC60DF5991D45029409E60FC09", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620F", 16), // q
new BigInteger("340E7BE2A280EB74E2BE61BADA745D97E8F7C300", 16), // a
new BigInteger("1E589A8595423412134FAA2DBDEC95C8D8675E58", 16), // b
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04BED5AF16EA3F6A4F62938C4631EB5AF7BDBCDBC31667CB477A1A8EC338F94741669C976316DA6321")), // G
n, h);
}
}
internal class BrainpoolP160t1Holder
: X9ECParametersHolder
{
private BrainpoolP160t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP160t1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("E95E4A5F737059DC60DF5991D45029409E60FC09", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
// new BigInteger("24DBFF5DEC9B986BBFE5295A29BFBAE45E0F5D0B", 16), // Z
new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620F", 16), // q
new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620C", 16), // a'
new BigInteger("7A556B6DAE535B7B51ED2C4D7DAA7A0B5C55F380", 16), // b'
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04B199B13B9B34EFC1397E64BAEB05ACC265FF2378ADD6718B7C7C1961F0991B842443772152C9E0AD")), // G
n, h);
}
}
internal class BrainpoolP192r1Holder
: X9ECParametersHolder
{
private BrainpoolP192r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP192r1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", 16), // q
new BigInteger("6A91174076B1E0E19C39C031FE8685C1CAE040E5C69A28EF", 16), // a
new BigInteger("469A28EF7C28CCA3DC721D044F4496BCCA7EF4146FBF25C9", 16), // b
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04C0A0647EAAB6A48753B033C56CB0F0900A2F5C4853375FD614B690866ABD5BB88B5F4828C1490002E6773FA2FA299B8F")), // G
n, h);
}
}
internal class BrainpoolP192t1Holder
: X9ECParametersHolder
{
private BrainpoolP192t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP192t1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
//new BigInteger("1B6F5CC8DB4DC7AF19458A9CB80DC2295E5EB9C3732104CB") //Z
new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", 16), // q
new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86294", 16), // a'
new BigInteger("13D56FFAEC78681E68F9DEB43B35BEC2FB68542E27897B79", 16), // b'
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("043AE9E58C82F63C30282E1FE7BBF43FA72C446AF6F4618129097E2C5667C2223A902AB5CA449D0084B7E5B3DE7CCC01C9")), // G'
n, h);
}
}
internal class BrainpoolP224r1Holder
: X9ECParametersHolder
{
private BrainpoolP224r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP224r1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", 16), // q
new BigInteger("68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43", 16), // a
new BigInteger("2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B", 16), // b
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("040D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD")), // G
n, h);
}
}
internal class BrainpoolP224t1Holder
: X9ECParametersHolder
{
private BrainpoolP224t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP224t1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
//new BigInteger("2DF271E14427A346910CF7A2E6CFA7B3F484E5C2CCE1C8B730E28B3F") //Z
new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", 16), // q
new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FC", 16), // a'
new BigInteger("4B337D934104CD7BEF271BF60CED1ED20DA14C08B3BB64F18A60888D", 16), // b'
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("046AB1E344CE25FF3896424E7FFE14762ECB49F8928AC0C76029B4D5800374E9F5143E568CD23F3F4D7C0D4B1E41C8CC0D1C6ABD5F1A46DB4C")), // G'
n, h);
}
}
internal class BrainpoolP256r1Holder
: X9ECParametersHolder
{
private BrainpoolP256r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP256r1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16), // q
new BigInteger("7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9", 16), // a
new BigInteger("26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6", 16), // b
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997")), // G
n, h);
}
}
internal class BrainpoolP256t1Holder
: X9ECParametersHolder
{
private BrainpoolP256t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP256t1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
//new BigInteger("3E2D4BD9597B58639AE7AA669CAB9837CF5CF20A2C852D10F655668DFC150EF0") //Z
new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16), // q
new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5374", 16), // a'
new BigInteger("662C61C430D84EA4FE66A7733D0B76B7BF93EBC4AF2F49256AE58101FEE92B04", 16), // b'
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04A3E8EB3CC1CFE7B7732213B23A656149AFA142C47AAFBC2B79A191562E1305F42D996C823439C56D7F7B22E14644417E69BCB6DE39D027001DABE8F35B25C9BE")), // G'
n, h);
}
}
internal class BrainpoolP320r1Holder
: X9ECParametersHolder
{
private BrainpoolP320r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP320r1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", 16), // q
new BigInteger("3EE30B568FBAB0F883CCEBD46D3F3BB8A2A73513F5EB79DA66190EB085FFA9F492F375A97D860EB4", 16), // a
new BigInteger("520883949DFDBC42D3AD198640688A6FE13F41349554B49ACC31DCCD884539816F5EB4AC8FB1F1A6", 16), // b
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("0443BD7E9AFB53D8B85289BCC48EE5BFE6F20137D10A087EB6E7871E2A10A599C710AF8D0D39E2061114FDD05545EC1CC8AB4093247F77275E0743FFED117182EAA9C77877AAAC6AC7D35245D1692E8EE1")), // G
n, h);
}
}
internal class BrainpoolP320t1Holder
: X9ECParametersHolder
{
private BrainpoolP320t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP320t1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
//new BigInteger("15F75CAF668077F7E85B42EB01F0A81FF56ECD6191D55CB82B7D861458A18FEFC3E5AB7496F3C7B1") //Z
new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", 16), // q
new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E24", 16), // a'
new BigInteger("A7F561E038EB1ED560B3D147DB782013064C19F27ED27C6780AAF77FB8A547CEB5B4FEF422340353", 16), // b'
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04925BE9FB01AFC6FB4D3E7D4990010F813408AB106C4F09CB7EE07868CC136FFF3357F624A21BED5263BA3A7A27483EBF6671DBEF7ABB30EBEE084E58A0B077AD42A5A0989D1EE71B1B9BC0455FB0D2C3")), // G'
n, h);
}
}
internal class BrainpoolP384r1Holder
: X9ECParametersHolder
{
private BrainpoolP384r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP384r1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", 16), // q
new BigInteger("7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826", 16), // a
new BigInteger("4A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11", 16), // b
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("041D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315")), // G
n, h);
}
}
internal class BrainpoolP384t1Holder
: X9ECParametersHolder
{
private BrainpoolP384t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP384t1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
//new BigInteger("41DFE8DD399331F7166A66076734A89CD0D2BCDB7D068E44E1F378F41ECBAE97D2D63DBC87BCCDDCCC5DA39E8589291C") //Z
new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", 16), // q
new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC50", 16), // a'
new BigInteger("7F519EADA7BDA81BD826DBA647910F8C4B9346ED8CCDC64E4B1ABD11756DCE1D2074AA263B88805CED70355A33B471EE", 16), // b'
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("0418DE98B02DB9A306F2AFCD7235F72A819B80AB12EBD653172476FECD462AABFFC4FF191B946A5F54D8D0AA2F418808CC25AB056962D30651A114AFD2755AD336747F93475B7A1FCA3B88F2B6A208CCFE469408584DC2B2912675BF5B9E582928")), // G'
n, h);
}
}
internal class BrainpoolP512r1Holder
: X9ECParametersHolder
{
private BrainpoolP512r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP512r1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", 16), // q
new BigInteger("7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA", 16), // a
new BigInteger("3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723", 16), // b
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("0481AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F8227DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892")), // G
n, h);
}
}
internal class BrainpoolP512t1Holder
: X9ECParametersHolder
{
private BrainpoolP512t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP512t1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", 16);
var h = new BigInteger("01", 16);
var curve = ConfigureCurve(new FpCurve(
//new BigInteger("12EE58E6764838B69782136F0F2D3BA06E27695716054092E60A80BEDB212B64E585D90BCE13761F85C3F1D2A64E3BE8FEA2220F01EBA5EEB0F35DBD29D922AB") //Z
new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", 16), // q
new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F0", 16), // a'
new BigInteger("7CBBBCF9441CFAB76E1890E46884EAE321F70C0BCB4981527897504BEC3E36A62BCDFA2304976540F6450085F2DAE145C22553B465763689180EA2571867423E", 16), // b'
n, h));
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04640ECE5C12788717B9C1BA06CBC2A6FEBA85842458C56DDE9DB1758D39C0313D82BA51735CDB3EA499AA77A7D6943A64F7A3F25FE26F06B51BAA2696FA9035DA5B534BD595F5AF0FA2C892376C84ACE1BB4E3019B71634C01131159CAE03CEE9D9932184BEEF216BD71DF2DADF86A627306ECFF96DBB8BACE198B61E00F8B332")), // G'
n, h);
}
}
private static readonly IDictionary objIds = Platform.CreateHashtable();
private static readonly IDictionary curves = Platform.CreateHashtable();
private static readonly IDictionary names = Platform.CreateHashtable();
private static void DefineCurve(
string name,
DerObjectIdentifier oid,
X9ECParametersHolder holder)
{
objIds.Add(name, oid);
names.Add(oid, name);
curves.Add(oid, holder);
}
static TeleTrusTNamedCurves()
{
DefineCurve("brainpoolp160r1", TeleTrusTObjectIdentifiers.BrainpoolP160R1, BrainpoolP160r1Holder.Instance);
DefineCurve("brainpoolp160t1", TeleTrusTObjectIdentifiers.BrainpoolP160T1, BrainpoolP160t1Holder.Instance);
DefineCurve("brainpoolp192r1", TeleTrusTObjectIdentifiers.BrainpoolP192R1, BrainpoolP192r1Holder.Instance);
DefineCurve("brainpoolp192t1", TeleTrusTObjectIdentifiers.BrainpoolP192T1, BrainpoolP192t1Holder.Instance);
DefineCurve("brainpoolp224r1", TeleTrusTObjectIdentifiers.BrainpoolP224R1, BrainpoolP224r1Holder.Instance);
DefineCurve("brainpoolp224t1", TeleTrusTObjectIdentifiers.BrainpoolP224T1, BrainpoolP224t1Holder.Instance);
DefineCurve("brainpoolp256r1", TeleTrusTObjectIdentifiers.BrainpoolP256R1, BrainpoolP256r1Holder.Instance);
DefineCurve("brainpoolp256t1", TeleTrusTObjectIdentifiers.BrainpoolP256T1, BrainpoolP256t1Holder.Instance);
DefineCurve("brainpoolp320r1", TeleTrusTObjectIdentifiers.BrainpoolP320R1, BrainpoolP320r1Holder.Instance);
DefineCurve("brainpoolp320t1", TeleTrusTObjectIdentifiers.BrainpoolP320T1, BrainpoolP320t1Holder.Instance);
DefineCurve("brainpoolp384r1", TeleTrusTObjectIdentifiers.BrainpoolP384R1, BrainpoolP384r1Holder.Instance);
DefineCurve("brainpoolp384t1", TeleTrusTObjectIdentifiers.BrainpoolP384T1, BrainpoolP384t1Holder.Instance);
DefineCurve("brainpoolp512r1", TeleTrusTObjectIdentifiers.BrainpoolP512R1, BrainpoolP512r1Holder.Instance);
DefineCurve("brainpoolp512t1", TeleTrusTObjectIdentifiers.BrainpoolP512T1, BrainpoolP512t1Holder.Instance);
}
public static X9ECParameters GetByName(
string name)
{
var oid = (DerObjectIdentifier)
objIds[Platform.ToLowerInvariant(name)];
return oid == null ? null : GetByOid(oid);
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters GetByOid(
DerObjectIdentifier oid)
{
var holder = (X9ECParametersHolder) curves[oid];
return holder == null ? null : holder.Parameters;
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DerObjectIdentifier GetOid(
string name)
{
return (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)];
}
/**
* return the named curve name represented by the given object identifier.
*/
public static string GetName(
DerObjectIdentifier oid)
{
return (string) names[oid];
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static IEnumerable Names
{
get { return new EnumerableProxy(objIds.Keys); }
}
public static DerObjectIdentifier GetOid(
short curvesize,
bool twisted)
{
return GetOid("brainpoolP" + curvesize + (twisted ? "t" : "r") + "1");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Routing
{
public class ActionEndpointFactoryTest
{
public ActionEndpointFactoryTest()
{
var serviceCollection = new ServiceCollection();
var routeOptionsSetup = new MvcCoreRouteOptionsSetup();
serviceCollection.Configure<RouteOptions>(routeOptionsSetup.Configure);
serviceCollection.AddRouting(options =>
{
options.ConstraintMap["upper-case"] = typeof(UpperCaseParameterTransform);
});
Services = serviceCollection.BuildServiceProvider();
Factory = new ActionEndpointFactory(Services.GetRequiredService<RoutePatternTransformer>(), Enumerable.Empty<IRequestDelegateFactory>());
}
internal ActionEndpointFactory Factory { get; }
internal IServiceProvider Services { get; }
[Fact]
public void AddEndpoints_ConventionalRouted_WithEmptyRouteName_CreatesMetadataWithEmptyRouteName()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values);
var route = CreateRoute(routeName: string.Empty, pattern: "{controller}/{action}");
// Act
var endpoint = CreateConventionalRoutedEndpoint(action, route);
// Assert
var routeNameMetadata = endpoint.Metadata.GetMetadata<IRouteNameMetadata>();
Assert.NotNull(routeNameMetadata);
Assert.Equal(string.Empty, routeNameMetadata.RouteName);
}
[Fact]
public void AddEndpoints_ConventionalRouted_ContainsParameterWithNullRequiredRouteValue_NoEndpointCreated()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values);
var route = CreateRoute(
routeName: "Test",
pattern: "{controller}/{action}/{page}",
defaults: new RouteValueDictionary(new { action = "TestAction" }));
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, route);
// Assert
Assert.Empty(endpoints);
}
// area, controller, action and page are special, but not hardcoded. Actions can define custom required
// route values. This has been used successfully for localization, versioning and similar schemes. We should
// be able to replace custom route values too.
[Fact]
public void AddEndpoints_ConventionalRouted_NonReservedRequiredValue_WithNoCorresponding_TemplateParameter_DoesNotProduceEndpoint()
{
// Arrange
var values = new { controller = "home", action = "index", locale = "en-NZ" };
var action = CreateActionDescriptor(values);
var route = CreateRoute(routeName: "test", pattern: "{controller}/{action}");
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, route);
// Assert
Assert.Empty(endpoints);
}
[Fact]
public void AddEndpoints_ConventionalRouted_NonReservedRequiredValue_WithCorresponding_TemplateParameter_ProducesEndpoint()
{
// Arrange
var values = new { controller = "home", action = "index", locale = "en-NZ" };
var action = CreateActionDescriptor(values);
var route = CreateRoute(routeName: "test", pattern: "{locale}/{controller}/{action}");
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, route);
// Assert
Assert.Single(endpoints);
}
[Fact]
public void AddEndpoints_ConventionalRouted_NonAreaRouteForAreaAction_DoesNotProduceEndpoint()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", area = "admin", page = (string)null };
var action = CreateActionDescriptor(values);
var route = CreateRoute(routeName: "test", pattern: "{controller}/{action}");
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, route);
// Assert
Assert.Empty(endpoints);
}
[Fact]
public void AddEndpoints_ConventionalRouted_AreaRouteForNonAreaAction_DoesNotProduceEndpoint()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", area = (string)null, page = (string)null };
var action = CreateActionDescriptor(values);
var route = CreateRoute(routeName: "test", pattern: "{area}/{controller}/{action}");
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, route);
// Assert
Assert.Empty(endpoints);
}
[Fact]
public void AddEndpoints_ConventionalRouted_RequiredValues_DoesNotMatchParameterDefaults_CreatesEndpoint()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values);
var route = CreateRoute(
routeName: "test",
pattern: "{controller}/{action}/{id?}",
defaults: new RouteValueDictionary(new { controller = "TestController", action = "TestAction1" }));
// Act
var endpoint = CreateConventionalRoutedEndpoint(action, route);
// Assert
Assert.Equal("{controller}/{action}/{id?}", endpoint.RoutePattern.RawText);
Assert.Equal("TestController", endpoint.RoutePattern.RequiredValues["controller"]);
Assert.Equal("TestAction", endpoint.RoutePattern.RequiredValues["action"]);
Assert.Equal("TestController", endpoint.RoutePattern.Defaults["controller"]);
Assert.False(endpoint.RoutePattern.Defaults.ContainsKey("action"));
}
[Fact]
public void AddEndpoints_ConventionalRouted_RequiredValues_DoesNotMatchNonParameterDefaults_DoesNotProduceEndpoint()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values);
var route = CreateRoute(
routeName: "test",
pattern: "/Blog/{*slug}",
defaults: new RouteValueDictionary(new { controller = "TestController", action = "TestAction1" }));
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, route);
// Assert
Assert.Empty(endpoints);
}
[Fact]
public void AddEndpoints_ConventionalRouted_AttributeRoutes_DefaultDifferentCaseFromRouteValue_UseDefaultCase()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values, "{controller}/{action=TESTACTION}/{id?}");
// Act
var endpoint = CreateAttributeRoutedEndpoint(action);
// Assert
Assert.Equal("{controller}/{action=TESTACTION}/{id?}", endpoint.RoutePattern.RawText);
Assert.Equal("TESTACTION", endpoint.RoutePattern.Defaults["action"]);
Assert.Equal(0, endpoint.Order);
Assert.Equal("TestAction", endpoint.RoutePattern.RequiredValues["action"]);
}
[Fact]
public void AddEndpoints_ConventionalRouted_RequiredValueWithNoCorrespondingParameter_DoesNotProduceEndpoint()
{
// Arrange
var values = new { area = "admin", controller = "home", action = "index" };
var action = CreateActionDescriptor(values);
var route = CreateRoute(routeName: "test", pattern: "{controller}/{action}");
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, route);
// Assert
Assert.Empty(endpoints);
}
[Fact]
public void AddEndpoints_AttributeRouted_ContainsParameterUsingReservedNameWithConstraint_ExceptionThrown()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values, "Products/{action:int}");
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(() => CreateAttributeRoutedEndpoint(action));
Assert.Equal(
"Failed to update the route pattern 'Products/{action:int}' with required route values. " +
"This can occur when the route pattern contains parameters with reserved names such as: 'controller', 'action', 'page' and also uses route constraints such as '{action:int}'. " +
"To fix this error, choose a different parameter name.",
exception.Message);
}
[Fact]
public void AddEndpoints_AttributeRouted_ContainsParameterWithNullRequiredRouteValue_EndpointCreated()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values, "{controller}/{action}/{page}");
// Act
var endpoint = CreateAttributeRoutedEndpoint(action);
// Assert
Assert.Equal("{controller}/{action}/{page}", endpoint.RoutePattern.RawText);
Assert.Equal("TestController", endpoint.RoutePattern.RequiredValues["controller"]);
Assert.Equal("TestAction", endpoint.RoutePattern.RequiredValues["action"]);
Assert.False(endpoint.RoutePattern.RequiredValues.ContainsKey("page"));
}
[Fact]
public void AddEndpoints_AttributeRouted_WithRouteName_EndpointCreated()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values, "{controller}/{action}/{page}");
action.AttributeRouteInfo.Name = "Test";
// Act
var endpoint = CreateAttributeRoutedEndpoint(action);
// Assert
Assert.Equal("{controller}/{action}/{page}", endpoint.RoutePattern.RawText);
Assert.Equal("TestController", endpoint.RoutePattern.RequiredValues["controller"]);
Assert.Equal("TestAction", endpoint.RoutePattern.RequiredValues["action"]);
Assert.False(endpoint.RoutePattern.RequiredValues.ContainsKey("page"));
Assert.Equal("Test", endpoint.Metadata.GetMetadata<IRouteNameMetadata>().RouteName);
Assert.Equal("Test", endpoint.Metadata.GetMetadata<IEndpointNameMetadata>().EndpointName);
}
[Fact]
public void RequestDelegateFactoryWorks()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values, "{controller}/{action}/{page}");
action.AttributeRouteInfo.Name = "Test";
RequestDelegate del = context => Task.CompletedTask;
var requestDelegateFactory = new Mock<IRequestDelegateFactory>();
requestDelegateFactory.Setup(m => m.CreateRequestDelegate(action, It.IsAny<RouteValueDictionary>())).Returns(del);
// Act
var factory = new ActionEndpointFactory(Services.GetRequiredService<RoutePatternTransformer>(), new[] { requestDelegateFactory.Object });
var endpoints = new List<Endpoint>();
factory.AddEndpoints(endpoints, new HashSet<string>(), action, Array.Empty<ConventionalRouteEntry>(), Array.Empty<Action<EndpointBuilder>>(), createInertEndpoints: false);
var endpoint = Assert.IsType<RouteEndpoint>(Assert.Single(endpoints));
// Assert
Assert.Same(del, endpoint.RequestDelegate);
}
[Fact]
public void AddEndpoints_ConventionalRouted_WithMatchingConstraint_CreatesEndpoint()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction1", page = (string)null };
var action = CreateActionDescriptor(values);
var route = CreateRoute(
routeName: "test",
pattern: "{controller}/{action}",
constraints: new RouteValueDictionary(new { action = "(TestAction1|TestAction2)" }));
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, route);
// Assert
Assert.Single(endpoints);
}
[Fact]
public void AddEndpoints_ConventionalRouted_WithNotMatchingConstraint_DoesNotCreateEndpoint()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values);
var route = CreateRoute(
routeName: "test",
pattern: "{controller}/{action}",
constraints: new RouteValueDictionary(new { action = "(TestAction1|TestAction2)" }));
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, route);
// Assert
Assert.Empty(endpoints);
}
[Fact]
public void AddEndpoints_ConventionalRouted_StaticallyDefinedOrder_IsMaintained()
{
// Arrange
var values = new { controller = "Home", action = "Index", page = (string)null };
var action = CreateActionDescriptor(values);
var routes = new[]
{
CreateRoute(routeName: "test1", pattern: "{controller}/{action}/{id?}", order: 1),
CreateRoute(routeName: "test2", pattern: "named/{controller}/{action}/{id?}", order: 2),
};
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, routes);
// Assert
Assert.Collection(
endpoints,
(ep) =>
{
var matcherEndpoint = Assert.IsType<RouteEndpoint>(ep);
Assert.Equal("{controller}/{action}/{id?}", matcherEndpoint.RoutePattern.RawText);
Assert.Equal("Index", matcherEndpoint.RoutePattern.RequiredValues["action"]);
Assert.Equal("Home", matcherEndpoint.RoutePattern.RequiredValues["controller"]);
Assert.Equal(1, matcherEndpoint.Order);
},
(ep) =>
{
var matcherEndpoint = Assert.IsType<RouteEndpoint>(ep);
Assert.Equal("named/{controller}/{action}/{id?}", matcherEndpoint.RoutePattern.RawText);
Assert.Equal("Index", matcherEndpoint.RoutePattern.RequiredValues["action"]);
Assert.Equal("Home", matcherEndpoint.RoutePattern.RequiredValues["controller"]);
Assert.Equal(2, matcherEndpoint.Order);
});
}
[Fact]
public void AddEndpoints_CreatesInertEndpoint()
{
// Arrange
var values = new { controller = "TestController", action = "TestAction", page = (string)null };
var action = CreateActionDescriptor(values);
// Act
var endpoints = CreateConventionalRoutedEndpoints(action, Array.Empty<ConventionalRouteEntry>(), createInertEndpoints: true);
// Assert
Assert.IsType<Endpoint>(Assert.Single(endpoints));
}
private RouteEndpoint CreateAttributeRoutedEndpoint(ActionDescriptor action)
{
var endpoints = new List<Endpoint>();
Factory.AddEndpoints(endpoints, new HashSet<string>(), action, Array.Empty<ConventionalRouteEntry>(), Array.Empty<Action<EndpointBuilder>>(), createInertEndpoints: false);
return Assert.IsType<RouteEndpoint>(Assert.Single(endpoints));
}
private RouteEndpoint CreateConventionalRoutedEndpoint(ActionDescriptor action, string template)
{
return CreateConventionalRoutedEndpoint(action, new ConventionalRouteEntry(routeName: null, template, null, null, null, order: 0, new List<Action<EndpointBuilder>>()));
}
private RouteEndpoint CreateConventionalRoutedEndpoint(ActionDescriptor action, ConventionalRouteEntry route)
{
Assert.NotNull(action.RouteValues);
var endpoints = new List<Endpoint>();
Factory.AddEndpoints(endpoints, new HashSet<string>(), action, new[] { route, }, Array.Empty<Action<EndpointBuilder>>(), createInertEndpoints: false);
var endpoint = Assert.IsType<RouteEndpoint>(Assert.Single(endpoints));
// This should be true for all conventional-routed actions.
AssertIsSubset(new RouteValueDictionary(action.RouteValues), endpoint.RoutePattern.RequiredValues);
return endpoint;
}
private IReadOnlyList<Endpoint> CreateConventionalRoutedEndpoints(ActionDescriptor action, ConventionalRouteEntry route)
{
return CreateConventionalRoutedEndpoints(action, new[] { route, });
}
private IReadOnlyList<Endpoint> CreateConventionalRoutedEndpoints(ActionDescriptor action, IReadOnlyList<ConventionalRouteEntry> routes, bool createInertEndpoints = false)
{
var endpoints = new List<Endpoint>();
Factory.AddEndpoints(endpoints, new HashSet<string>(), action, routes, Array.Empty<Action<EndpointBuilder>>(), createInertEndpoints);
return endpoints.ToList();
}
private ConventionalRouteEntry CreateRoute(
string routeName,
string pattern,
RouteValueDictionary defaults = null,
IDictionary<string, object> constraints = null,
RouteValueDictionary dataTokens = null,
int order = 0,
List<Action<EndpointBuilder>> conventions = null)
{
conventions ??= new List<Action<EndpointBuilder>>();
return new ConventionalRouteEntry(routeName, pattern, defaults, constraints, dataTokens, order, conventions);
}
private ActionDescriptor CreateActionDescriptor(
object requiredValues,
string pattern = null,
IList<object> metadata = null)
{
var actionDescriptor = new ActionDescriptor();
var routeValues = new RouteValueDictionary(requiredValues);
foreach (var kvp in routeValues)
{
actionDescriptor.RouteValues[kvp.Key] = kvp.Value?.ToString();
}
if (!string.IsNullOrEmpty(pattern))
{
actionDescriptor.AttributeRouteInfo = new AttributeRouteInfo
{
Name = pattern,
Template = pattern
};
}
actionDescriptor.EndpointMetadata = metadata;
return actionDescriptor;
}
private void AssertIsSubset(
IReadOnlyDictionary<string, object> subset,
IReadOnlyDictionary<string, object> fullSet)
{
foreach (var subsetPair in subset)
{
var isPresent = fullSet.TryGetValue(subsetPair.Key, out var fullSetPairValue);
Assert.True(isPresent);
Assert.Equal(subsetPair.Value, fullSetPairValue);
}
}
private void AssertMatchingSuppressed(Endpoint endpoint, bool suppressed)
{
var isEndpointSuppressed = endpoint.Metadata.GetMetadata<ISuppressMatchingMetadata>()?.SuppressMatching ?? false;
Assert.Equal(suppressed, isEndpointSuppressed);
}
private class UpperCaseParameterTransform : IOutboundParameterTransformer
{
public string TransformOutbound(object value)
{
return value?.ToString().ToUpperInvariant();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DowUtils;
namespace Factotum
{
public partial class CalBlockEdit : Form, IEntityEditForm
{
private ECalBlock curCalBlock;
private CalBlockType[] calBlockTypes;
private CalBlockMaterial[] calBlockMaterials;
private EKitCollection kits;
// Allow the calling form to access the entity
public IEntity Entity
{
get { return curCalBlock; }
}
//---------------------------------------------------------
// Initialization
//---------------------------------------------------------
// If you are creating a new record, the ID should be null
// Normally in this case, you will want to provide a parentID
public CalBlockEdit()
: this(null){}
public CalBlockEdit(Guid? ID)
{
InitializeComponent();
curCalBlock = new ECalBlock();
curCalBlock.Load(ID);
InitializeControls(ID == null);
}
// Initialize the form control values
private void InitializeControls(bool newRecord)
{
kits = EKit.ListByName(true);
cboKit.DataSource = kits;
cboKit.DisplayMember = "ToolKitName";
cboKit.ValueMember = "ID";
calBlockMaterials = ECalBlock.GetCalBlockMaterialsArray();
cboMaterialType.DataSource = calBlockMaterials;
cboMaterialType.DisplayMember = "Name";
cboMaterialType.ValueMember = "ID";
calBlockTypes = ECalBlock.GetCalBlockTypesArray();
cboType.DataSource = calBlockTypes;
cboType.DisplayMember = "Name";
cboType.ValueMember = "ID";
SetControlValues();
this.Text = newRecord ? "New Calibration Block" : "Edit Calibration Block";
EKit.Changed += new EventHandler<EntityChangedEventArgs>(EKit_Changed);
}
//---------------------------------------------------------
// Event Handlers
//---------------------------------------------------------
void EKit_Changed(object sender, EntityChangedEventArgs e)
{
Guid? currentValue = (Guid?)cboKit.SelectedValue;
kits = EKit.ListByName(true);
cboKit.DataSource = kits;
if (currentValue == null)
cboKit.SelectedIndex = 0;
else
cboKit.SelectedValue = currentValue;
}
// If the user cancels out, just close.
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
DialogResult = DialogResult.Cancel;
}
// If the user clicks OK, first validate and set the error text
// for any controls with invalid values.
// If it validates, try to save.
private void btnOK_Click(object sender, EventArgs e)
{
SaveAndClose();
}
// Each time the text changes, check to make sure its length is ok
// If not, set the error.
private void txtName_TextChanged(object sender, EventArgs e)
{
// Calling this method sets the ErrMsg property of the Object.
curCalBlock.CalBlockSerialNumberLengthOk(txtName.Text);
errorProvider1.SetError(txtName, curCalBlock.CalBlockSerialNumberErrMsg);
}
private void txtMin_TextChanged(object sender, EventArgs e)
{
curCalBlock.CalBlockCalMinLengthOk(txtMin.Text);
errorProvider1.SetError(txtMin, curCalBlock.CalBlockCalMinErrMsg);
}
private void txtMax_TextChanged(object sender, EventArgs e)
{
curCalBlock.CalBlockCalMaxLengthOk(txtMax.Text);
errorProvider1.SetError(txtMax, curCalBlock.CalBlockCalMaxErrMsg);
}
// The validating event gets called when the user leaves the control.
// We handle it to perform all validation for the value.
private void txtName_Validating(object sender, CancelEventArgs e)
{
// Calling this function will set the ErrMsg property of the object.
curCalBlock.CalBlockSerialNumberValid(txtName.Text);
errorProvider1.SetError(txtName, curCalBlock.CalBlockSerialNumberErrMsg);
}
private void txtMin_Validating(object sender, CancelEventArgs e)
{
curCalBlock.CalBlockCalMinValid(txtMin.Text);
errorProvider1.SetError(txtMin, curCalBlock.CalBlockCalMinErrMsg);
}
private void txtMax_Validating(object sender, CancelEventArgs e)
{
curCalBlock.CalBlockCalMaxValid(txtMax.Text);
errorProvider1.SetError(txtMax, curCalBlock.CalBlockCalMaxErrMsg);
}
// Handle the user clicking the "Is Active" checkbox
private void ckActive_Click(object sender, EventArgs e)
{
string msg = ckActive.Checked ?
"A Calibration Block should only be Activated if it has returned to service. Continue?" :
"A Calibration Block should only be Inactivated if it is out of service. Continue?";
DialogResult r = MessageBox.Show(msg, "Factotum: Confirm Calibration Block Status Change", MessageBoxButtons.YesNo);
if (r == DialogResult.No) ckActive.Checked = !ckActive.Checked;
}
//---------------------------------------------------------
// Helper functions
//---------------------------------------------------------
// No prompting is performed. The user should understand the meanings of OK and Cancel.
private void SaveAndClose()
{
if (AnyControlErrors()) return;
// Set the entity values to match the form values
UpdateRecord();
// Try to validate
if (!curCalBlock.Valid())
{
setAllErrors();
return;
}
// The Save function returns a the Guid? of the record created or updated.
Guid? tmpID = curCalBlock.Save();
if (tmpID != null)
{
Close();
DialogResult = DialogResult.OK;
}
}
// Set the form controls to the site object values.
private void SetControlValues()
{
txtName.Text = curCalBlock.CalBlockSerialNumber;
txtMax.Text = Util.GetFormattedDecimal(curCalBlock.CalBlockCalMax);
txtMin.Text = Util.GetFormattedDecimal(curCalBlock.CalBlockCalMin);
if (curCalBlock.CalBlockKitID != null) cboKit.SelectedValue = curCalBlock.CalBlockKitID;
if (curCalBlock.CalBlockMaterialType != null) cboMaterialType.SelectedValue = curCalBlock.CalBlockMaterialType;
if (curCalBlock.CalBlockType != null) cboType.SelectedValue = curCalBlock.CalBlockType;
ckActive.Checked = curCalBlock.CalBlockIsActive;
}
// Set the error provider text for all controls that use it.
private void setAllErrors()
{
errorProvider1.SetError(txtName, curCalBlock.CalBlockSerialNumberErrMsg);
errorProvider1.SetError(txtMax, curCalBlock.CalBlockCalMaxErrMsg);
errorProvider1.SetError(txtMin, curCalBlock.CalBlockCalMinErrMsg);
}
// Check all controls to see if any have errors.
private bool AnyControlErrors()
{
return (errorProvider1.GetError(txtName).Length > 0 ||
errorProvider1.GetError(txtMax).Length > 0 ||
errorProvider1.GetError(txtMin).Length > 0);
}
// Update the object values from the form control values.
private void UpdateRecord()
{
curCalBlock.CalBlockSerialNumber = txtName.Text;
curCalBlock.CalBlockCalMax = Util.GetNullableDecimalForString(txtMax.Text);
curCalBlock.CalBlockCalMin = Util.GetNullableDecimalForString(txtMin.Text);
curCalBlock.CalBlockSerialNumber = txtName.Text;
curCalBlock.CalBlockKitID = (Guid?)cboKit.SelectedValue;
curCalBlock.CalBlockMaterialType = (byte?)cboMaterialType.SelectedValue;
curCalBlock.CalBlockType = (byte?)cboType.SelectedValue;
curCalBlock.CalBlockIsActive = ckActive.Checked;
}
}
}
| |
/*
Copyright 2019 Esri
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.Text;
using ESRI.ArcGIS.esriSystem;
//FILE AUTOMATICALLY GENERATED BY ESRI LICENSE INITIALIZATION ADDIN
//YOU SHOULD NOT NORMALLY EDIT OR REMOVE THIS FILE FROM THE PROJECT
namespace DemoITableBinding
{
internal sealed class LicenseInitializer
{
private IAoInitialize m_AoInit = new AoInitializeClass();
#region Private members
private const string MessageNoLicensesRequested = "Product: No licenses were requested";
private const string MessageProductAvailable = "Product: {0}: Available";
private const string MessageProductNotLicensed = "Product: {0}: Not Licensed";
private const string MessageExtensionAvailable = " Extension: {0}: Available";
private const string MessageExtensionNotLicensed = " Extension: {0}: Not Licensed";
private const string MessageExtensionFailed = " Extension: {0}: Failed";
private const string MessageExtensionUnavailable = " Extension: {0}: Unavailable";
private bool m_hasShutDown = false;
private bool m_hasInitializeProduct = false;
private List<int> m_requestedProducts;
private List<esriLicenseExtensionCode> m_requestedExtensions;
private Dictionary<esriLicenseProductCode, esriLicenseStatus> m_productStatus = new Dictionary<esriLicenseProductCode, esriLicenseStatus>();
private Dictionary<esriLicenseExtensionCode, esriLicenseStatus> m_extensionStatus = new Dictionary<esriLicenseExtensionCode, esriLicenseStatus>();
private bool m_productCheckOrdering = true; //default from low to high
#endregion
public bool InitializeApplication(esriLicenseProductCode[] productCodes, esriLicenseExtensionCode[] extensionLics)
{
//Cache product codes by enum int so can be sorted without custom sorter
m_requestedProducts = new List<int>();
foreach (esriLicenseProductCode code in productCodes)
{
int requestCodeNum = Convert.ToInt32(code);
if (!m_requestedProducts.Contains(requestCodeNum))
{
m_requestedProducts.Add(requestCodeNum);
}
}
AddExtensions(extensionLics);
return Initialize();
}
/// <summary>
/// A summary of the status of product and extensions initialization.
/// </summary>
public string LicenseMessage()
{
string prodStatus = string.Empty;
if (m_productStatus == null || m_productStatus.Count == 0)
{
prodStatus = MessageNoLicensesRequested + Environment.NewLine;
}
else if (m_productStatus.ContainsValue(esriLicenseStatus.esriLicenseAlreadyInitialized)
|| m_productStatus.ContainsValue(esriLicenseStatus.esriLicenseCheckedOut))
{
prodStatus = ReportInformation(m_AoInit as ILicenseInformation,
m_AoInit.InitializedProduct(),
esriLicenseStatus.esriLicenseCheckedOut) + Environment.NewLine;
}
else
{
//Failed...
foreach (KeyValuePair<esriLicenseProductCode, esriLicenseStatus> item in m_productStatus)
{
prodStatus += ReportInformation(m_AoInit as ILicenseInformation,
item.Key, item.Value) + Environment.NewLine;
}
}
string extStatus = string.Empty;
foreach (KeyValuePair<esriLicenseExtensionCode, esriLicenseStatus> item in m_extensionStatus)
{
string info = ReportInformation(m_AoInit as ILicenseInformation, item.Key, item.Value);
if (!string.IsNullOrEmpty(info))
extStatus += info + Environment.NewLine;
}
string status = prodStatus + extStatus;
return status.Trim();
}
/// <summary>
/// Shuts down AoInitialize object and check back in extensions to ensure
/// any ESRI libraries that have been used are unloaded in the correct order.
/// </summary>
/// <remarks>Once Shutdown has been called, you cannot re-initialize the product license
/// and should not make any ArcObjects call.</remarks>
public void ShutdownApplication()
{
if (m_hasShutDown)
return;
//Check back in extensions
foreach (KeyValuePair<esriLicenseExtensionCode, esriLicenseStatus> item in m_extensionStatus)
{
if (item.Value == esriLicenseStatus.esriLicenseCheckedOut)
m_AoInit.CheckInExtension(item.Key);
}
m_requestedProducts.Clear();
m_requestedExtensions.Clear();
m_extensionStatus.Clear();
m_productStatus.Clear();
m_AoInit.Shutdown();
m_hasShutDown = true;
//m_hasInitializeProduct = false;
}
/// <summary>
/// Indicates if the extension is currently checked out.
/// </summary>
public bool IsExtensionCheckedOut(esriLicenseExtensionCode code)
{
return m_AoInit.IsExtensionCheckedOut(code);
}
/// <summary>
/// Set the extension(s) to be checked out for your ArcObjects code.
/// </summary>
public bool AddExtensions(params esriLicenseExtensionCode[] requestCodes)
{
if (m_requestedExtensions == null)
m_requestedExtensions = new List<esriLicenseExtensionCode>();
foreach (esriLicenseExtensionCode code in requestCodes)
{
if (!m_requestedExtensions.Contains(code))
m_requestedExtensions.Add(code);
}
if (m_hasInitializeProduct)
return CheckOutLicenses(this.InitializedProduct);
return false;
}
/// <summary>
/// Check in extension(s) when it is no longer needed.
/// </summary>
public void RemoveExtensions(params esriLicenseExtensionCode[] requestCodes)
{
if (m_extensionStatus == null || m_extensionStatus.Count == 0)
return;
foreach (esriLicenseExtensionCode code in requestCodes)
{
if (m_extensionStatus.ContainsKey(code))
{
if (m_AoInit.CheckInExtension(code) == esriLicenseStatus.esriLicenseCheckedIn)
{
m_extensionStatus[code] = esriLicenseStatus.esriLicenseCheckedIn;
}
}
}
}
/// <summary>
/// Get/Set the ordering of product code checking. If true, check from lowest to
/// highest license. True by default.
/// </summary>
public bool InitializeLowerProductFirst
{
get
{
return m_productCheckOrdering;
}
set
{
m_productCheckOrdering = value;
}
}
/// <summary>
/// Retrieves the product code initialized in the ArcObjects application
/// </summary>
public esriLicenseProductCode InitializedProduct
{
get
{
try
{
return m_AoInit.InitializedProduct();
}
catch
{
return 0;
}
}
}
#region Helper methods
private bool Initialize()
{
if (m_requestedProducts == null || m_requestedProducts.Count == 0)
return false;
esriLicenseProductCode currentProduct = new esriLicenseProductCode();
bool productInitialized = false;
//Try to initialize a product
ILicenseInformation licInfo = (ILicenseInformation)m_AoInit;
m_requestedProducts.Sort();
if (!InitializeLowerProductFirst) //Request license from highest to lowest
m_requestedProducts.Reverse();
foreach (int prodNumber in m_requestedProducts)
{
esriLicenseProductCode prod = (esriLicenseProductCode)Enum.ToObject(typeof(esriLicenseProductCode), prodNumber);
esriLicenseStatus status = m_AoInit.IsProductCodeAvailable(prod);
if (status == esriLicenseStatus.esriLicenseAvailable)
{
status = m_AoInit.Initialize(prod);
if (status == esriLicenseStatus.esriLicenseAlreadyInitialized ||
status == esriLicenseStatus.esriLicenseCheckedOut)
{
productInitialized = true;
currentProduct = m_AoInit.InitializedProduct();
}
}
m_productStatus.Add(prod, status);
if (productInitialized)
break;
}
m_hasInitializeProduct = productInitialized;
m_requestedProducts.Clear();
//No product is initialized after trying all requested licenses, quit
if (!productInitialized)
{
return false;
}
//Check out extension licenses
return CheckOutLicenses(currentProduct);
}
private bool CheckOutLicenses(esriLicenseProductCode currentProduct)
{
bool allSuccessful = true;
//Request extensions
if (m_requestedExtensions != null && currentProduct != 0)
{
foreach (esriLicenseExtensionCode ext in m_requestedExtensions)
{
esriLicenseStatus licenseStatus = m_AoInit.IsExtensionCodeAvailable(currentProduct, ext);
if (licenseStatus == esriLicenseStatus.esriLicenseAvailable)//skip unavailable extensions
{
licenseStatus = m_AoInit.CheckOutExtension(ext);
}
allSuccessful = (allSuccessful && licenseStatus == esriLicenseStatus.esriLicenseCheckedOut);
if (m_extensionStatus.ContainsKey(ext))
m_extensionStatus[ext] = licenseStatus;
else
m_extensionStatus.Add(ext, licenseStatus);
}
m_requestedExtensions.Clear();
}
return allSuccessful;
}
private string ReportInformation(ILicenseInformation licInfo,
esriLicenseProductCode code, esriLicenseStatus status)
{
string prodName = string.Empty;
try
{
prodName = licInfo.GetLicenseProductName(code);
}
catch
{
prodName = code.ToString();
}
string statusInfo = string.Empty;
switch (status)
{
case esriLicenseStatus.esriLicenseAlreadyInitialized:
case esriLicenseStatus.esriLicenseCheckedOut:
statusInfo = string.Format(MessageProductAvailable, prodName);
break;
default:
statusInfo = string.Format(MessageProductNotLicensed, prodName);
break;
}
return statusInfo;
}
private string ReportInformation(ILicenseInformation licInfo,
esriLicenseExtensionCode code, esriLicenseStatus status)
{
string extensionName = string.Empty;
try
{
extensionName = licInfo.GetLicenseExtensionName(code);
}
catch
{
extensionName = code.ToString();
}
string statusInfo = string.Empty;
switch (status)
{
case esriLicenseStatus.esriLicenseAlreadyInitialized:
case esriLicenseStatus.esriLicenseCheckedOut:
statusInfo = string.Format(MessageExtensionAvailable, extensionName);
break;
case esriLicenseStatus.esriLicenseCheckedIn:
break;
case esriLicenseStatus.esriLicenseUnavailable:
statusInfo = string.Format(MessageExtensionUnavailable, extensionName);
break;
case esriLicenseStatus.esriLicenseFailure:
statusInfo = string.Format(MessageExtensionFailed, extensionName);
break;
default:
statusInfo = string.Format(MessageExtensionNotLicensed, extensionName);
break;
}
return statusInfo;
}
#endregion
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
// Taken from Asset Store: https://www.assetstore.unity3d.com/en/#!/content/7747
public class KinectManager : MonoBehaviour
{
public enum Smoothing : int { None, Default, Medium, Aggressive }
// Public Bool to determine how many players there are. Default of one user.
public bool TwoUsers = false;
// // Public Bool to determine if the sensor is used in near mode.
// public bool NearMode = false;
// Public Bool to determine whether to receive and compute the user map
public bool ComputeUserMap = false;
// Public Bool to determine whether to receive and compute the color map
public bool ComputeColorMap = false;
public float DisplayMapsWidthPercent = 20f;
// How high off the ground is the sensor (in meters).
public float SensorHeight = 1.0f;
// Kinect elevation angle (in degrees)
public int SensorAngle = 0;
// Minimum user distance in order to process skeleton data
public float MinUserDistance = 1.0f;
// Maximum user distance, if any. 0 means no max-distance limitation
public float MaxUserDistance = 0f;
// Public Bool to determine whether to detect only the closest user or not
public bool DetectClosestUser = true;
// Public Bool to determine whether to use only the tracked joints (and ignore the inferred ones)
public bool IgnoreInferredJoints = true;
// Selection of smoothing parameters
public Smoothing smoothing = Smoothing.Default;
// Bool to keep track of whether Kinect has been initialized
private bool _kinectInitialized = false;
// Bools to keep track of who is currently calibrated.
private bool _player1Calibrated = false;
private bool _player2Calibrated = false;
private bool _allPlayersCalibrated = false;
// Values to track which ID (assigned by the Kinect) is player 1 and player 2.
private uint _player1Id;
private uint _player2Id;
private int _player1Index;
private int _player2Index;
// User Map vars.
private Texture2D _usersLblTex;
private Color32[] _usersMapColors;
private ushort[] _usersPrevState;
private Rect _usersMapRect;
private int _usersMapSize;
private Texture2D _usersClrTex;
//Color[] usersClrColors;
private Rect _usersClrRect;
//short[] usersLabelMap;
private ushort[] _usersDepthMap;
private float[] _usersHistogramMap;
// List of all users
private List<uint> _allUsers;
// Image stream handles for the kinect
private IntPtr _colorStreamHandle;
private IntPtr _depthStreamHandle;
// Color image data, if used
private Color32[] _colorImage;
private byte[] _usersColorMap;
// Skeleton related structures
private KinectWrapper.NuiSkeletonFrame _skeletonFrame;
private KinectWrapper.NuiTransformSmoothParameters _smoothParameters;
private int _player1SkeletonIndex;
private int _player2SkeletonIndex;
// Skeleton tracking states, positions and joints' orientations
private Vector3 _player1Pos, _player2Pos;
private Matrix4x4 _player1Ori, _player2Ori;
private bool[] _player1JointsTracked, _player2JointsTracked;
private bool[] _player1PrevTracked, _player2PrevTracked;
private Vector3[] _player1JointsPos, _player2JointsPos;
private Matrix4x4[] _player1JointsOri, _player2JointsOri;
private KinectWrapper.NuiSkeletonBoneOrientation[] _jointOrientations;
private Matrix4x4 _kinectToWorld, _flipMatrix;
// Timer for controlling Filter Lerp blends.
private float _lastNuiTime;
// returns the single KinectManager instance
public static KinectManager Instance { get; private set; }
// checks if Kinect is initialized and ready to use. If not, there was an error during Kinect-sensor initialization
public static bool IsKinectInitialized()
{
return Instance != null && Instance._kinectInitialized;
}
// checks if Kinect is initialized and ready to use. If not, there was an error during Kinect-sensor initialization
public bool IsInitialized()
{
return _kinectInitialized;
}
// this function is used internally by AvatarController
public static bool IsCalibrationNeeded()
{
return false;
}
// returns the raw depth/user data, if ComputeUserMap is true
public ushort[] GetRawDepthMap()
{
return _usersDepthMap;
}
// returns the depth data for a specific pixel, if ComputeUserMap is true
public ushort GetDepthForPixel(int x, int y)
{
var index = y * KinectWrapper.Constants.DepthImageWidth + x;
if(index >= 0 && index < _usersDepthMap.Length) return _usersDepthMap[index];
return 0;
}
// returns the depth map position for a 3d joint position
public Vector2 GetDepthMapPosForJointPos(Vector3 posJoint)
{
var vDepthPos = KinectWrapper.MapSkeletonPointToDepthPoint(posJoint);
var vMapPos = new Vector2(vDepthPos.x, vDepthPos.y);
return vMapPos;
}
// returns the color map position for a depth 2d position
public Vector2 GetColorMapPosForDepthPos(Vector2 posDepth)
{
int cx, cy;
KinectWrapper.NuiImageViewArea pcViewArea = new KinectWrapper.NuiImageViewArea
{
eDigitalZoom = 0,
lCenterX = 0,
lCenterY = 0
};
KinectWrapper.NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution(
KinectWrapper.Constants.ColorImageResolution,
KinectWrapper.Constants.DepthImageResolution,
ref pcViewArea,
(int)posDepth.x, (int)posDepth.y, GetDepthForPixel((int)posDepth.x, (int)posDepth.y),
out cx, out cy);
return new Vector2(cx, cy);
}
// returns the depth image/users histogram texture,if ComputeUserMap is true
public Texture2D GetUsersLblTex()
{
return _usersLblTex;
}
// returns the color image texture,if ComputeColorMap is true
public Texture2D GetUsersClrTex()
{
return _usersClrTex;
}
// returns true if at least one user is currently detected by the sensor
public bool IsUserDetected()
{
return _kinectInitialized && (_allUsers.Count > 0);
}
// returns the UserID of Player1, or 0 if no Player1 is detected
public uint GetPlayer1ID()
{
return _player1Id;
}
// returns the UserID of Player2, or 0 if no Player2 is detected
public uint GetPlayer2ID()
{
return _player2Id;
}
// returns the index of Player1, or 0 if no Player2 is detected
public int GetPlayer1Index()
{
return _player1Index;
}
// returns the index of Player2, or 0 if no Player2 is detected
public int GetPlayer2Index()
{
return _player2Index;
}
// returns true if the User is calibrated and ready to use
public bool IsPlayerCalibrated(uint UserId)
{
if(UserId == _player1Id) return _player1Calibrated;
if(UserId == _player2Id) return _player2Calibrated;
return false;
}
// returns the raw unmodified joint position, as returned by the Kinect sensor
public Vector3 GetRawSkeletonJointPos(uint UserId, int joint)
{
if(UserId == _player1Id)
return joint >= 0 && joint < _player1JointsPos.Length ? (Vector3)_skeletonFrame.SkeletonData[_player1SkeletonIndex].SkeletonPositions[joint] : Vector3.zero;
else if(UserId == _player2Id)
return joint >= 0 && joint < _player2JointsPos.Length ? (Vector3)_skeletonFrame.SkeletonData[_player2SkeletonIndex].SkeletonPositions[joint] : Vector3.zero;
return Vector3.zero;
}
// returns the User position, relative to the Kinect-sensor, in meters
public Vector3 GetUserPosition(uint UserId)
{
if(UserId == _player1Id)
return _player1Pos;
else if(UserId == _player2Id)
return _player2Pos;
return Vector3.zero;
}
// returns the User rotation, relative to the Kinect-sensor
public Quaternion GetUserOrientation(uint UserId, bool flip)
{
if(UserId == _player1Id && _player1JointsTracked[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter])
return ConvertMatrixToQuat(_player1Ori, (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter, flip);
else if(UserId == _player2Id && _player2JointsTracked[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter])
return ConvertMatrixToQuat(_player2Ori, (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter, flip);
return Quaternion.identity;
}
// returns true if the given joint of the specified user is being tracked
public bool IsJointTracked(uint UserId, int joint)
{
if(UserId == _player1Id)
return joint >= 0 && joint < _player1JointsTracked.Length ? _player1JointsTracked[joint] : false;
else if(UserId == _player2Id)
return joint >= 0 && joint < _player2JointsTracked.Length ? _player2JointsTracked[joint] : false;
return false;
}
// returns the joint position of the specified user, relative to the Kinect-sensor, in meters
public Vector3 GetJointPosition(uint UserId, int joint)
{
if(UserId == _player1Id)
return joint >= 0 && joint < _player1JointsPos.Length ? _player1JointsPos[joint] : Vector3.zero;
else if(UserId == _player2Id)
return joint >= 0 && joint < _player2JointsPos.Length ? _player2JointsPos[joint] : Vector3.zero;
return Vector3.zero;
}
// returns the local joint position of the specified user, relative to the parent joint, in meters
public Vector3 GetJointLocalPosition(uint UserId, int joint)
{
int parent = KinectWrapper.GetSkeletonJointParent(joint);
if(UserId == _player1Id)
return joint >= 0 && joint < _player1JointsPos.Length ?
(_player1JointsPos[joint] - _player1JointsPos[parent]) : Vector3.zero;
else if(UserId == _player2Id)
return joint >= 0 && joint < _player2JointsPos.Length ?
(_player2JointsPos[joint] - _player2JointsPos[parent]) : Vector3.zero;
return Vector3.zero;
}
// returns the joint rotation of the specified user, relative to the Kinect-sensor
public Quaternion GetJointOrientation(uint UserId, int joint, bool flip)
{
if(UserId == _player1Id)
{
if(joint >= 0 && joint < _player1JointsOri.Length && _player1JointsTracked[joint])
return ConvertMatrixToQuat(_player1JointsOri[joint], joint, flip);
}
else if(UserId == _player2Id)
{
if(joint >= 0 && joint < _player2JointsOri.Length && _player2JointsTracked[joint])
return ConvertMatrixToQuat(_player2JointsOri[joint], joint, flip);
}
return Quaternion.identity;
}
// returns the joint rotation of the specified user, relative to the parent joint
public Quaternion GetJointLocalOrientation(uint UserId, int joint, bool flip)
{
int parent = KinectWrapper.GetSkeletonJointParent(joint);
if(UserId == _player1Id)
{
if(joint >= 0 && joint < _player1JointsOri.Length && _player1JointsTracked[joint])
{
Matrix4x4 localMat = (_player1JointsOri[parent].inverse * _player1JointsOri[joint]);
return Quaternion.LookRotation(localMat.GetColumn(2), localMat.GetColumn(1));
}
}
else if(UserId == _player2Id)
{
if(joint >= 0 && joint < _player2JointsOri.Length && _player2JointsTracked[joint])
{
Matrix4x4 localMat = (_player2JointsOri[parent].inverse * _player2JointsOri[joint]);
return Quaternion.LookRotation(localMat.GetColumn(2), localMat.GetColumn(1));
}
}
return Quaternion.identity;
}
// returns the direction between baseJoint and nextJoint, for the specified user
public Vector3 GetDirectionBetweenJoints(uint UserId, int baseJoint, int nextJoint, bool flipX, bool flipZ)
{
Vector3 jointDir = Vector3.zero;
if(UserId == _player1Id)
{
if(baseJoint >= 0 && baseJoint < _player1JointsPos.Length && _player1JointsTracked[baseJoint] &&
nextJoint >= 0 && nextJoint < _player1JointsPos.Length && _player1JointsTracked[nextJoint])
{
jointDir = _player1JointsPos[nextJoint] - _player1JointsPos[baseJoint];
}
}
else if(UserId == _player2Id)
{
if(baseJoint >= 0 && baseJoint < _player2JointsPos.Length && _player2JointsTracked[baseJoint] &&
nextJoint >= 0 && nextJoint < _player2JointsPos.Length && _player2JointsTracked[nextJoint])
{
jointDir = _player2JointsPos[nextJoint] - _player2JointsPos[baseJoint];
}
}
if(jointDir != Vector3.zero)
{
if(flipX)
jointDir.x = -jointDir.x;
if(flipZ)
jointDir.z = -jointDir.z;
}
return jointDir;
}
// removes the currently detected kinect users, allowing a new detection/calibration process to start
public void ClearKinectUsers()
{
if(!_kinectInitialized)
return;
// remove current users
for(int i = _allUsers.Count - 1; i >= 0; i--)
{
uint userId = _allUsers[i];
RemoveUser(userId);
}
ResetFilters();
}
// clears Kinect buffers and resets the filters
public void ResetFilters()
{
if(!_kinectInitialized)
return;
// clear kinect vars
_player1Pos = Vector3.zero; _player2Pos = Vector3.zero;
_player1Ori = Matrix4x4.identity; _player2Ori = Matrix4x4.identity;
int skeletonJointsCount = (int)KinectWrapper.NuiSkeletonPositionIndex.Count;
for(int i = 0; i < skeletonJointsCount; i++)
{
_player1JointsTracked[i] = false; _player2JointsTracked[i] = false;
_player1PrevTracked[i] = false; _player2PrevTracked[i] = false;
_player1JointsPos[i] = Vector3.zero; _player2JointsPos[i] = Vector3.zero;
_player1JointsOri[i] = Matrix4x4.identity; _player2JointsOri[i] = Matrix4x4.identity;
}
}
//----------------------------------- end of public functions --------------------------------------//
void Start()
{
//CalibrationText = GameObject.Find("CalibrationText");
int hr = 0;
try
{
hr = KinectWrapper.NuiInitialize(KinectWrapper.NuiInitializeFlags.UsesSkeleton |
KinectWrapper.NuiInitializeFlags.UsesDepthAndPlayerIndex |
(ComputeColorMap ? KinectWrapper.NuiInitializeFlags.UsesColor : 0));
if (hr != 0)
{
throw new Exception("NuiInitialize Failed");
}
hr = KinectWrapper.NuiSkeletonTrackingEnable(IntPtr.Zero, 8); // 0, 12,8
if (hr != 0)
{
throw new Exception("Cannot initialize Skeleton Data");
}
_depthStreamHandle = IntPtr.Zero;
if(ComputeUserMap)
{
hr = KinectWrapper.NuiImageStreamOpen(KinectWrapper.NuiImageType.DepthAndPlayerIndex,
KinectWrapper.Constants.DepthImageResolution, 0, 2, IntPtr.Zero, ref _depthStreamHandle);
if (hr != 0)
{
throw new Exception("Cannot open depth stream");
}
}
_colorStreamHandle = IntPtr.Zero;
if(ComputeColorMap)
{
hr = KinectWrapper.NuiImageStreamOpen(KinectWrapper.NuiImageType.Color,
KinectWrapper.Constants.ColorImageResolution, 0, 2, IntPtr.Zero, ref _colorStreamHandle);
if (hr != 0)
{
throw new Exception("Cannot open color stream");
}
}
// set kinect elevation angle
KinectWrapper.NuiCameraElevationSetAngle(SensorAngle);
// init skeleton structures
_skeletonFrame = new KinectWrapper.NuiSkeletonFrame()
{
SkeletonData = new KinectWrapper.NuiSkeletonData[KinectWrapper.Constants.NuiSkeletonCount]
};
// values used to pass to smoothing function
_smoothParameters = new KinectWrapper.NuiTransformSmoothParameters();
switch(smoothing)
{
case Smoothing.Default:
_smoothParameters.fSmoothing = 0.5f;
_smoothParameters.fCorrection = 0.5f;
_smoothParameters.fPrediction = 0.5f;
_smoothParameters.fJitterRadius = 0.05f;
_smoothParameters.fMaxDeviationRadius = 0.04f;
break;
case Smoothing.Medium:
_smoothParameters.fSmoothing = 0.5f;
_smoothParameters.fCorrection = 0.1f;
_smoothParameters.fPrediction = 0.5f;
_smoothParameters.fJitterRadius = 0.1f;
_smoothParameters.fMaxDeviationRadius = 0.1f;
break;
case Smoothing.Aggressive:
_smoothParameters.fSmoothing = 0.7f;
_smoothParameters.fCorrection = 0.3f;
_smoothParameters.fPrediction = 1.0f;
_smoothParameters.fJitterRadius = 1.0f;
_smoothParameters.fMaxDeviationRadius = 1.0f;
break;
}
// create arrays for joint positions and joint orientations
int skeletonJointsCount = (int)KinectWrapper.NuiSkeletonPositionIndex.Count;
_player1JointsTracked = new bool[skeletonJointsCount];
_player2JointsTracked = new bool[skeletonJointsCount];
_player1PrevTracked = new bool[skeletonJointsCount];
_player2PrevTracked = new bool[skeletonJointsCount];
_player1JointsPos = new Vector3[skeletonJointsCount];
_player2JointsPos = new Vector3[skeletonJointsCount];
_player1JointsOri = new Matrix4x4[skeletonJointsCount];
_player2JointsOri = new Matrix4x4[skeletonJointsCount];
//create the transform matrix that converts from kinect-space to world-space
Quaternion quatTiltAngle = new Quaternion();
quatTiltAngle.eulerAngles = new Vector3(-SensorAngle, 0.0f, 0.0f);
// transform matrix - kinect to world
_kinectToWorld.SetTRS(new Vector3(0.0f, SensorHeight, 0.0f), quatTiltAngle, Vector3.one);
_flipMatrix = Matrix4x4.identity;
_flipMatrix[2, 2] = -1;
Instance = this;
DontDestroyOnLoad(gameObject);
}
catch(DllNotFoundException e)
{
string message = "Please check the Kinect SDK installation.";
Debug.LogError(message);
Debug.LogError(e.ToString());
return;
}
catch (Exception e)
{
string message = e.Message + " - " + KinectWrapper.GetNuiErrorString(hr);
Debug.LogError(message);
Debug.LogError(e.ToString());
return;
}
// get the main camera rectangle
Rect cameraRect = Camera.main.pixelRect;
if(ComputeUserMap)
{
var displayMapsWidthPercent = DisplayMapsWidthPercent / 100f;
var displayMapsHeightPercent = displayMapsWidthPercent * KinectWrapper.GetDepthHeight() / KinectWrapper.GetDepthWidth();
var displayWidth = cameraRect.width * displayMapsWidthPercent;
var displayHeight = cameraRect.width * displayMapsHeightPercent;
// Initialize depth & label map related stuff
_usersMapSize = KinectWrapper.GetDepthWidth() * KinectWrapper.GetDepthHeight();
_usersLblTex = new Texture2D(KinectWrapper.GetDepthWidth(), KinectWrapper.GetDepthHeight());
_usersMapColors = new Color32[_usersMapSize];
_usersPrevState = new ushort[_usersMapSize];
_usersMapRect = new Rect(cameraRect.width - displayWidth, cameraRect.height, displayWidth, -displayHeight);
_usersDepthMap = new ushort[_usersMapSize];
_usersHistogramMap = new float[8192];
}
if(ComputeColorMap)
{
var displayMapsWidthPercent = DisplayMapsWidthPercent / 100f;
var displayMapsHeightPercent = displayMapsWidthPercent * KinectWrapper.GetColorHeight() / KinectWrapper.GetColorWidth();
var displayWidth = cameraRect.width * displayMapsWidthPercent;
var displayHeight = cameraRect.width * displayMapsHeightPercent;
// Initialize color map related stuff
_usersClrTex = new Texture2D(KinectWrapper.GetColorWidth(), KinectWrapper.GetColorHeight());
_usersClrRect = new Rect(cameraRect.width - displayWidth, cameraRect.height, displayWidth, -displayHeight);
_colorImage = new Color32[KinectWrapper.GetColorWidth() * KinectWrapper.GetColorHeight()];
_usersColorMap = new byte[_colorImage.Length << 2];
}
// Initialize user list to contain ALL users.
_allUsers = new List<uint>();
Debug.Log("Waiting for users.");
_kinectInitialized = true;
}
void Update()
{
if(_kinectInitialized)
{
// needed by the KinectExtras' native wrapper to check for next frames
// uncomment the line below, if you use the Extras' wrapper, but none of the Extras' managers
//KinectWrapper.UpdateKinectSensor();
// If the players aren't all calibrated yet, draw the user map.
if(ComputeUserMap)
{
if(_depthStreamHandle != IntPtr.Zero &&
KinectWrapper.PollDepth(_depthStreamHandle, KinectWrapper.Constants.IsNearMode, ref _usersDepthMap))
{
UpdateUserMap();
}
}
if(ComputeColorMap)
{
if(_colorStreamHandle != IntPtr.Zero &&
KinectWrapper.PollColor(_colorStreamHandle, ref _usersColorMap, ref _colorImage))
{
UpdateColorMap();
}
}
if(KinectWrapper.PollSkeleton(ref _smoothParameters, ref _skeletonFrame))
{
ProcessSkeleton();
}
}
// Kill the program with ESC.
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
}
// Make sure to kill the Kinect on quitting.
void OnApplicationQuit()
{
if(_kinectInitialized)
{
// Shutdown OpenNI
KinectWrapper.NuiShutdown();
Instance = null;
}
}
// Update the User Map
void UpdateUserMap()
{
int numOfPoints = 0;
Array.Clear(_usersHistogramMap, 0, _usersHistogramMap.Length);
// Calculate cumulative histogram for depth
for (int i = 0; i < _usersMapSize; i++)
{
// Only calculate for depth that contains users
if ((_usersDepthMap[i] & 7) != 0)
{
ushort userDepth = (ushort)(_usersDepthMap[i] >> 3);
_usersHistogramMap[userDepth]++;
numOfPoints++;
}
}
if (numOfPoints > 0)
{
for (int i = 1; i < _usersHistogramMap.Length; i++)
{
_usersHistogramMap[i] += _usersHistogramMap[i - 1];
}
for (int i = 0; i < _usersHistogramMap.Length; i++)
{
_usersHistogramMap[i] = 1.0f - (_usersHistogramMap[i] / numOfPoints);
}
}
// dummy structure needed by the coordinate mapper
KinectWrapper.NuiImageViewArea pcViewArea = new KinectWrapper.NuiImageViewArea
{
eDigitalZoom = 0,
lCenterX = 0,
lCenterY = 0
};
// Create the actual users texture based on label map and depth histogram
Color32 clrClear = Color.clear;
for (int i = 0; i < _usersMapSize; i++)
{
// Flip the texture as we convert label map to color array
int flipIndex = i; // usersMapSize - i - 1;
ushort userMap = (ushort)(_usersDepthMap[i] & 7);
ushort userDepth = (ushort)(_usersDepthMap[i] >> 3);
ushort nowUserPixel = userMap != 0 ? (ushort)((userMap << 13) | userDepth) : userDepth;
ushort wasUserPixel = _usersPrevState[flipIndex];
// draw only the changed pixels
if(nowUserPixel != wasUserPixel)
{
_usersPrevState[flipIndex] = nowUserPixel;
if (userMap == 0)
{
_usersMapColors[flipIndex] = clrClear;
}
else
{
if(_colorImage != null)
{
int x = i % KinectWrapper.Constants.DepthImageWidth;
int y = i / KinectWrapper.Constants.DepthImageWidth;
int cx, cy;
int hr = KinectWrapper.NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution(
KinectWrapper.Constants.ColorImageResolution,
KinectWrapper.Constants.DepthImageResolution,
ref pcViewArea,
x, y, _usersDepthMap[i],
out cx, out cy);
if(hr == 0)
{
int colorIndex = cx + cy * KinectWrapper.Constants.ColorImageWidth;
//colorIndex = usersMapSize - colorIndex - 1;
if(colorIndex >= 0 && colorIndex < _usersMapSize)
{
Color32 colorPixel = _colorImage[colorIndex];
_usersMapColors[flipIndex] = colorPixel; // new Color(colorPixel.r / 256f, colorPixel.g / 256f, colorPixel.b / 256f, 0.9f);
_usersMapColors[flipIndex].a = 230; // 0.9f
}
}
}
else
{
// Create a blending color based on the depth histogram
float histDepth = _usersHistogramMap[userDepth];
Color c = new Color(histDepth, histDepth, histDepth, 0.9f);
switch(userMap % 4)
{
case 0:
_usersMapColors[flipIndex] = Color.red * c;
break;
case 1:
_usersMapColors[flipIndex] = Color.green * c;
break;
case 2:
_usersMapColors[flipIndex] = Color.blue * c;
break;
case 3:
_usersMapColors[flipIndex] = Color.magenta * c;
break;
}
}
}
}
}
// Draw it!
_usersLblTex.SetPixels32(_usersMapColors);
}
// Update the Color Map
void UpdateColorMap()
{
_usersClrTex.SetPixels32(_colorImage);
_usersClrTex.Apply();
}
// Assign UserId to player 1 or 2.
void CalibrateUser(uint UserId, int UserIndex, ref KinectWrapper.NuiSkeletonData skeletonData)
{
// If player 1 hasn't been calibrated, assign that UserID to it.
if(!_player1Calibrated)
{
// Check to make sure we don't accidentally assign player 2 to player 1.
if (!_allUsers.Contains(UserId))
{
_player1Calibrated = true;
_player1Id = UserId;
_player1Index = UserIndex;
_allUsers.Add(UserId);
// reset skeleton filters
ResetFilters();
// If we're not using 2 users, we're all calibrated.
//if(!TwoUsers)
{
_allPlayersCalibrated = !TwoUsers ? _allUsers.Count >= 1 : _allUsers.Count >= 2; // true;
}
}
}
// Otherwise, assign to player 2.
else if(TwoUsers && !_player2Calibrated)
{
if (!_allUsers.Contains(UserId))
{
_player2Calibrated = true;
_player2Id = UserId;
_player2Index = UserIndex;
_allUsers.Add(UserId);
// reset skeleton filters
ResetFilters();
// All users are calibrated!
_allPlayersCalibrated = !TwoUsers ? _allUsers.Count >= 1 : _allUsers.Count >= 2; // true;
}
}
// If all users are calibrated, stop trying to find them.
if(_allPlayersCalibrated)
{
Debug.Log("All players calibrated.");
}
}
// Remove a lost UserId
void RemoveUser(uint UserId)
{
// If we lose player 1...
if(UserId == _player1Id)
{
// Null out the ID and reset all the models associated with that ID.
_player1Id = 0;
_player1Index = 0;
_player1Calibrated = false;
}
// If we lose player 2...
if(UserId == _player2Id)
{
// Null out the ID and reset all the models associated with that ID.
_player2Id = 0;
_player2Index = 0;
_player2Calibrated = false;
}
// remove from global users list
_allUsers.Remove(UserId);
_allPlayersCalibrated = !TwoUsers ? _allUsers.Count >= 1 : _allUsers.Count >= 2; // false;
// Try to replace that user!
Debug.Log("Waiting for users.");
}
// Some internal constants
private const int stateTracked = (int)KinectWrapper.NuiSkeletonPositionTrackingState.Tracked;
private const int stateNotTracked = (int)KinectWrapper.NuiSkeletonPositionTrackingState.NotTracked;
private int [] mustBeTrackedJoints = {
(int)KinectWrapper.NuiSkeletonPositionIndex.AnkleLeft,
(int)KinectWrapper.NuiSkeletonPositionIndex.FootLeft,
(int)KinectWrapper.NuiSkeletonPositionIndex.AnkleRight,
(int)KinectWrapper.NuiSkeletonPositionIndex.FootRight,
};
public KinectManager(Matrix4x4 kinectToWorld) {
this._kinectToWorld = kinectToWorld;
}
// Process the skeleton data
void ProcessSkeleton()
{
List<uint> lostUsers = new List<uint>();
lostUsers.AddRange(_allUsers);
// calculate the time since last update
float currentNuiTime = Time.realtimeSinceStartup;
float deltaNuiTime = currentNuiTime - _lastNuiTime;
for(int i = 0; i < KinectWrapper.Constants.NuiSkeletonCount; i++)
{
KinectWrapper.NuiSkeletonData skeletonData = _skeletonFrame.SkeletonData[i];
uint userId = skeletonData.dwTrackingID;
if(skeletonData.eTrackingState == KinectWrapper.NuiSkeletonTrackingState.SkeletonTracked)
{
// get the skeleton position
Vector3 skeletonPos = _kinectToWorld.MultiplyPoint3x4(skeletonData.Position);
if(!_allPlayersCalibrated)
{
// check if this is the closest user
bool bClosestUser = true;
if(DetectClosestUser)
{
for(int j = 0; j < KinectWrapper.Constants.NuiSkeletonCount; j++)
{
if(j != i)
{
KinectWrapper.NuiSkeletonData skeletonDataOther = _skeletonFrame.SkeletonData[j];
if((skeletonDataOther.eTrackingState == KinectWrapper.NuiSkeletonTrackingState.SkeletonTracked) &&
(Mathf.Abs(_kinectToWorld.MultiplyPoint3x4(skeletonDataOther.Position).z) < Mathf.Abs(skeletonPos.z)))
{
bClosestUser = false;
break;
}
}
}
}
if(bClosestUser)
{
CalibrateUser(userId, i + 1, ref skeletonData);
}
}
if(userId == _player1Id && Mathf.Abs(skeletonPos.z) >= MinUserDistance &&
(MaxUserDistance <= 0f || Mathf.Abs(skeletonPos.z) <= MaxUserDistance))
{
_player1SkeletonIndex = i;
// get player position
_player1Pos = skeletonPos;
// get joints' position and rotation
for (int j = 0; j < (int)KinectWrapper.NuiSkeletonPositionIndex.Count; j++)
{
bool playerTracked = IgnoreInferredJoints ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked :
(Array.BinarySearch(mustBeTrackedJoints, j) >= 0 ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked :
(int)skeletonData.eSkeletonPositionTrackingState[j] != stateNotTracked);
_player1JointsTracked[j] = _player1PrevTracked[j] && playerTracked;
_player1PrevTracked[j] = playerTracked;
if(_player1JointsTracked[j])
{
_player1JointsPos[j] = _kinectToWorld.MultiplyPoint3x4(skeletonData.SkeletonPositions[j]);
}
}
// calculate joint orientations
KinectWrapper.GetSkeletonJointOrientation(ref _player1JointsPos, ref _player1JointsTracked, ref _player1JointsOri);
// get player rotation
_player1Ori = _player1JointsOri[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter];
}
else if(userId == _player2Id && Mathf.Abs(skeletonPos.z) >= MinUserDistance &&
(MaxUserDistance <= 0f || Mathf.Abs(skeletonPos.z) <= MaxUserDistance))
{
_player2SkeletonIndex = i;
// get player position
_player2Pos = skeletonPos;
// get joints' position and rotation
for (int j = 0; j < (int)KinectWrapper.NuiSkeletonPositionIndex.Count; j++)
{
bool playerTracked = IgnoreInferredJoints ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked :
(Array.BinarySearch(mustBeTrackedJoints, j) >= 0 ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked :
(int)skeletonData.eSkeletonPositionTrackingState[j] != stateNotTracked);
_player2JointsTracked[j] = _player2PrevTracked[j] && playerTracked;
_player2PrevTracked[j] = playerTracked;
if(_player2JointsTracked[j])
{
_player2JointsPos[j] = _kinectToWorld.MultiplyPoint3x4(skeletonData.SkeletonPositions[j]);
}
}
// calculate joint orientations
KinectWrapper.GetSkeletonJointOrientation(ref _player2JointsPos, ref _player2JointsTracked, ref _player2JointsOri);
// get player rotation
_player2Ori = _player2JointsOri[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter];
}
lostUsers.Remove(userId);
}
}
// update the nui-timer
_lastNuiTime = currentNuiTime;
// remove the lost users if any
if(lostUsers.Count > 0)
{
foreach(uint userId in lostUsers)
{
RemoveUser(userId);
}
lostUsers.Clear();
}
}
// draws a line in a texture
private void DrawLine(Texture2D a_Texture, int x1, int y1, int x2, int y2, Color a_Color)
{
int width = a_Texture.width; // KinectWrapper.Constants.DepthImageWidth;
int height = a_Texture.height; // KinectWrapper.Constants.DepthImageHeight;
int dy = y2 - y1;
int dx = x2 - x1;
int stepy = 1;
if (dy < 0)
{
dy = -dy;
stepy = -1;
}
int stepx = 1;
if (dx < 0)
{
dx = -dx;
stepx = -1;
}
dy <<= 1;
dx <<= 1;
if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height)
for(int x = -1; x <= 1; x++)
for(int y = -1; y <= 1; y++)
a_Texture.SetPixel(x1 + x, y1 + y, a_Color);
if (dx > dy)
{
int fraction = dy - (dx >> 1);
while (x1 != x2)
{
if (fraction >= 0)
{
y1 += stepy;
fraction -= dx;
}
x1 += stepx;
fraction += dy;
if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height)
for(int x = -1; x <= 1; x++)
for(int y = -1; y <= 1; y++)
a_Texture.SetPixel(x1 + x, y1 + y, a_Color);
}
}
else
{
int fraction = dx - (dy >> 1);
while (y1 != y2)
{
if (fraction >= 0)
{
x1 += stepx;
fraction -= dy;
}
y1 += stepy;
fraction += dx;
if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height)
for(int x = -1; x <= 1; x++)
for(int y = -1; y <= 1; y++)
a_Texture.SetPixel(x1 + x, y1 + y, a_Color);
}
}
}
// convert the matrix to quaternion, taking care of the mirroring
private Quaternion ConvertMatrixToQuat(Matrix4x4 mOrient, int joint, bool flip)
{
var vZ = mOrient.GetColumn(2);
var vY = mOrient.GetColumn(1);
if(!flip)
{
vZ.y = -vZ.y;
vY.x = -vY.x;
vY.z = -vY.z;
}
else
{
vZ.x = -vZ.x;
vZ.y = -vZ.y;
vY.z = -vY.z;
}
if (vZ.x != 0.0f || vZ.y != 0.0f || vZ.z != 0.0f) {
return Quaternion.LookRotation(vZ, vY);
}
return Quaternion.identity;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace GamePoc0.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
#region License
// Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#endregion
using BenchmarkDotNet.Attributes;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace SourceCode.Clay.Buffers.Bench
{
/*
If using AggressiveInlining:
Method | Mean | Error | StdDev | Scaled | ScaledSD |
-------- |---------:|----------:|----------:|-------:|---------:|
Actual | 21.24 ns | 0.1442 ns | 0.1349 ns | 1.00 | 0.00 | X
Unroll | 27.40 ns | 0.4784 ns | 0.4475 ns | 1.29 | 0.02 |
Blit | 26.38 ns | 0.2007 ns | 0.1878 ns | 1.24 | 0.01 |
Hybrid1 | 22.64 ns | 0.3441 ns | 0.3219 ns | 1.07 | 0.02 | x
Hybrid2 | 21.24 ns | 0.2131 ns | 0.1994 ns | 1.00 | 0.01 | x
Cast | 23.29 ns | 0.1943 ns | 0.1818 ns | 1.10 | 0.01 | x
Else:
Method | Mean | Error | StdDev | Scaled | ScaledSD |
-------- |---------:|----------:|----------:|-------:|---------:|
Actual | 21.45 ns | 0.1922 ns | 0.1704 ns | 1.00 | 0.00 | X
Unroll | 27.19 ns | 0.1992 ns | 0.1766 ns | 1.27 | 0.01 |
Blit | 26.64 ns | 0.2264 ns | 0.2118 ns | 1.24 | 0.01 |
Hybrid1 | 22.90 ns | 0.2583 ns | 0.2416 ns | 1.07 | 0.01 | x
Hybrid2 | 21.58 ns | 0.3742 ns | 0.3317 ns | 1.01 | 0.02 | x
Cast | 36.24 ns | 0.6614 ns | 0.6186 ns | 1.69 | 0.03 |
Cast is fast when inlined, but much slower when not.
All others are consistent, whether inlined or not.
Some callsites may not inline.
*/
//[MemoryDiagnoser]
public class SpanBench
{
private const uint _iterations = 100;
private const uint N = ushort.MaxValue;
// Whatever is being used in the actual code
[Benchmark(Baseline = true, OperationsPerInvoke = (int)(_iterations * N))]
public static ulong Actual()
{
var sum = 0ul;
for (var i = 0; i < _iterations; i++)
{
for (var n = 0; n <= N; n++)
{
long v = i * n * ushort.MaxValue + uint.MaxValue;
var b = BitConverter.GetBytes(v);
b = new byte[25] { 0, 0, 0, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], 0, 0, 1, 0, 0, 0, 1, 2, 0, 4, 5, 3, 0, 100 };
var u64 = BitOps.ExtractUInt64(b, n % b.Length);
sum = unchecked(sum + u64);
}
}
return sum;
}
[Benchmark(Baseline = false, OperationsPerInvoke = (int)(_iterations * N))]
public static ulong Unroll()
{
var sum = 0ul;
for (var i = 0; i < _iterations; i++)
{
for (var n = 0; n <= N; n++)
{
long v = i * n * ushort.MaxValue + uint.MaxValue;
var b = BitConverter.GetBytes(v);
b = new byte[25] { 0, 0, 0, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], 0, 0, 1, 0, 0, 0, 1, 2, 0, 4, 5, 3, 0, 100 };
var u64 = ExtractUInt64_Unroll(b, n % b.Length);
sum = unchecked(sum + u64);
}
}
return sum;
}
[Benchmark(Baseline = false, OperationsPerInvoke = (int)(_iterations * N))]
public static ulong Blit()
{
var sum = 0ul;
for (var i = 0; i < _iterations; i++)
{
for (var n = 0; n <= N; n++)
{
long v = i * n * ushort.MaxValue + uint.MaxValue;
var b = BitConverter.GetBytes(v);
b = new byte[25] { 0, 0, 0, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], 0, 0, 1, 0, 0, 0, 1, 2, 0, 4, 5, 3, 0, 100 };
var u64 = ExtractUInt64_Blit(b, n % b.Length);
sum = unchecked(sum + u64);
}
}
return sum;
}
[Benchmark(Baseline = false, OperationsPerInvoke = (int)(_iterations * N))]
public static ulong Hybrid1()
{
var sum = 0ul;
for (var i = 0; i < _iterations; i++)
{
for (var n = 0; n <= N; n++)
{
long v = i * n * ushort.MaxValue + uint.MaxValue;
var b = BitConverter.GetBytes(v);
b = new byte[25] { 0, 0, 0, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], 0, 0, 1, 0, 0, 0, 1, 2, 0, 4, 5, 3, 0, 100 };
var u64 = ExtractUInt64_Hybrid1(b, n % b.Length);
sum = unchecked(sum + u64);
}
}
return sum;
}
[Benchmark(Baseline = false, OperationsPerInvoke = (int)(_iterations * N))]
public static ulong Hybrid2()
{
var sum = 0ul;
for (var i = 0; i < _iterations; i++)
{
for (var n = 0; n <= N; n++)
{
long v = i * n * ushort.MaxValue + uint.MaxValue;
var b = BitConverter.GetBytes(v);
b = new byte[25] { 0, 0, 0, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], 0, 0, 1, 0, 0, 0, 1, 2, 0, 4, 5, 3, 0, 100 };
var u64 = ExtractUInt64_Hybrid2(b, n % b.Length);
sum = unchecked(sum + u64);
}
}
return sum;
}
[Benchmark(Baseline = false, OperationsPerInvoke = (int)(_iterations * N))]
public static ulong Cast()
{
var sum = 0ul;
for (var i = 0; i < _iterations; i++)
{
for (var n = 0; n <= N; n++)
{
long v = i * n * ushort.MaxValue + uint.MaxValue;
var b = BitConverter.GetBytes(v);
b = new byte[25] { 0, 0, 0, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], 0, 0, 1, 0, 0, 0, 1, 2, 0, 4, 5, 3, 0, 100 };
var u64 = ExtractUInt64_Cast(b, n % b.Length);
sum = unchecked(sum + u64);
}
}
return sum;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ulong ExtractUInt64_Unroll(ReadOnlySpan<byte> span, int bitOffset)
{
int ix = bitOffset >> 3; // div 8
var len = span.Length - ix;
int shft = bitOffset & 7; // mod 8
ulong val = 0;
switch (len)
{
// Need at least 8+1 bytes
default:
if (len <= 0) throw new ArgumentOutOfRangeException(nameof(bitOffset));
goto case 9;
case 09: val = (ulong)span[ix + 8] << (8 * 8 - shft); goto case 8;
case 8: val |= (ulong)span[ix + 7] << (7 * 8 - shft); goto case 7;
case 7: val |= (ulong)span[ix + 6] << (6 * 8 - shft); goto case 6;
case 6: val |= (ulong)span[ix + 5] << (5 * 8 - shft); goto case 5;
case 5: val |= (ulong)span[ix + 4] << (4 * 8 - shft); goto case 4;
case 4: val |= (ulong)span[ix + 3] << (3 * 8 - shft); goto case 3;
case 3: val |= (ulong)span[ix + 2] << (2 * 8 - shft); goto case 2;
case 2: val |= (ulong)span[ix + 1] << (1 * 8 - shft); goto case 1;
case 1: val |= (ulong)span[ix + 0] >> shft; break;
}
return val;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ulong ExtractUInt64_Blit(ReadOnlySpan<byte> span, int bitOffset)
{
int ix = bitOffset >> 3; // div 8
var len = Math.Max(0, span.Length - ix);
int shft = bitOffset & 7; // mod 8
var blit = new Blit64();
ulong val = 0;
switch (len)
{
case 0: throw new ArgumentOutOfRangeException(nameof(bitOffset));
// Need at least 8+1 bytes
default:
val = (ulong)span[ix + 8] << (64 - shft);
goto case 8;
case 8: blit.b7 = span[ix + 7]; goto case 7;
case 7: blit.b6 = span[ix + 6]; goto case 6;
case 6: blit.b5 = span[ix + 5]; goto case 5;
case 5: blit.b4 = span[ix + 4]; goto case 4;
case 4: blit.b3 = span[ix + 3]; goto case 3;
case 3: blit.b2 = span[ix + 2]; goto case 2;
case 2: blit.b1 = span[ix + 1]; goto case 1;
case 1: blit.b0 = span[ix + 0]; break;
}
val |= blit.u64 >> shft;
return val;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ulong ExtractUInt64_Hybrid1(ReadOnlySpan<byte> span, int bitOffset)
{
int ix = bitOffset >> 3; // div 8
var len = Math.Max(0, span.Length - ix);
int shft = bitOffset & 7; // mod 8
var blit = new Blit64();
ulong val = 0;
switch (len)
{
case 0: throw new ArgumentOutOfRangeException(nameof(bitOffset));
// Need at least 8+1 bytes
default:
val = (ulong)span[ix + 8] << (64 - shft);
goto case 8;
case 8: blit.u64 = MemoryMarshal.Cast<byte, ulong>(span.Slice(ix, 8))[0]; break;
case 7: blit.b6 = span[ix + 6]; goto case 6;
case 6: blit.b5 = span[ix + 5]; goto case 5;
case 5: blit.b4 = span[ix + 4]; goto case 4;
case 4: blit.i0 = MemoryMarshal.Cast<byte, uint>(span.Slice(ix, 4))[0]; break;
case 3: blit.b2 = span[ix + 2]; goto case 2;
case 2: blit.s0 = MemoryMarshal.Cast<byte, ushort>(span.Slice(ix, 2))[0]; break;
case 1: blit.b0 = span[ix + 0]; break;
}
val |= blit.u64 >> shft;
return val;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ulong ExtractUInt64_Hybrid2(ReadOnlySpan<byte> span, int bitOffset)
{
int ix = bitOffset >> 3; // div 8
if (ix >= span.Length) throw new ArgumentOutOfRangeException(nameof(bitOffset));
ReadOnlySpan<byte> bytes = span.Slice(ix);
ulong left = 0;
ulong blit = 0;
switch (span.Length - ix)
{
// Need at least 8+1 bytes
default:
case 9: left = bytes[8]; goto case 8;
case 8: blit = BitOps.ReadUInt64(bytes); break;
case 7: blit = (ulong)bytes[6] << 48; goto case 6;
case 6: blit |= (ulong)bytes[5] << 40; goto case 5;
case 5: blit |= (ulong)bytes[4] << 32; goto case 4;
case 4: blit |= BitOps.ReadUInt32(bytes); break;
case 3: blit = (ulong)bytes[2] << 16; goto case 2;
case 2: blit |= (ulong)bytes[1] << 8; goto case 1;
case 1: blit |= bytes[0]; break;
}
int shft = bitOffset & 7; // mod 8
blit = (left << (64 - shft)) | (blit >> shft);
return blit;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ExtractUInt64_Cast(ReadOnlySpan<byte> span, int bitOffset)
{
int ix = bitOffset >> 3; // div 8
if (ix >= span.Length) throw new ArgumentOutOfRangeException(nameof(bitOffset));
// Need at least 8+1 bytes, so align on 16
int len = Math.Min(span.Length - ix, 16);
Span<byte> aligned = stackalloc byte[16];
span.Slice(ix, len).CopyTo(aligned);
ReadOnlySpan<ulong> cast = MemoryMarshal.Cast<byte, ulong>(aligned);
int shft = bitOffset & 7; // mod 8
ulong val = cast[0] >> shft;
val |= cast[1] << (64 - shft);
return val;
}
#pragma warning disable IDE1006 // Naming Styles
[StructLayout(LayoutKind.Explicit, Size = 8)]
private ref struct Blit64
{
// byte
[FieldOffset(0)]
public byte b0;
[FieldOffset(1)]
public byte b1;
[FieldOffset(2)]
public byte b2;
[FieldOffset(3)]
public byte b3;
[FieldOffset(4)]
public byte b4;
[FieldOffset(5)]
public byte b5;
[FieldOffset(6)]
public byte b6;
[FieldOffset(7)]
public byte b7;
// ushort
[FieldOffset(0)]
public ushort s0;
[FieldOffset(1)]
public ushort s1;
[FieldOffset(2)]
public ushort s2;
[FieldOffset(3)]
public ushort s3;
// uint
[FieldOffset(0)]
public uint i0;
[FieldOffset(1)]
public uint i1;
// ulong
[FieldOffset(0)]
public ulong u64;
}
[StructLayout(LayoutKind.Explicit, Size = 4)]
private ref struct Blit32
{
// byte
[FieldOffset(0)]
public byte b0;
[FieldOffset(1)]
public byte b1;
[FieldOffset(2)]
public byte b2;
[FieldOffset(3)]
public byte b3;
// ushort
[FieldOffset(0)]
public ushort s0;
[FieldOffset(1)]
public ushort s1;
// uint
[FieldOffset(0)]
public uint u32;
}
#pragma warning restore IDE1006 // Naming Styles
}
}
| |
using System;
using System.Text;
namespace xroad
{
namespace car
{
internal class Converter
{
public static int to_bytes(int val, ref byte[] bytes, int offset)
{
bytes[0 + offset] = (byte) val;
bytes[1 + offset] = (byte) (val >> 8);
bytes[2 + offset] = (byte) (val >> 16);
bytes[3 + offset] = (byte) (val >> 24);
return 4;
}
public static int to_bytes(uint val, ref byte[] bytes, int offset)
{
bytes[0 + offset] = (byte) val;
bytes[1 + offset] = (byte) (val >> 8);
bytes[2 + offset] = (byte) (val >> 16);
bytes[3 + offset] = (byte) (val >> 24);
return 4;
}
public static int to_bytes(long val, ref byte[] bytes, int offset)
{
bytes[0 + offset] = (byte) val;
bytes[1 + offset] = (byte) (val >> 8);
bytes[2 + offset] = (byte) (val >> 16);
bytes[3 + offset] = (byte) (val >> 24);
bytes[4 + offset] = (byte) (val >> 32);
bytes[5 + offset] = (byte) (val >> 40);
bytes[6 + offset] = (byte) (val >> 48);
bytes[7 + offset] = (byte) (val >> 56);
return 8;
}
public static int to_bytes(ulong val, ref byte[] bytes, int offset)
{
bytes[0 + offset] = (byte) val;
bytes[1 + offset] = (byte) (val >> 8);
bytes[2 + offset] = (byte) (val >> 16);
bytes[3 + offset] = (byte) (val >> 24);
bytes[4 + offset] = (byte) (val >> 32);
bytes[5 + offset] = (byte) (val >> 40);
bytes[6 + offset] = (byte) (val >> 48);
bytes[7 + offset] = (byte) (val >> 56);
return 8;
}
public static int to_bytes(short val, ref byte[] bytes, int offset)
{
bytes[0 + offset] = (byte) val;
bytes[1 + offset] = (byte) (val >> 8);
return 8;
}
public static int to_bytes(ushort val, ref byte[] bytes, int offset)
{
bytes[0 + offset] = (byte) val;
bytes[1 + offset] = (byte) (val >> 8);
return 8;
}
public static int to_bytes(byte val, ref byte[] bytes, int offset)
{
bytes[0 + offset] = val;
return 8;
}
public static int to_bytes(sbyte val, ref byte[] bytes, int offset)
{
bytes[0 + offset] = (byte) val;
return 8;
}
public static int to_bytes(float val, ref byte[] bytes, int offset)
{
var arr = BitConverter.GetBytes(val);
bytes[0 + offset] = arr[0];
bytes[1 + offset] = arr[1];
bytes[2 + offset] = arr[2];
bytes[3 + offset] = arr[3];
return 4;
}
public static int to_bytes(double val, ref byte[] bytes, int offset)
{
var arr = BitConverter.GetBytes(val);
bytes[0 + offset] = arr[0];
bytes[1 + offset] = arr[1];
bytes[2 + offset] = arr[2];
bytes[3 + offset] = arr[3];
bytes[4 + offset] = arr[4];
bytes[5 + offset] = arr[5];
bytes[6 + offset] = arr[6];
bytes[7 + offset] = arr[7];
return 8;
}
public static int to_bytes(string val, ref byte[] bytes, int size, int offset)
{
var arr = Encoding.ASCII.GetBytes(val);
var sz = Math.Min(val.Length, size);
for(var i = 0; i < sz; ++i) bytes[i + offset] = arr[i];
return sz;
}
}
internal enum Templates : short
{
car = 1
}
/// Message Header Encoder
internal class MessageHeaderTypeEncoder
{
private int size_ = 8;
private byte[] data_;
private readonly int offset_;
public MessageHeaderTypeEncoder(ref byte[] data, int offset)
{
data_ = data;
offset_ = offset;
}
public int size
{
get { return size_; }
}
public short blockLength
{
set { Converter.to_bytes(value, ref data_, offset_ + 0); }
}
public Templates templateId
{
set { Converter.to_bytes((short) value, ref data_, offset_ + 2); }
}
public short schemaId
{
set { Converter.to_bytes(value, ref data_, offset_ + 4); }
}
public short version
{
set { Converter.to_bytes(value, ref data_, offset_ + 6); }
}
}
/// Message Header Decoder
internal class MessageHeaderTypeDecoder
{
public int size_ = 8;
private byte[] data_;
public MessageHeaderTypeDecoder(ref byte[] data)
{
data_ = data;
}
public int size
{
get { return size_; }
}
public short blockLength
{
get { return BitConverter.ToInt16(data_, 0); }
}
public Templates templateId
{
get { return (Templates) BitConverter.ToInt16(data_, 2); }
}
public short schemaId
{
get { return BitConverter.ToInt16(data_, 4); }
}
public short version
{
get { return BitConverter.ToInt16(data_, 6); }
}
}
/// Repeating group dimensions
internal class GroupSizeEncodingTypeEncoder
{
public int size_ = 4;
private byte[] data_;
private readonly int offset_;
private int var_offset_;
public GroupSizeEncodingTypeEncoder(ref byte[] data, ref int var_offset, int offset)
{
data_ = data;
offset_ = offset;
var_offset_ = var_offset;
}
public int size
{
get { return size_; }
}
public short blockLength
{
set { Converter.to_bytes(value, ref data_, var_offset_ + offset_ + 0); }
}
public short numInGroup
{
set { Converter.to_bytes(value, ref data_, var_offset_ + offset_ + 2); }
}
}
/// Repeating group dimensions
internal class GroupSizeEncodingTypeDecoder
{
public int size_ = 4;
private byte[] data_;
private readonly int offset_;
private int var_offset_;
public GroupSizeEncodingTypeDecoder(ref byte[] data, ref int var_offset, int offset)
{
data_ = data;
offset_ = offset;
var_offset_ = var_offset;
}
public int size
{
get { return size_; }
}
public short blockLength
{
get { return BitConverter.ToInt16(data_, var_offset_ + offset_ + 0); }
}
public short numInGroup
{
get { return BitConverter.ToInt16(data_, var_offset_ + offset_ + 2); }
}
}
/// Variable-length string encoder
internal class VarStringTypeEncoder
{
public int size_ = 2;
private byte[] data_;
private readonly int offset_;
private int var_offset_;
public VarStringTypeEncoder(ref byte[] data, ref int var_offset, int offset)
{
data_ = data;
offset_ = offset;
var_offset_ = var_offset;
}
public int size
{
get { return size_; }
}
public string val
{
set
{
Converter.to_bytes((ushort)value.Length, ref data_, var_offset_ + offset_ + 0);
Converter.to_bytes(value, ref data_, value.Length, var_offset_ + offset_ + 2);
size_ += value.Length;
var_offset_ += value.Length;
}
}
}
/// Variable-length string decoder
internal class VarStringTypeDecoder
{
public int size_ = 2;
private byte[] data_;
private readonly int offset_;
private int var_offset_;
public VarStringTypeDecoder(ref byte[] data, ref int var_offset, int offset)
{
data_ = data;
offset_ = offset;
var_offset_ = var_offset;
}
public int size
{
get { return size_; }
}
public string val
{
get
{
int length = BitConverter.ToUInt16(data_, var_offset_ + offset_ + 0);
var arr = new byte[length];
Array.Copy(data_, var_offset_ + offset_ + 2, arr, 0, arr.Length);
size_ += length;
var_offset_ += length;
return System.Text.Encoding.Default.GetString(arr);
}
}
}
internal partial class carEncoder
{
private byte[] data_;
private int size_;
private readonly int offset_;
private int var_offset_ = 0;
public carEncoder(ref byte[] data, int size, int offset)
{
data_ = data;
size_ = size;
offset_ = offset;
}
public int size
{
get { return size_ + 24 + var_offset_; }
}
// car id
public Int32 id
{
set
{
Converter.to_bytes(value, ref data_, var_offset_ + offset_ + 0);
}
}
// car name
public string name
{
set
{
Converter.to_bytes(value, ref data_, 20, var_offset_ + offset_ + 4);
}
}
}
internal partial class carDecoder
{
private byte[] data_;
private readonly int offset_;
private int var_offset_ = 0;
public carDecoder(ref byte[] data, int offset)
{
data_ = data;
offset_ = offset;
}
// car id
public Int32 id
{
get
{
return BitConverter.ToInt32(data_, offset_ + 0);
}
}
// car name
public string name
{
get
{
return Encoding.ASCII.GetString(data_, offset_ + 4, 20).TrimEnd((char)0);
}
}
}
internal class ObjectFactory
{
public static object createEncoder<T>(ref byte[] data, ref int size)
{
if(typeof(T) == typeof(carEncoder))
{
MessageHeaderTypeEncoder hdr = new MessageHeaderTypeEncoder(ref data, 0);
hdr.blockLength = 24;
hdr.templateId = Templates.car;
hdr.schemaId = 1;
hdr.version = 1;
carEncoder obj = new carEncoder(ref data, hdr.size, hdr.size);
return obj;
}
throw new ArgumentException("unknown object type");
}
}
}
} // namespace xroad
| |
//
// 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 Hyak.Common;
using Microsoft.Azure.Management.Internal.Resources.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
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;
namespace Microsoft.Azure.Management.Internal.Resources
{
/// <summary>
/// Operations for managing resource groups.
/// </summary>
internal partial class ResourceGroupOperations : IServiceOperations<ResourceManagementClient>, IResourceGroupOperations
{
/// <summary>
/// Initializes a new instance of the ResourceGroupOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ResourceGroupOperations(ResourceManagementClient client)
{
this._client = client;
}
private ResourceManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient.
/// </summary>
public ResourceManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Begin deleting resource group.To determine whether the operation
/// has finished processing the request, call
/// GetLongRunningOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be deleted. The name is
/// case insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> BeginDeletingAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResponse result = null;
// Deserialize Response
result = new LongRunningOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Conflict)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Checks whether resource group exists.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to check. The name is case
/// insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupExistsResult> CheckExistenceAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
TracingAdapter.Enter(invocationId, this, "CheckExistenceAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Head;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.NotFound)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceGroupExistsResult result = null;
// Deserialize Response
result = new ResourceGroupExistsResult();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Exists = true;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be created or updated.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create or update resource
/// group service operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupCreateOrUpdateResult> CreateOrUpdateAsync(string resourceGroupName, ResourceGroup parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject resourceGroupValue = new JObject();
requestDoc = resourceGroupValue;
resourceGroupValue["location"] = parameters.Location;
if (parameters.Properties != null)
{
resourceGroupValue["properties"] = JObject.Parse(parameters.Properties);
}
if (parameters.Tags != null)
{
if (parameters.Tags is ILazyCollection == false || ((ILazyCollection)parameters.Tags).IsInitialized)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
resourceGroupValue["tags"] = tagsDictionary;
}
}
if (parameters.ProvisioningState != null)
{
resourceGroupValue["provisioningState"] = parameters.ProvisioningState;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceGroupCreateOrUpdateResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupCreateOrUpdateResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
result.ResourceGroup = resourceGroupInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupInstance.Location = locationInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
resourceGroupInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken provisioningStateValue2 = responseDoc["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete resource group and all of its resources.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be deleted. The name is
/// case insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, CancellationToken cancellationToken)
{
ResourceManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResponse response = await client.ResourceGroups.BeginDeletingAsync(resourceGroupName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupGetResult> GetAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceGroupGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
result.ResourceGroup = resourceGroupInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupInstance.Location = locationInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
resourceGroupInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken provisioningStateValue2 = responseDoc["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a collection of resource groups.
/// </summary>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns all resource
/// groups.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of resource groups.
/// </returns>
public async Task<ResourceGroupListResult> ListAsync(ResourceGroupListParameters parameters, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (parameters != null && parameters.TagName != null)
{
odataFilter.Add("tagname eq '" + Uri.EscapeDataString(parameters.TagName) + "'");
}
if (parameters != null && parameters.TagValue != null)
{
odataFilter.Add("tagvalue eq '" + Uri.EscapeDataString(parameters.TagValue) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
if (parameters != null && parameters.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString()));
}
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceGroupListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ResourceGroupExtended resourceGroupJsonFormatInstance = new ResourceGroupExtended();
result.ResourceGroups.Add(resourceGroupJsonFormatInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupJsonFormatInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupJsonFormatInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupJsonFormatInstance.Location = locationInstance;
}
JToken propertiesValue2 = valueValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupJsonFormatInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
resourceGroupJsonFormatInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken provisioningStateValue2 = valueValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of resource groups.
/// </returns>
public async Task<ResourceGroupListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceGroupListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ResourceGroupExtended resourceGroupJsonFormatInstance = new ResourceGroupExtended();
result.ResourceGroups.Add(resourceGroupJsonFormatInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupJsonFormatInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupJsonFormatInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupJsonFormatInstance.Location = locationInstance;
}
JToken propertiesValue2 = valueValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupJsonFormatInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
resourceGroupJsonFormatInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken provisioningStateValue2 = valueValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Resource groups can be updated through a simple PATCH operation to
/// a group address. The format of the request is the same as that for
/// creating a resource groups, though if a field is unspecified
/// current value will be carried over.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be created or updated.
/// The name is case insensitive.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the update state resource group
/// service operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupPatchResult> PatchAsync(string resourceGroupName, ResourceGroup parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject resourceGroupValue = new JObject();
requestDoc = resourceGroupValue;
resourceGroupValue["location"] = parameters.Location;
if (parameters.Properties != null)
{
resourceGroupValue["properties"] = JObject.Parse(parameters.Properties);
}
if (parameters.Tags != null)
{
if (parameters.Tags is ILazyCollection == false || ((ILazyCollection)parameters.Tags).IsInitialized)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
resourceGroupValue["tags"] = tagsDictionary;
}
}
if (parameters.ProvisioningState != null)
{
resourceGroupValue["provisioningState"] = parameters.ProvisioningState;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceGroupPatchResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupPatchResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
result.ResourceGroup = resourceGroupInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupInstance.Location = locationInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
resourceGroupInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken provisioningStateValue2 = responseDoc["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System.Linq;
using Content.Client.Info;
using Content.Client.Lobby.UI;
using Content.Client.Resources;
using Content.Shared.CharacterAppearance.Systems;
using Content.Shared.Preferences;
using Content.Shared.Roles;
using Content.Shared.Species;
using Robust.Client.AutoGenerated;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.XAML;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
using static Robust.Client.UserInterface.Controls.BoxContainer;
namespace Content.Client.Preferences.UI
{
[GenerateTypedNameReferences]
public sealed partial class CharacterSetupGui : Control
{
private readonly IClientPreferencesManager _preferencesManager;
private readonly IEntityManager _entityManager;
private readonly IPrototypeManager _prototypeManager;
private readonly Button _createNewCharacterButton;
private readonly HumanoidProfileEditor _humanoidProfileEditor;
public CharacterSetupGui(
IEntityManager entityManager,
IResourceCache resourceCache,
IClientPreferencesManager preferencesManager,
IPrototypeManager prototypeManager)
{
RobustXamlLoader.Load(this);
_entityManager = entityManager;
_prototypeManager = prototypeManager;
_preferencesManager = preferencesManager;
var panelTex = resourceCache.GetTexture("/Textures/Interface/Nano/button.svg.96dpi.png");
var back = new StyleBoxTexture
{
Texture = panelTex,
Modulate = new Color(37, 37, 42)
};
back.SetPatchMargin(StyleBox.Margin.All, 10);
BackgroundPanel.PanelOverride = back;
_createNewCharacterButton = new Button
{
Text = Loc.GetString("character-setup-gui-create-new-character-button"),
};
_createNewCharacterButton.OnPressed += args =>
{
preferencesManager.CreateCharacter(HumanoidCharacterProfile.Random());
UpdateUI();
args.Event.Handle();
};
_humanoidProfileEditor = new HumanoidProfileEditor(preferencesManager, prototypeManager, entityManager);
_humanoidProfileEditor.OnProfileChanged += ProfileChanged;
CharEditor.AddChild(_humanoidProfileEditor);
UpdateUI();
RulesButton.OnPressed += _ => new RulesAndInfoWindow().Open();
preferencesManager.OnServerDataLoaded += UpdateUI;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!disposing)
return;
_preferencesManager.OnServerDataLoaded -= UpdateUI;
}
public void Save() => _humanoidProfileEditor.Save();
private void ProfileChanged(ICharacterProfile profile, int profileSlot)
{
_humanoidProfileEditor.UpdateControls();
UpdateUI();
}
private void UpdateUI()
{
var numberOfFullSlots = 0;
var characterButtonsGroup = new ButtonGroup();
Characters.RemoveAllChildren();
if (!_preferencesManager.ServerDataLoaded)
{
return;
}
_createNewCharacterButton.ToolTip =
Loc.GetString("character-setup-gui-create-new-character-button-tooltip",
("maxCharacters", _preferencesManager.Settings!.MaxCharacterSlots));
foreach (var (slot, character) in _preferencesManager.Preferences!.Characters)
{
if (character is null)
{
continue;
}
numberOfFullSlots++;
var characterPickerButton = new CharacterPickerButton(_entityManager,
_preferencesManager,
_prototypeManager,
characterButtonsGroup,
character);
Characters.AddChild(characterPickerButton);
var characterIndexCopy = slot;
characterPickerButton.OnPressed += args =>
{
_humanoidProfileEditor.Profile = (HumanoidCharacterProfile) character;
_humanoidProfileEditor.CharacterSlot = characterIndexCopy;
_humanoidProfileEditor.UpdateControls();
_preferencesManager.SelectCharacter(character);
UpdateUI();
args.Event.Handle();
};
}
_createNewCharacterButton.Disabled =
numberOfFullSlots >= _preferencesManager.Settings.MaxCharacterSlots;
Characters.AddChild(_createNewCharacterButton);
}
private sealed class CharacterPickerButton : ContainerButton
{
private EntityUid _previewDummy;
public CharacterPickerButton(
IEntityManager entityManager,
IClientPreferencesManager preferencesManager,
IPrototypeManager prototypeManager,
ButtonGroup group,
ICharacterProfile profile)
{
AddStyleClass(StyleClassButton);
ToggleMode = true;
Group = group;
var humanoid = profile as HumanoidCharacterProfile;
if (humanoid is not null)
{
var dummy = prototypeManager.Index<SpeciesPrototype>(humanoid.Species).DollPrototype;
_previewDummy = entityManager.SpawnEntity(dummy, MapCoordinates.Nullspace);
}
else
{
_previewDummy = entityManager.SpawnEntity(prototypeManager.Index<SpeciesPrototype>(SpeciesManager.DefaultSpecies).DollPrototype, MapCoordinates.Nullspace);
}
EntitySystem.Get<SharedHumanoidAppearanceSystem>().UpdateFromProfile(_previewDummy, profile);
if (humanoid != null)
{
LobbyCharacterPreviewPanel.GiveDummyJobClothes(_previewDummy, humanoid);
}
var isSelectedCharacter = profile == preferencesManager.Preferences?.SelectedCharacter;
if (isSelectedCharacter)
Pressed = true;
var view = new SpriteView
{
Sprite = entityManager.GetComponent<SpriteComponent>(_previewDummy),
Scale = (2, 2),
OverrideDirection = Direction.South
};
var description = profile.Name;
var highPriorityJob = humanoid?.JobPriorities.SingleOrDefault(p => p.Value == JobPriority.High).Key;
if (highPriorityJob != null)
{
var jobName = IoCManager.Resolve<IPrototypeManager>().Index<JobPrototype>(highPriorityJob).Name;
description = $"{description}\n{jobName}";
}
var descriptionLabel = new Label
{
Text = description,
ClipText = true,
HorizontalExpand = true
};
var deleteButton = new Button
{
Text = Loc.GetString("character-setup-gui-character-picker-button-delete-button"),
Visible = !isSelectedCharacter,
};
deleteButton.OnPressed += _ =>
{
Parent?.RemoveChild(this);
preferencesManager.DeleteCharacter(profile);
};
var internalHBox = new BoxContainer
{
Orientation = LayoutOrientation.Horizontal,
HorizontalExpand = true,
SeparationOverride = 0,
Children =
{
view,
descriptionLabel,
deleteButton
}
};
AddChild(internalHBox);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!disposing)
return;
IoCManager.Resolve<IEntityManager>().DeleteEntity((EntityUid) _previewDummy);
_previewDummy = default;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities.DurableInstancing
{
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Runtime.DurableInstancing;
using System.Transactions;
using System.Xml.Linq;
class LoadWorkflowAsyncResult : SqlWorkflowInstanceStoreAsyncResult
{
static readonly string commandText = string.Format(CultureInfo.InvariantCulture, "{0}.[LoadInstance]", SqlWorkflowInstanceStoreConstants.DefaultSchema);
Dictionary<Guid, IDictionary<XName, InstanceValue>> associatedInstanceKeys;
Dictionary<Guid, IDictionary<XName, InstanceValue>> completedInstanceKeys;
Dictionary<XName, InstanceValue> instanceData;
Dictionary<XName, InstanceValue> instanceMetadata;
IObjectSerializer objectSerializer;
public LoadWorkflowAsyncResult
(
InstancePersistenceContext context,
InstancePersistenceCommand command,
SqlWorkflowInstanceStore store,
SqlWorkflowInstanceStoreLock storeLock,
Transaction currentTransaction,
TimeSpan timeout,
AsyncCallback callback,
object state
) :
base(context, command, store, storeLock, currentTransaction, timeout, callback, state)
{
this.associatedInstanceKeys = new Dictionary<Guid, IDictionary<XName, InstanceValue>>();
this.completedInstanceKeys = new Dictionary<Guid, IDictionary<XName, InstanceValue>>();
this.objectSerializer = ObjectSerializerFactory.GetDefaultObjectSerializer();
}
protected void GenerateLoadSqlCommand
(
SqlCommand command,
LoadType loadType,
Guid keyToLoadBy,
Guid instanceId,
List<CorrelationKey> keysToAssociate
)
{
long surrogateLockOwnerId = base.StoreLock.SurrogateLockOwnerId;
byte[] concatenatedKeyProperties = null;
bool singleKeyToAssociate = (keysToAssociate != null && keysToAssociate.Count == 1);
if (keysToAssociate != null)
{
concatenatedKeyProperties = SerializationUtilities.CreateKeyBinaryBlob(keysToAssociate);
}
double operationTimeout = this.TimeoutHelper.RemainingTime().TotalMilliseconds;
SqlParameterCollection parameters = command.Parameters;
parameters.Add(new SqlParameter { ParameterName = "@surrogateLockOwnerId", SqlDbType = SqlDbType.BigInt, Value = surrogateLockOwnerId });
parameters.Add(new SqlParameter { ParameterName = "@operationType", SqlDbType = SqlDbType.TinyInt, Value = loadType });
parameters.Add(new SqlParameter { ParameterName = "@keyToLoadBy", SqlDbType = SqlDbType.UniqueIdentifier, Value = keyToLoadBy });
parameters.Add(new SqlParameter { ParameterName = "@instanceId", SqlDbType = SqlDbType.UniqueIdentifier, Value = instanceId });
parameters.Add(new SqlParameter { ParameterName = "@handleInstanceVersion", SqlDbType = SqlDbType.BigInt, Value = base.InstancePersistenceContext.InstanceVersion });
parameters.Add(new SqlParameter { ParameterName = "@handleIsBoundToLock", SqlDbType = SqlDbType.Bit, Value = base.InstancePersistenceContext.InstanceView.IsBoundToLock });
parameters.Add(new SqlParameter { ParameterName = "@keysToAssociate", SqlDbType = SqlDbType.Xml, Value = singleKeyToAssociate ? DBNull.Value : SerializationUtilities.CreateCorrelationKeyXmlBlob(keysToAssociate) });
parameters.Add(new SqlParameter { ParameterName = "@encodingOption", SqlDbType = SqlDbType.TinyInt, Value = base.Store.InstanceEncodingOption });
parameters.Add(new SqlParameter { ParameterName = "@concatenatedKeyProperties", SqlDbType = SqlDbType.VarBinary, Value = (object) concatenatedKeyProperties ?? DBNull.Value });
parameters.Add(new SqlParameter { ParameterName = "@operationTimeout", SqlDbType = SqlDbType.Int, Value = (operationTimeout < Int32.MaxValue) ? Convert.ToInt32(operationTimeout) : Int32.MaxValue });
parameters.Add(new SqlParameter { ParameterName = "@singleKeyId", SqlDbType = SqlDbType.UniqueIdentifier, Value = singleKeyToAssociate ? keysToAssociate[0].KeyId : (object) DBNull.Value });
}
protected override void GenerateSqlCommand(SqlCommand command)
{
LoadWorkflowCommand loadWorkflowCommand = base.InstancePersistenceCommand as LoadWorkflowCommand;
LoadType loadType = loadWorkflowCommand.AcceptUninitializedInstance ? LoadType.LoadOrCreateByInstance : LoadType.LoadByInstance;
Guid instanceId = base.InstancePersistenceContext.InstanceView.InstanceId;
GenerateLoadSqlCommand(command, loadType, Guid.Empty, instanceId, null);
}
protected override string GetSqlCommandText()
{
return LoadWorkflowAsyncResult.commandText;
}
protected override CommandType GetSqlCommandType()
{
return CommandType.StoredProcedure;
}
protected override Exception ProcessSqlResult(SqlDataReader reader)
{
Exception exception = StoreUtilities.GetNextResultSet(base.InstancePersistenceCommand.Name, reader);
if (exception == null)
{
Guid instanceId = reader.GetGuid(1);
long surrogateInstanceId = reader.GetInt64(2);
byte[] primitiveProperties = reader.IsDBNull(3) ? null : (byte[])(reader.GetValue(3));
byte[] complexProperties = reader.IsDBNull(4) ? null : (byte[])(reader.GetValue(4));
byte[] metadataProperties = reader.IsDBNull(5) ? null : (byte[])(reader.GetValue(5));
InstanceEncodingOption dataEncodingOption = (InstanceEncodingOption)(reader.GetByte(6));
InstanceEncodingOption metadataEncodingOption = (InstanceEncodingOption)(reader.GetByte(7));
long version = reader.GetInt64(8);
bool isInitialized = reader.GetBoolean(9);
bool createdInstance = reader.GetBoolean(10);
LoadWorkflowCommand loadWorkflowCommand = base.InstancePersistenceCommand as LoadWorkflowCommand;
LoadWorkflowByInstanceKeyCommand loadByKeycommand = base.InstancePersistenceCommand as LoadWorkflowByInstanceKeyCommand;
if (!base.InstancePersistenceContext.InstanceView.IsBoundToInstance)
{
base.InstancePersistenceContext.BindInstance(instanceId);
}
if (!base.InstancePersistenceContext.InstanceView.IsBoundToInstanceOwner)
{
base.InstancePersistenceContext.BindInstanceOwner(base.StoreLock.LockOwnerId, base.StoreLock.LockOwnerId);
}
if (!base.InstancePersistenceContext.InstanceView.IsBoundToLock)
{
InstanceLockTracking instanceLockTracking = (InstanceLockTracking)(base.InstancePersistenceContext.UserContext);
instanceLockTracking.TrackStoreLock(instanceId, version, this.DependentTransaction);
base.InstancePersistenceContext.BindAcquiredLock(version);
}
this.instanceData = SerializationUtilities.DeserializePropertyBag(primitiveProperties, complexProperties, dataEncodingOption);
this.instanceMetadata = SerializationUtilities.DeserializeMetadataPropertyBag(metadataProperties, metadataEncodingOption);
if (!createdInstance)
{
ReadInstanceMetadataChanges(reader, this.instanceMetadata);
ReadKeyData(reader, this.associatedInstanceKeys, this.completedInstanceKeys);
}
else if (loadByKeycommand != null)
{
foreach (KeyValuePair<Guid, IDictionary<XName, InstanceValue>> keyEntry in loadByKeycommand.InstanceKeysToAssociate)
{
this.associatedInstanceKeys.Add(keyEntry.Key, keyEntry.Value);
}
if (!this.associatedInstanceKeys.ContainsKey(loadByKeycommand.LookupInstanceKey))
{
base.InstancePersistenceContext.AssociatedInstanceKey(loadByKeycommand.LookupInstanceKey);
this.associatedInstanceKeys.Add(loadByKeycommand.LookupInstanceKey, new Dictionary<XName, InstanceValue>());
}
}
if (loadByKeycommand != null)
{
foreach (KeyValuePair<Guid, IDictionary<XName, InstanceValue>> keyEntry in loadByKeycommand.InstanceKeysToAssociate)
{
base.InstancePersistenceContext.AssociatedInstanceKey(keyEntry.Key);
if (keyEntry.Value != null)
{
foreach (KeyValuePair<XName, InstanceValue> property in keyEntry.Value)
{
base.InstancePersistenceContext.WroteInstanceKeyMetadataValue(keyEntry.Key, property.Key, property.Value);
}
}
}
}
base.InstancePersistenceContext.LoadedInstance
(
isInitialized ? InstanceState.Initialized : InstanceState.Uninitialized,
this.instanceData,
this.instanceMetadata,
this.associatedInstanceKeys,
this.completedInstanceKeys
);
}
else if (exception is InstanceLockLostException)
{
base.InstancePersistenceContext.InstanceHandle.Free();
}
return exception;
}
void ReadInstanceMetadataChanges(SqlDataReader reader, Dictionary<XName, InstanceValue> instanceMetadata)
{
Exception exception = StoreUtilities.GetNextResultSet(base.InstancePersistenceCommand.Name, reader);
if (exception == null)
{
if (reader.IsDBNull(1))
{
return;
}
}
do
{
InstanceEncodingOption encodingOption = (InstanceEncodingOption) reader.GetByte(1);
byte[] serializedMetadataChanges = (byte[]) reader.GetValue(2);
Dictionary<XName, InstanceValue> metadataChangeSet = SerializationUtilities.DeserializeMetadataPropertyBag(serializedMetadataChanges, encodingOption);
foreach (KeyValuePair<XName, InstanceValue> metadataChange in metadataChangeSet)
{
XName xname = metadataChange.Key;
InstanceValue propertyValue = metadataChange.Value;
if (propertyValue.Value is DeletedMetadataValue)
{
instanceMetadata.Remove(xname);
}
else
{
instanceMetadata[xname] = propertyValue;
}
}
}
while (reader.Read());
}
void ReadKeyData(SqlDataReader reader, Dictionary<Guid, IDictionary<XName, InstanceValue>> associatedInstanceKeys,
Dictionary<Guid, IDictionary<XName, InstanceValue>> completedInstanceKeys)
{
Exception exception = StoreUtilities.GetNextResultSet(base.InstancePersistenceCommand.Name, reader);
if (exception == null)
{
if (reader.IsDBNull(1))
{
return;
}
do
{
Guid key = reader.GetGuid(1);
bool isAssociated = reader.GetBoolean(2);
InstanceEncodingOption encodingOption = (InstanceEncodingOption) reader.GetByte(3);
Dictionary<Guid, IDictionary<XName, InstanceValue>> destination = isAssociated ? associatedInstanceKeys : completedInstanceKeys;
if (!reader.IsDBNull(4))
{
destination[key] = SerializationUtilities.DeserializeKeyMetadata((byte[]) reader.GetValue(4), encodingOption);
}
else
{
destination[key] = new Dictionary<XName, InstanceValue>();
}
}
while (reader.Read());
}
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Monitoring.V3.Tests
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using apis = Google.Cloud.Monitoring.V3;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Moq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
/// <summary>Generated unit tests</summary>
public class GeneratedUptimeCheckServiceClientTest
{
[Fact]
public void GetUptimeCheckConfig()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
GetUptimeCheckConfigRequest expectedRequest = new GetUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.GetUptimeCheckConfig(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString();
UptimeCheckConfig response = client.GetUptimeCheckConfig(formattedName);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetUptimeCheckConfigAsync()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
GetUptimeCheckConfigRequest expectedRequest = new GetUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.GetUptimeCheckConfigAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString();
UptimeCheckConfig response = await client.GetUptimeCheckConfigAsync(formattedName);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetUptimeCheckConfig2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
GetUptimeCheckConfigRequest request = new GetUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.GetUptimeCheckConfig(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = client.GetUptimeCheckConfig(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetUptimeCheckConfigAsync2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
GetUptimeCheckConfigRequest request = new GetUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.GetUptimeCheckConfigAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = await client.GetUptimeCheckConfigAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateUptimeCheckConfig()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
CreateUptimeCheckConfigRequest expectedRequest = new CreateUptimeCheckConfigRequest
{
Parent = new ProjectName("[PROJECT]").ToString(),
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.CreateUptimeCheckConfig(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedParent = new ProjectName("[PROJECT]").ToString();
UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig();
UptimeCheckConfig response = client.CreateUptimeCheckConfig(formattedParent, uptimeCheckConfig);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateUptimeCheckConfigAsync()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
CreateUptimeCheckConfigRequest expectedRequest = new CreateUptimeCheckConfigRequest
{
Parent = new ProjectName("[PROJECT]").ToString(),
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.CreateUptimeCheckConfigAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedParent = new ProjectName("[PROJECT]").ToString();
UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig();
UptimeCheckConfig response = await client.CreateUptimeCheckConfigAsync(formattedParent, uptimeCheckConfig);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateUptimeCheckConfig2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
CreateUptimeCheckConfigRequest request = new CreateUptimeCheckConfigRequest
{
Parent = new ProjectName("[PROJECT]").ToString(),
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.CreateUptimeCheckConfig(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = client.CreateUptimeCheckConfig(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateUptimeCheckConfigAsync2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
CreateUptimeCheckConfigRequest request = new CreateUptimeCheckConfigRequest
{
Parent = new ProjectName("[PROJECT]").ToString(),
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.CreateUptimeCheckConfigAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = await client.CreateUptimeCheckConfigAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateUptimeCheckConfig()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
UpdateUptimeCheckConfigRequest expectedRequest = new UpdateUptimeCheckConfigRequest
{
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.UpdateUptimeCheckConfig(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig();
UptimeCheckConfig response = client.UpdateUptimeCheckConfig(uptimeCheckConfig);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateUptimeCheckConfigAsync()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
UpdateUptimeCheckConfigRequest expectedRequest = new UpdateUptimeCheckConfigRequest
{
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.UpdateUptimeCheckConfigAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig();
UptimeCheckConfig response = await client.UpdateUptimeCheckConfigAsync(uptimeCheckConfig);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateUptimeCheckConfig2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
UpdateUptimeCheckConfigRequest request = new UpdateUptimeCheckConfigRequest
{
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.UpdateUptimeCheckConfig(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = client.UpdateUptimeCheckConfig(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateUptimeCheckConfigAsync2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
UpdateUptimeCheckConfigRequest request = new UpdateUptimeCheckConfigRequest
{
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.UpdateUptimeCheckConfigAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = await client.UpdateUptimeCheckConfigAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteUptimeCheckConfig()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
DeleteUptimeCheckConfigRequest expectedRequest = new DeleteUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteUptimeCheckConfig(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString();
client.DeleteUptimeCheckConfig(formattedName);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteUptimeCheckConfigAsync()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
DeleteUptimeCheckConfigRequest expectedRequest = new DeleteUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteUptimeCheckConfigAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString();
await client.DeleteUptimeCheckConfigAsync(formattedName);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteUptimeCheckConfig2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
DeleteUptimeCheckConfigRequest request = new DeleteUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteUptimeCheckConfig(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteUptimeCheckConfig(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteUptimeCheckConfigAsync2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
DeleteUptimeCheckConfigRequest request = new DeleteUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteUptimeCheckConfigAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteUptimeCheckConfigAsync(request);
mockGrpcClient.VerifyAll();
}
}
}
| |
#region License
/*
* HttpConnection.cs
*
* This code is derived from HttpConnection.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <[email protected]>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <[email protected]>
*/
#endregion
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace WebSocketSharp.Net
{
internal sealed class HttpConnection
{
#region Private Fields
private byte[] _buffer;
private const int _bufferLength = 8192;
private bool _chunked;
private HttpListenerContext _context;
private bool _contextWasBound;
private StringBuilder _currentLine;
private InputState _inputState;
private RequestStream _inputStream;
private HttpListener _lastListener;
private LineState _lineState;
private EndPointListener _listener;
private ResponseStream _outputStream;
private int _position;
private HttpListenerPrefix _prefix;
private MemoryStream _requestBuffer;
private int _reuses;
private bool _secure;
private Socket _socket;
private Stream _stream;
private object _sync;
private int _timeout;
private Timer _timer;
#endregion
#region Internal Constructors
internal HttpConnection (Socket socket, EndPointListener listener)
{
_socket = socket;
_listener = listener;
_secure = listener.IsSecure;
var netStream = new NetworkStream (socket, false);
if (_secure) {
var conf = listener.SslConfiguration;
var sslStream = new SslStream (netStream, false, conf.ClientCertificateValidationCallback);
sslStream.AuthenticateAsServer (
conf.ServerCertificate,
conf.ClientCertificateRequired,
conf.EnabledSslProtocols,
conf.CheckCertificateRevocation);
_stream = sslStream;
}
else {
_stream = netStream;
}
_sync = new object ();
_timeout = 90000; // 90k ms for first request, 15k ms from then on.
_timer = new Timer (onTimeout, this, Timeout.Infinite, Timeout.Infinite);
init ();
}
#endregion
#region Public Properties
public bool IsClosed {
get {
return _socket == null;
}
}
public bool IsSecure {
get {
return _secure;
}
}
public IPEndPoint LocalEndPoint {
get {
return (IPEndPoint) _socket.LocalEndPoint;
}
}
public HttpListenerPrefix Prefix {
get {
return _prefix;
}
set {
_prefix = value;
}
}
public IPEndPoint RemoteEndPoint {
get {
return (IPEndPoint) _socket.RemoteEndPoint;
}
}
public int Reuses {
get {
return _reuses;
}
}
public Stream Stream {
get {
return _stream;
}
}
#endregion
#region Private Methods
private void close ()
{
lock (_sync) {
if (_socket == null)
return;
disposeTimer ();
disposeRequestBuffer ();
disposeStream ();
closeSocket ();
}
unbind ();
removeConnection ();
}
private void closeSocket ()
{
try {
_socket.Shutdown (SocketShutdown.Both);
}
catch {
}
_socket.Close ();
_socket = null;
}
private void disposeRequestBuffer ()
{
if (_requestBuffer == null)
return;
_requestBuffer.Dispose ();
_requestBuffer = null;
}
private void disposeStream ()
{
if (_stream == null)
return;
_inputStream = null;
_outputStream = null;
_stream.Dispose ();
_stream = null;
}
private void disposeTimer ()
{
if (_timer == null)
return;
try {
_timer.Change (Timeout.Infinite, Timeout.Infinite);
}
catch {
}
_timer.Dispose ();
_timer = null;
}
private void init ()
{
_chunked = false;
_context = new HttpListenerContext (this);
_inputState = InputState.RequestLine;
_inputStream = null;
_lineState = LineState.None;
_outputStream = null;
_position = 0;
_prefix = null;
_requestBuffer = new MemoryStream ();
}
private static void onRead (IAsyncResult asyncResult)
{
var conn = (HttpConnection) asyncResult.AsyncState;
if (conn._socket == null)
return;
lock (conn._sync) {
if (conn._socket == null)
return;
var nread = -1;
var len = 0;
try {
conn._timer.Change (Timeout.Infinite, Timeout.Infinite);
nread = conn._stream.EndRead (asyncResult);
conn._requestBuffer.Write (conn._buffer, 0, nread);
len = (int) conn._requestBuffer.Length;
}
catch (Exception ex) {
if (conn._requestBuffer != null && conn._requestBuffer.Length > 0)
conn.SendError (ex.Message, 400);
conn.close ();
return;
}
if (nread <= 0) {
conn.close ();
return;
}
if (conn.processInput (conn._requestBuffer.GetBuffer (), len)) {
if (!conn._context.HasError)
conn._context.Request.FinishInitialization ();
if (conn._context.HasError) {
conn.SendError ();
conn.Close (true);
return;
}
if (!conn._listener.BindContext (conn._context)) {
conn.SendError ("Invalid host", 400);
conn.Close (true);
return;
}
var lsnr = conn._context.Listener;
if (conn._lastListener != lsnr) {
conn.removeConnection ();
lsnr.AddConnection (conn);
conn._lastListener = lsnr;
}
conn._contextWasBound = true;
lsnr.RegisterContext (conn._context);
return;
}
conn._stream.BeginRead (conn._buffer, 0, _bufferLength, onRead, conn);
}
}
private static void onTimeout (object state)
{
var conn = (HttpConnection) state;
conn.close ();
}
// true -> Done processing.
// false -> Need more input.
private bool processInput (byte[] data, int length)
{
if (_currentLine == null)
_currentLine = new StringBuilder (64);
var nread = 0;
try {
string line;
while ((line = readLineFrom (data, _position, length, out nread)) != null) {
_position += nread;
if (line.Length == 0) {
if (_inputState == InputState.RequestLine)
continue;
if (_position > 32768)
_context.ErrorMessage = "Bad request";
_currentLine = null;
return true;
}
if (_inputState == InputState.RequestLine) {
_context.Request.SetRequestLine (line);
_inputState = InputState.Headers;
}
else {
_context.Request.AddHeader (line);
}
if (_context.HasError)
return true;
}
}
catch (Exception ex) {
_context.ErrorMessage = ex.Message;
return true;
}
_position += nread;
if (_position >= 32768) {
_context.ErrorMessage = "Bad request";
return true;
}
return false;
}
private string readLineFrom (byte[] buffer, int offset, int length, out int read)
{
read = 0;
for (var i = offset; i < length && _lineState != LineState.Lf; i++) {
read++;
var b = buffer[i];
if (b == 13)
_lineState = LineState.Cr;
else if (b == 10)
_lineState = LineState.Lf;
else
_currentLine.Append ((char) b);
}
if (_lineState == LineState.Lf) {
_lineState = LineState.None;
var line = _currentLine.ToString ();
_currentLine.Length = 0;
return line;
}
return null;
}
private void removeConnection ()
{
if (_lastListener != null)
_lastListener.RemoveConnection (this);
else
_listener.RemoveConnection (this);
}
private void unbind ()
{
if (!_contextWasBound)
return;
_listener.UnbindContext (_context);
_contextWasBound = false;
}
#endregion
#region Internal Methods
internal void Close (bool force)
{
if (_socket == null)
return;
lock (_sync) {
if (_socket == null)
return;
if (!force) {
GetResponseStream ().Close (false);
var req = _context.Request;
var res = _context.Response;
if (req.KeepAlive &&
!res.CloseConnection &&
req.FlushInput () &&
(!_chunked || (_chunked && !res.ForceCloseChunked))) {
// Don't close. Keep working.
_reuses++;
disposeRequestBuffer ();
unbind ();
init ();
BeginReadRequest ();
return;
}
}
else if (_outputStream != null) {
_outputStream.Close (true);
}
close ();
}
}
#endregion
#region Public Methods
public void BeginReadRequest ()
{
if (_buffer == null)
_buffer = new byte[_bufferLength];
if (_reuses == 1)
_timeout = 15000;
try {
_timer.Change (_timeout, Timeout.Infinite);
_stream.BeginRead (_buffer, 0, _bufferLength, onRead, this);
}
catch {
close ();
}
}
public void Close ()
{
Close (false);
}
public RequestStream GetRequestStream (long contentLength, bool chunked)
{
if (_inputStream != null || _socket == null)
return _inputStream;
lock (_sync) {
if (_socket == null)
return _inputStream;
var buff = _requestBuffer.GetBuffer ();
var len = (int) _requestBuffer.Length;
disposeRequestBuffer ();
if (chunked) {
_chunked = true;
_context.Response.SendChunked = true;
_inputStream = new ChunkedRequestStream (
_stream, buff, _position, len - _position, _context);
}
else {
_inputStream = new RequestStream (
_stream, buff, _position, len - _position, contentLength);
}
return _inputStream;
}
}
public ResponseStream GetResponseStream ()
{
// TODO: Can we get this stream before reading the input?
if (_outputStream != null || _socket == null)
return _outputStream;
lock (_sync) {
if (_socket == null)
return _outputStream;
var lsnr = _context.Listener;
var ignore = lsnr != null ? lsnr.IgnoreWriteExceptions : true;
_outputStream = new ResponseStream (_stream, _context.Response, ignore);
return _outputStream;
}
}
public void SendError ()
{
SendError (_context.ErrorMessage, _context.ErrorStatus);
}
public void SendError (string message, int status)
{
if (_socket == null)
return;
lock (_sync) {
if (_socket == null)
return;
try {
var res = _context.Response;
res.StatusCode = status;
res.ContentType = "text/html";
var desc = status.GetStatusDescription ();
var msg = message != null && message.Length > 0
? String.Format ("<h1>{0} ({1})</h1>", desc, message)
: String.Format ("<h1>{0}</h1>", desc);
var entity = res.ContentEncoding.GetBytes (msg);
res.Close (entity, false);
}
catch {
// Response was already closed.
}
}
}
#endregion
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Runtime.InteropServices;
using Avalonia.Cairo.Media.Imaging;
using Avalonia.Media;
namespace Avalonia.Cairo.Media
{
using Avalonia.Media.Imaging;
using Cairo = global::Cairo;
/// <summary>
/// Draws using Cairo.
/// </summary>
public class DrawingContext : IDrawingContextImpl, IDisposable
{
/// <summary>
/// The cairo context.
/// </summary>
private readonly Cairo.Context _context;
private readonly Stack<BrushImpl> _maskStack = new Stack<BrushImpl>();
/// <summary>
/// Initializes a new instance of the <see cref="DrawingContext"/> class.
/// </summary>
/// <param name="surface">The target surface.</param>
public DrawingContext(Cairo.Surface surface)
{
_context = new Cairo.Context(surface);
}
/// <summary>
/// Initializes a new instance of the <see cref="DrawingContext"/> class.
/// </summary>
/// <param name="surface">The GDK drawable.</param>
public DrawingContext(Gdk.Drawable drawable)
{
_context = Gdk.CairoHelper.Create(drawable);
}
private Matrix _transform = Matrix.Identity;
/// <summary>
/// Gets the current transform of the drawing context.
/// </summary>
public Matrix Transform
{
get { return _transform; }
set
{
_transform = value;
_context.Matrix = value.ToCairo();
}
}
/// <summary>
/// Ends a draw operation.
/// </summary>
public void Dispose()
{
_context.Dispose();
}
/// <summary>
/// Draws a bitmap image.
/// </summary>
/// <param name="source">The bitmap image.</param>
/// <param name="opacity">The opacity to draw with.</param>
/// <param name="sourceRect">The rect in the image to draw.</param>
/// <param name="destRect">The rect in the output to draw to.</param>
public void DrawImage(IBitmap bitmap, double opacity, Rect sourceRect, Rect destRect)
{
var impl = bitmap.PlatformImpl as BitmapImpl;
var size = new Size(impl.PixelWidth, impl.PixelHeight);
var scale = new Vector(destRect.Width / sourceRect.Width, destRect.Height / sourceRect.Height);
_context.Save();
_context.Scale(scale.X, scale.Y);
destRect /= scale;
if (opacityOverride < 1.0f) {
_context.PushGroup ();
Gdk.CairoHelper.SetSourcePixbuf (
_context,
impl,
-sourceRect.X + destRect.X,
-sourceRect.Y + destRect.Y);
_context.Rectangle (destRect.ToCairo ());
_context.Fill ();
_context.PopGroupToSource ();
_context.PaintWithAlpha (opacityOverride);
} else {
_context.PushGroup ();
Gdk.CairoHelper.SetSourcePixbuf (
_context,
impl,
-sourceRect.X + destRect.X,
-sourceRect.Y + destRect.Y);
_context.Rectangle (destRect.ToCairo ());
_context.Fill ();
_context.PopGroupToSource ();
_context.PaintWithAlpha (opacityOverride);
}
_context.Restore();
}
/// <summary>
/// Draws a line.
/// </summary>
/// <param name="pen">The stroke pen.</param>
/// <param name="p1">The first point of the line.</param>
/// <param name="p1">The second point of the line.</param>
public void DrawLine(Pen pen, Point p1, Point p2)
{
var size = new Rect(p1, p2).Size;
using (var p = SetPen(pen, size))
{
_context.MoveTo(p1.ToCairo());
_context.LineTo(p2.ToCairo());
_context.Stroke();
}
}
/// <summary>
/// Draws a geometry.
/// </summary>
/// <param name="brush">The fill brush.</param>
/// <param name="pen">The stroke pen.</param>
/// <param name="geometry">The geometry.</param>
public void DrawGeometry(IBrush brush, Pen pen, Geometry geometry)
{
var impl = geometry.PlatformImpl as StreamGeometryImpl;
var oldMatrix = Transform;
Transform = impl.Transform * Transform;
if (brush != null)
{
_context.AppendPath(impl.Path);
using (var b = SetBrush(brush, geometry.Bounds.Size))
{
_context.FillRule = impl.FillRule == FillRule.EvenOdd
? Cairo.FillRule.EvenOdd
: Cairo.FillRule.Winding;
if (pen != null)
_context.FillPreserve();
else
_context.Fill();
}
}
Transform = oldMatrix;
if (pen != null)
{
_context.AppendPath(impl.Path);
using (var p = SetPen(pen, geometry.Bounds.Size))
{
_context.Stroke();
}
}
}
/// <summary>
/// Draws the outline of a rectangle.
/// </summary>
/// <param name="pen">The pen.</param>
/// <param name="rect">The rectangle bounds.</param>
public void DrawRectangle(Pen pen, Rect rect, float cornerRadius)
{
using (var p = SetPen(pen, rect.Size))
{
_context.Rectangle(rect.ToCairo ());
_context.Stroke();
}
}
/// <summary>
/// Draws text.
/// </summary>
/// <param name="foreground">The foreground brush.</param>
/// <param name="origin">The upper-left corner of the text.</param>
/// <param name="text">The text.</param>
public void DrawText(IBrush foreground, Point origin, FormattedText text)
{
var layout = ((FormattedTextImpl)text.PlatformImpl).Layout;
_context.MoveTo(origin.X, origin.Y);
using (var b = SetBrush(foreground, new Size(0, 0)))
{
Pango.CairoHelper.ShowLayout(_context, layout);
}
}
/// <summary>
/// Draws a filled rectangle.
/// </summary>
/// <param name="brush">The brush.</param>
/// <param name="rect">The rectangle bounds.</param>
public void FillRectangle(IBrush brush, Rect rect, float cornerRadius)
{
using (var b = SetBrush(brush, rect.Size))
{
_context.Rectangle(rect.ToCairo ());
_context.Fill();
}
}
/// <summary>
/// Pushes a clip rectange.
/// </summary>
/// <param name="clip">The clip rectangle.</param>
/// <returns>A disposable used to undo the clip rectangle.</returns>
public void PushClip(Rect clip)
{
_context.Save();
_context.Rectangle(clip.ToCairo());
_context.Clip();
}
public void PopClip()
{
_context.Restore();
}
readonly Stack<double> _opacityStack = new Stack<double>();
/// <summary>
/// Pushes an opacity value.
/// </summary>
/// <param name="opacity">The opacity.</param>
/// <returns>A disposable used to undo the opacity.</returns>
public void PushOpacity(double opacity)
{
_opacityStack.Push(opacityOverride);
if (opacity < 1.0f)
opacityOverride *= opacity;
}
public void PopOpacity()
{
opacityOverride = _opacityStack.Pop();
}
/// <summary>
/// Pushes a matrix transformation.
/// </summary>
/// <param name="matrix">The matrix</param>
/// <returns>A disposable used to undo the transformation.</returns>
public IDisposable PushTransform(Matrix matrix)
{
_context.Save();
_context.Transform(matrix.ToCairo());
return Disposable.Create(() =>
{
_context.Restore();
});
}
private double opacityOverride = 1.0f;
private IDisposable SetBrush(IBrush brush, Size destinationSize)
{
_context.Save();
BrushImpl impl = CreateBrushImpl(brush, destinationSize);
_context.SetSource(impl.PlatformBrush);
return Disposable.Create(() =>
{
impl.Dispose();
_context.Restore();
});
}
private BrushImpl CreateBrushImpl(IBrush brush, Size destinationSize)
{
var solid = brush as SolidColorBrush;
var linearGradientBrush = brush as LinearGradientBrush;
var radialGradientBrush = brush as RadialGradientBrush;
var imageBrush = brush as ImageBrush;
var visualBrush = brush as VisualBrush;
BrushImpl impl = null;
if (solid != null)
{
impl = new SolidColorBrushImpl(solid, opacityOverride);
}
else if (linearGradientBrush != null)
{
impl = new LinearGradientBrushImpl(linearGradientBrush, destinationSize);
}
else if (radialGradientBrush != null)
{
impl = new RadialGradientBrushImpl(radialGradientBrush, destinationSize);
}
else if (imageBrush != null)
{
impl = new ImageBrushImpl(imageBrush, destinationSize);
}
else if (visualBrush != null)
{
impl = new VisualBrushImpl(visualBrush, destinationSize);
}
else
{
impl = new SolidColorBrushImpl(null, opacityOverride);
}
return impl;
}
private IDisposable SetPen(Pen pen, Size destinationSize)
{
if (pen.DashStyle != null)
{
if (pen.DashStyle.Dashes != null && pen.DashStyle.Dashes.Count > 0)
{
var cray = pen.DashStyle.Dashes.ToArray();
_context.SetDash(cray, pen.DashStyle.Offset);
}
}
_context.LineWidth = pen.Thickness;
_context.MiterLimit = pen.MiterLimit;
// Line caps and joins are currently broken on Cairo. I've defaulted them to sensible defaults for now.
// Cairo does not have StartLineCap, EndLineCap, and DashCap properties, whereas Direct2D does.
// TODO: Figure out a solution for this.
_context.LineJoin = Cairo.LineJoin.Miter;
_context.LineCap = Cairo.LineCap.Butt;
if (pen.Brush == null)
return Disposable.Empty;
return SetBrush(pen.Brush, destinationSize);
}
public void PushGeometryClip(Geometry clip)
{
_context.Save();
_context.AppendPath(((StreamGeometryImpl)clip.PlatformImpl).Path);
_context.Clip();
}
public void PopGeometryClip()
{
_context.Restore();
}
public void PushOpacityMask(IBrush mask, Rect bounds)
{
_context.PushGroup();
var impl = CreateBrushImpl(mask, bounds.Size);
_maskStack.Push(impl);
}
public void PopOpacityMask()
{
_context.PopGroupToSource();
var brushImpl = _maskStack.Pop ();
_context.Mask(brushImpl.PlatformBrush);
brushImpl.Dispose ();
}
}
}
| |
//
// 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.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.WebSitesExtensions;
using Microsoft.WindowsAzure.WebSitesExtensions.Models;
namespace Microsoft.WindowsAzure
{
/// <summary>
/// The websites extensions client manages the web sites deployments, web
/// jobs and other extensions.
/// </summary>
public static partial class ContinuousWebJobOperationsExtensions
{
/// <summary>
/// Delete a continuous job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Delete(this IContinuousWebJobOperations operations, string jobName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContinuousWebJobOperations)s).DeleteAsync(jobName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a continuous job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> DeleteAsync(this IContinuousWebJobOperations operations, string jobName)
{
return operations.DeleteAsync(jobName, CancellationToken.None);
}
/// <summary>
/// Get a continuous WebJob.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <returns>
/// The get continuous WebJob Operation Response.
/// </returns>
public static ContinuousWebJobGetResponse Get(this IContinuousWebJobOperations operations, string jobName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContinuousWebJobOperations)s).GetAsync(jobName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a continuous WebJob.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <returns>
/// The get continuous WebJob Operation Response.
/// </returns>
public static Task<ContinuousWebJobGetResponse> GetAsync(this IContinuousWebJobOperations operations, string jobName)
{
return operations.GetAsync(jobName, CancellationToken.None);
}
/// <summary>
/// Get the settings of a continuous WebJob.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <returns>
/// The continuous WebJob settings operation response.
/// </returns>
public static ContinuousWebJobSettingsResponse GetSettings(this IContinuousWebJobOperations operations, string jobName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContinuousWebJobOperations)s).GetSettingsAsync(jobName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the settings of a continuous WebJob.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <returns>
/// The continuous WebJob settings operation response.
/// </returns>
public static Task<ContinuousWebJobSettingsResponse> GetSettingsAsync(this IContinuousWebJobOperations operations, string jobName)
{
return operations.GetSettingsAsync(jobName, CancellationToken.None);
}
/// <summary>
/// List the continuous web jobs.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <returns>
/// The list of continuous WebJobs operation response.
/// </returns>
public static ContinuousWebJobListResponse List(this IContinuousWebJobOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContinuousWebJobOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List the continuous web jobs.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <returns>
/// The list of continuous WebJobs operation response.
/// </returns>
public static Task<ContinuousWebJobListResponse> ListAsync(this IContinuousWebJobOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
/// <summary>
/// Set the settings of a continuous WebJob (will replace the current
/// settings of the WebJob).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <param name='settings'>
/// Required. The continuous WebJob settings.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse SetSettings(this IContinuousWebJobOperations operations, string jobName, ContinuousWebJobSettingsUpdateParameters settings)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContinuousWebJobOperations)s).SetSettingsAsync(jobName, settings);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Set the settings of a continuous WebJob (will replace the current
/// settings of the WebJob).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <param name='settings'>
/// Required. The continuous WebJob settings.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> SetSettingsAsync(this IContinuousWebJobOperations operations, string jobName, ContinuousWebJobSettingsUpdateParameters settings)
{
return operations.SetSettingsAsync(jobName, settings, CancellationToken.None);
}
/// <summary>
/// Start a continuous WebJob.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The WebJob name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Start(this IContinuousWebJobOperations operations, string jobName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContinuousWebJobOperations)s).StartAsync(jobName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Start a continuous WebJob.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The WebJob name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> StartAsync(this IContinuousWebJobOperations operations, string jobName)
{
return operations.StartAsync(jobName, CancellationToken.None);
}
/// <summary>
/// Stop a continuous WebJob.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The WebJob name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Stop(this IContinuousWebJobOperations operations, string jobName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContinuousWebJobOperations)s).StopAsync(jobName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Stop a continuous WebJob.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The WebJob name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> StopAsync(this IContinuousWebJobOperations operations, string jobName)
{
return operations.StopAsync(jobName, CancellationToken.None);
}
/// <summary>
/// Create or replace a continuous WebJob with a script file (.exe,
/// .bat, .php, .js...).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <param name='fileName'>
/// Required. The file name.
/// </param>
/// <param name='jobContent'>
/// Required. The file content.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse UploadFile(this IContinuousWebJobOperations operations, string jobName, string fileName, Stream jobContent)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContinuousWebJobOperations)s).UploadFileAsync(jobName, fileName, jobContent);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace a continuous WebJob with a script file (.exe,
/// .bat, .php, .js...).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <param name='fileName'>
/// Required. The file name.
/// </param>
/// <param name='jobContent'>
/// Required. The file content.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> UploadFileAsync(this IContinuousWebJobOperations operations, string jobName, string fileName, Stream jobContent)
{
return operations.UploadFileAsync(jobName, fileName, jobContent, CancellationToken.None);
}
/// <summary>
/// Create or replace a continuous WebJob with a zip file (containing
/// the WebJob binaries).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <param name='fileName'>
/// Required. The zip file name.
/// </param>
/// <param name='jobContent'>
/// Required. The zip file content.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse UploadZip(this IContinuousWebJobOperations operations, string jobName, string fileName, Stream jobContent)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContinuousWebJobOperations)s).UploadZipAsync(jobName, fileName, jobContent);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace a continuous WebJob with a zip file (containing
/// the WebJob binaries).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations.
/// </param>
/// <param name='jobName'>
/// Required. The continuous WebJob name.
/// </param>
/// <param name='fileName'>
/// Required. The zip file name.
/// </param>
/// <param name='jobContent'>
/// Required. The zip file content.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> UploadZipAsync(this IContinuousWebJobOperations operations, string jobName, string fileName, Stream jobContent)
{
return operations.UploadZipAsync(jobName, fileName, jobContent, CancellationToken.None);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Agent.Sdk;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
using Microsoft.VisualStudio.Services.Agent.Util;
namespace Agent.Plugins.Repository
{
public class SvnCliManager
{
/// <summary>
/// Initializes svn command path and execution environment
/// </summary>
/// <param name="context">The build commands' execution context</param>
/// <param name="endpoint">The Subversion server endpoint providing URL, username/password, and untrasted certs acceptace information</param>
/// <param name="cancellationToken">The cancellation token used to stop svn command execution</param>
public void Init(
AgentTaskPluginExecutionContext context,
Pipelines.RepositoryResource repository,
CancellationToken cancellationToken)
{
// Validation.
ArgUtil.NotNull(context, nameof(context));
ArgUtil.NotNull(repository, nameof(repository));
ArgUtil.NotNull(cancellationToken, nameof(cancellationToken));
ArgUtil.NotNull(repository.Url, nameof(repository.Url));
ArgUtil.Equal(true, repository.Url.IsAbsoluteUri, nameof(repository.Url.IsAbsoluteUri));
ArgUtil.NotNull(repository.Endpoint, nameof(repository.Endpoint));
ServiceEndpoint endpoint = context.Endpoints.Single(
x => (repository.Endpoint.Id != Guid.Empty && x.Id == repository.Endpoint.Id) ||
(repository.Endpoint.Id == Guid.Empty && string.Equals(x.Name, repository.Endpoint.Name.ToString(), StringComparison.OrdinalIgnoreCase)));
ArgUtil.NotNull(endpoint.Data, nameof(endpoint.Data));
ArgUtil.NotNull(endpoint.Authorization, nameof(endpoint.Authorization));
ArgUtil.NotNull(endpoint.Authorization.Parameters, nameof(endpoint.Authorization.Parameters));
ArgUtil.Equal(EndpointAuthorizationSchemes.UsernamePassword, endpoint.Authorization.Scheme, nameof(endpoint.Authorization.Scheme));
_context = context;
_repository = repository;
_cancellationToken = cancellationToken;
// Find svn in %Path%
string svnPath = WhichUtil.Which("svn", trace: context);
if (string.IsNullOrEmpty(svnPath))
{
throw new Exception(StringUtil.Loc("SvnNotInstalled"));
}
else
{
_context.Debug($"Found svn installation path: {svnPath}.");
_svn = svnPath;
}
// External providers may need basic auth or tokens
endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Username, out _username);
endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Password, out _password);
if (endpoint.Data.TryGetValue(EndpointData.AcceptUntrustedCertificates, out string endpointAcceptUntrustedCerts))
{
_acceptUntrusted = StringUtil.ConvertToBoolean(endpointAcceptUntrustedCerts);
}
_acceptUntrusted = _acceptUntrusted || (context.GetCertConfiguration()?.SkipServerCertificateValidation ?? false);
}
/// <summary>
/// Detects old mappings (if any) and refreshes the SVN working copies to match the new mappings.
/// </summary>
/// <param name="rootPath"></param>
/// <param name="distinctMappings"></param>
/// <param name="cleanRepository"></param>
/// <param name="sourceBranch"></param>
/// <param name="revision"></param>
/// <returns></returns>
public async Task<string> UpdateWorkspace(
string rootPath,
Dictionary<string, SvnMappingDetails> distinctMappings,
bool cleanRepository,
string sourceBranch,
string revision)
{
if (cleanRepository)
{
// A clean build has been requested
IOUtil.DeleteDirectory(rootPath, _cancellationToken);
Directory.CreateDirectory(rootPath);
}
Dictionary<string, Uri> oldMappings = await GetOldMappings(rootPath);
_context.Debug($"oldMappings.Count: {oldMappings.Count}");
oldMappings.ToList().ForEach(p => _context.Debug($" [{p.Key}] {p.Value}"));
Dictionary<string, SvnMappingDetails> newMappings = BuildNewMappings(rootPath, sourceBranch, distinctMappings);
_context.Debug($"newMappings.Count: {newMappings.Count}");
newMappings.ToList().ForEach(p => _context.Debug($" [{p.Key}] ServerPath: {p.Value.ServerPath}, LocalPath: {p.Value.LocalPath}, Depth: {p.Value.Depth}, Revision: {p.Value.Revision}, IgnoreExternals: {p.Value.IgnoreExternals}"));
CleanUpSvnWorkspace(oldMappings, newMappings);
long maxRevision = 0;
foreach (SvnMappingDetails mapping in newMappings.Values)
{
long mappingRevision = await GetLatestRevisionAsync(mapping.ServerPath, revision);
if (mappingRevision > maxRevision)
{
maxRevision = mappingRevision;
}
}
await UpdateToRevisionAsync(oldMappings, newMappings, maxRevision);
return maxRevision > 0 ? maxRevision.ToString() : "HEAD";
}
private async Task<Dictionary<string, Uri>> GetOldMappings(string rootPath)
{
if (File.Exists(rootPath))
{
throw new Exception(StringUtil.Loc("SvnFileAlreadyExists", rootPath));
}
Dictionary<string, Uri> mappings = new Dictionary<string, Uri>();
if (Directory.Exists(rootPath))
{
foreach (string workingDirectoryPath in GetSvnWorkingCopyPaths(rootPath))
{
Uri url = await GetRootUrlAsync(workingDirectoryPath);
if (url != null)
{
mappings.Add(workingDirectoryPath, url);
}
}
}
return mappings;
}
private List<string> GetSvnWorkingCopyPaths(string rootPath)
{
if (Directory.Exists(Path.Combine(rootPath, ".svn")))
{
return new List<string>() { rootPath };
}
else
{
ConcurrentStack<string> candidates = new ConcurrentStack<string>();
Directory.EnumerateDirectories(rootPath, "*", SearchOption.TopDirectoryOnly)
.AsParallel()
.ForAll(fld => candidates.PushRange(GetSvnWorkingCopyPaths(fld).ToArray()));
return candidates.ToList();
}
}
private Dictionary<string, SvnMappingDetails> BuildNewMappings(string rootPath, string sourceBranch, Dictionary<string, SvnMappingDetails> distinctMappings)
{
Dictionary<string, SvnMappingDetails> mappings = new Dictionary<string, SvnMappingDetails>();
if (distinctMappings != null && distinctMappings.Count > 0)
{
foreach (KeyValuePair<string, SvnMappingDetails> mapping in distinctMappings)
{
SvnMappingDetails mappingDetails = mapping.Value;
string localPath = mappingDetails.LocalPath;
string absoluteLocalPath = Path.Combine(rootPath, localPath);
SvnMappingDetails newMappingDetails = new SvnMappingDetails();
newMappingDetails.ServerPath = mappingDetails.ServerPath;
newMappingDetails.LocalPath = absoluteLocalPath;
newMappingDetails.Revision = mappingDetails.Revision;
newMappingDetails.Depth = mappingDetails.Depth;
newMappingDetails.IgnoreExternals = mappingDetails.IgnoreExternals;
mappings.Add(absoluteLocalPath, newMappingDetails);
}
}
else
{
SvnMappingDetails newMappingDetails = new SvnMappingDetails();
newMappingDetails.ServerPath = sourceBranch;
newMappingDetails.LocalPath = rootPath;
newMappingDetails.Revision = "HEAD";
newMappingDetails.Depth = 3; //Infinity
newMappingDetails.IgnoreExternals = true;
mappings.Add(rootPath, newMappingDetails);
}
return mappings;
}
/// <summary>
/// svn info URL --depth empty --revision <sourceRevision> --xml --username <user> --password <password> --non-interactive [--trust-server-cert]
/// </summary>
/// <param name="serverPath"></param>
/// <param name="sourceRevision"></param>
/// <returns></returns>
public async Task<long> GetLatestRevisionAsync(string serverPath, string sourceRevision)
{
_context.Debug($@"Get latest revision of: '{_repository.Url.AbsoluteUri}' at or before: '{sourceRevision}'.");
string xml = await RunPorcelainCommandAsync(
"info",
BuildSvnUri(serverPath),
"--depth", "empty",
"--revision", sourceRevision,
"--xml");
// Deserialize the XML.
// The command returns a non-zero exit code if the source revision is not found.
// The assertions performed here should never fail.
XmlSerializer serializer = new XmlSerializer(typeof(SvnInfo));
ArgUtil.NotNullOrEmpty(xml, nameof(xml));
using (StringReader reader = new StringReader(xml))
{
SvnInfo info = serializer.Deserialize(reader) as SvnInfo;
ArgUtil.NotNull(info, nameof(info));
ArgUtil.NotNull(info.Entries, nameof(info.Entries));
ArgUtil.Equal(1, info.Entries.Length, nameof(info.Entries.Length));
long revision = 0;
long.TryParse(info.Entries[0].Commit?.Revision ?? sourceRevision, out revision);
return revision;
}
}
/// <summary>
/// Finds a local path the provided server path is mapped to.
/// </summary>
/// <param name="serverPath"></param>
/// <param name="rootPath"></param>
/// <returns></returns>
public string ResolveServerPath(string serverPath, string rootPath)
{
ArgUtil.Equal(true, serverPath.StartsWith(@"^/"), nameof(serverPath));
foreach (string workingDirectoryPath in GetSvnWorkingCopyPaths(rootPath))
{
try
{
_context.Debug($@"Get SVN info for the working directory path '{workingDirectoryPath}'.");
string xml = RunPorcelainCommandAsync(
"info",
workingDirectoryPath,
"--depth", "empty",
"--xml").GetAwaiter().GetResult();
// Deserialize the XML.
// The command returns a non-zero exit code if the local path is not a working copy.
// The assertions performed here should never fail.
XmlSerializer serializer = new XmlSerializer(typeof(SvnInfo));
ArgUtil.NotNullOrEmpty(xml, nameof(xml));
using (StringReader reader = new StringReader(xml))
{
SvnInfo info = serializer.Deserialize(reader) as SvnInfo;
ArgUtil.NotNull(info, nameof(info));
ArgUtil.NotNull(info.Entries, nameof(info.Entries));
ArgUtil.Equal(1, info.Entries.Length, nameof(info.Entries.Length));
if (serverPath.Equals(info.Entries[0].RelativeUrl, StringComparison.Ordinal) || serverPath.StartsWith(info.Entries[0].RelativeUrl + '/', StringComparison.Ordinal))
{
// We've found the mapping the serverPath belongs to.
int n = info.Entries[0].RelativeUrl.Length;
string relativePath = serverPath.Length <= n + 1 ? string.Empty : serverPath.Substring(n + 1);
return Path.Combine(workingDirectoryPath, relativePath);
}
}
}
catch (ProcessExitCodeException)
{
_context.Debug($@"The path '{workingDirectoryPath}' is not an SVN working directory path.");
}
}
_context.Debug($@"Haven't found any suitable mapping for '{serverPath}'");
// Since the server path starts with the "^/" prefix we return the original path without these two characters.
return serverPath.Substring(2);
}
private async Task<Uri> GetRootUrlAsync(string localPath)
{
_context.Debug($@"Get URL for: '{localPath}'.");
try
{
string xml = await RunPorcelainCommandAsync(
"info",
localPath,
"--depth", "empty",
"--xml");
// Deserialize the XML.
// The command returns a non-zero exit code if the local path is not a working copy.
// The assertions performed here should never fail.
XmlSerializer serializer = new XmlSerializer(typeof(SvnInfo));
ArgUtil.NotNullOrEmpty(xml, nameof(xml));
using (StringReader reader = new StringReader(xml))
{
SvnInfo info = serializer.Deserialize(reader) as SvnInfo;
ArgUtil.NotNull(info, nameof(info));
ArgUtil.NotNull(info.Entries, nameof(info.Entries));
ArgUtil.Equal(1, info.Entries.Length, nameof(info.Entries.Length));
return new Uri(info.Entries[0].Url);
}
}
catch (ProcessExitCodeException)
{
_context.Debug($@"The folder '{localPath}.svn' seems not to be a subversion system directory.");
return null;
}
}
private async Task UpdateToRevisionAsync(Dictionary<string, Uri> oldMappings, Dictionary<string, SvnMappingDetails> newMappings, long maxRevision)
{
foreach (KeyValuePair<string, SvnMappingDetails> mapping in newMappings)
{
string localPath = mapping.Key;
SvnMappingDetails mappingDetails = mapping.Value;
string effectiveServerUri = BuildSvnUri(mappingDetails.ServerPath);
string effectiveRevision = EffectiveRevision(mappingDetails.Revision, maxRevision);
mappingDetails.Revision = effectiveRevision;
if (!Directory.Exists(Path.Combine(localPath, ".svn")))
{
_context.Debug(String.Format(
"Checking out with depth: {0}, revision: {1}, ignore externals: {2}",
mappingDetails.Depth,
effectiveRevision,
mappingDetails.IgnoreExternals));
mappingDetails.ServerPath = effectiveServerUri;
await CheckoutAsync(mappingDetails);
}
else if (oldMappings.ContainsKey(localPath) && oldMappings[localPath].Equals(new Uri(effectiveServerUri)))
{
_context.Debug(String.Format(
"Updating with depth: {0}, revision: {1}, ignore externals: {2}",
mappingDetails.Depth,
mappingDetails.Revision,
mappingDetails.IgnoreExternals));
await UpdateAsync(mappingDetails);
}
else
{
_context.Debug(String.Format(
"Switching to {0} with depth: {1}, revision: {2}, ignore externals: {3}",
mappingDetails.ServerPath,
mappingDetails.Depth,
mappingDetails.Revision,
mappingDetails.IgnoreExternals));
await SwitchAsync(mappingDetails);
}
}
}
private string EffectiveRevision(string mappingRevision, long maxRevision)
{
if (!mappingRevision.Equals("HEAD", StringComparison.OrdinalIgnoreCase))
{
// A specific revision has been requested in mapping
return mappingRevision;
}
else if (maxRevision == 0)
{
// Tip revision
return "HEAD";
}
else
{
return maxRevision.ToString();
}
}
private void CleanUpSvnWorkspace(Dictionary<string, Uri> oldMappings, Dictionary<string, SvnMappingDetails> newMappings)
{
_context.Debug("Clean up Svn workspace.");
oldMappings.Where(m => !newMappings.ContainsKey(m.Key))
.AsParallel()
.ForAll(m =>
{
_context.Debug($@"Delete unmapped folder: '{m.Key}'");
IOUtil.DeleteDirectory(m.Key, CancellationToken.None);
});
}
/// <summary>
/// svn update localPath --depth empty --revision <sourceRevision> --xml --username lin --password ideafix --non-interactive [--trust-server-cert]
/// </summary>
/// <param name="mapping"></param>
/// <returns></returns>
private async Task UpdateAsync(SvnMappingDetails mapping)
{
_context.Debug($@"Update '{mapping.LocalPath}'.");
await RunCommandAsync(
"update",
mapping.LocalPath,
"--revision", mapping.Revision,
"--depth", ToDepthArgument(mapping.Depth),
mapping.IgnoreExternals ? "--ignore-externals" : null);
}
/// <summary>
/// svn switch localPath --depth empty --revision <sourceRevision> --xml --username lin --password ideafix --non-interactive [--trust-server-cert]
/// </summary>
/// <param name="mapping"></param>
/// <returns></returns>
private async Task SwitchAsync(SvnMappingDetails mapping)
{
_context.Debug($@"Switch '{mapping.LocalPath}' to '{mapping.ServerPath}'.");
await RunCommandAsync(
"switch",
$"^/{mapping.ServerPath}",
mapping.LocalPath,
"--ignore-ancestry",
"--revision", mapping.Revision,
"--depth", ToDepthArgument(mapping.Depth),
mapping.IgnoreExternals ? "--ignore-externals" : null);
}
/// <summary>
/// svn checkout localPath --depth empty --revision <sourceRevision> --xml --username lin --password ideafix --non-interactive [--trust-server-cert]
/// </summary>
/// <param name="mapping"></param>
/// <returns></returns>
private async Task CheckoutAsync(SvnMappingDetails mapping)
{
_context.Debug($@"Checkout '{mapping.ServerPath}' to '{mapping.LocalPath}'.");
await RunCommandAsync(
"checkout",
mapping.ServerPath,
mapping.LocalPath,
"--revision", mapping.Revision,
"--depth", ToDepthArgument(mapping.Depth),
mapping.IgnoreExternals ? "--ignore-externals" : null);
}
private string BuildSvnUri(string serverPath)
{
StringBuilder sb = new StringBuilder(_repository.Url.ToString());
if (!string.IsNullOrEmpty(serverPath))
{
if (sb[sb.Length - 1] != '/')
{
sb.Append('/');
}
sb.Append(serverPath);
}
return sb.Replace('\\', '/').ToString();
}
private string FormatArgumentsWithDefaults(params string[] args)
{
// Format each arg.
List<string> formattedArgs = new List<string>();
foreach (string arg in args ?? new string[0])
{
if (!string.IsNullOrEmpty(arg))
{
// Validate the arg.
if (arg.IndexOfAny(new char[] { '"', '\r', '\n' }) >= 0)
{
throw new Exception(StringUtil.Loc("InvalidCommandArg", arg));
}
// Add the arg.
formattedArgs.Add(QuotedArgument(arg));
}
}
// Add the common parameters.
if (_acceptUntrusted)
{
formattedArgs.Add("--trust-server-cert");
}
if (!string.IsNullOrWhiteSpace(_username))
{
formattedArgs.Add("--username");
formattedArgs.Add(QuotedArgument(_username));
}
if (!string.IsNullOrWhiteSpace(_password))
{
formattedArgs.Add("--password");
formattedArgs.Add(QuotedArgument(_password));
}
formattedArgs.Add("--no-auth-cache"); // Do not cache credentials
formattedArgs.Add("--non-interactive");
// Add proxy setting parameters
var agentProxy = _context.GetProxyConfiguration();
if (agentProxy != null && !string.IsNullOrEmpty(agentProxy.ProxyAddress) && !agentProxy.WebProxy.IsBypassed(_repository.Url))
{
_context.Debug($"Add proxy setting parameters to '{_svn}' for proxy server '{agentProxy.ProxyAddress}'.");
formattedArgs.Add("--config-option");
formattedArgs.Add(QuotedArgument($"servers:global:http-proxy-host={new Uri(agentProxy.ProxyAddress).Host}"));
formattedArgs.Add("--config-option");
formattedArgs.Add(QuotedArgument($"servers:global:http-proxy-port={new Uri(agentProxy.ProxyAddress).Port}"));
if (!string.IsNullOrEmpty(agentProxy.ProxyUsername))
{
formattedArgs.Add("--config-option");
formattedArgs.Add(QuotedArgument($"servers:global:http-proxy-username={agentProxy.ProxyUsername}"));
}
if (!string.IsNullOrEmpty(agentProxy.ProxyPassword))
{
formattedArgs.Add("--config-option");
formattedArgs.Add(QuotedArgument($"servers:global:http-proxy-password={agentProxy.ProxyPassword}"));
}
}
return string.Join(" ", formattedArgs);
}
private string QuotedArgument(string arg)
{
char quote = '\"';
char altQuote = '\'';
if (arg.IndexOf(quote) > -1)
{
quote = '\'';
altQuote = '\"';
}
return (arg.IndexOfAny(new char[] { ' ', altQuote }) == -1) ? arg : $"{quote}{arg}{quote}";
}
private string ToDepthArgument(int depth)
{
switch (depth)
{
case 0:
return "empty";
case 1:
return "files";
case 2:
return "immediates";
default:
return "infinity";
}
}
private async Task RunCommandAsync(params string[] args)
{
// Validation.
ArgUtil.NotNull(args, nameof(args));
ArgUtil.NotNull(_context, nameof(_context));
// Invoke tf.
using (var processInvoker = new ProcessInvoker(_context))
{
var outputLock = new object();
processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
{
lock (outputLock)
{
_context.Output(e.Data);
}
};
processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
{
lock (outputLock)
{
_context.Output(e.Data);
}
};
string arguments = FormatArgumentsWithDefaults(args);
_context.Command($@"{_svn} {arguments}");
await processInvoker.ExecuteAsync(
workingDirectory: _context.Variables.GetValueOrDefault("agent.workfolder")?.Value,
fileName: _svn,
arguments: arguments,
environment: null,
requireExitCodeZero: true,
cancellationToken: _cancellationToken);
}
}
private async Task<string> RunPorcelainCommandAsync(params string[] args)
{
// Validation.
ArgUtil.NotNull(args, nameof(args));
ArgUtil.NotNull(_context, nameof(_context));
// Invoke tf.
using (var processInvoker = new ProcessInvoker(_context))
{
var output = new List<string>();
var outputLock = new object();
processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
{
lock (outputLock)
{
_context.Debug(e.Data);
output.Add(e.Data);
}
};
processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
{
lock (outputLock)
{
_context.Debug(e.Data);
output.Add(e.Data);
}
};
string arguments = FormatArgumentsWithDefaults(args);
_context.Debug($@"{_svn} {arguments}");
// TODO: Test whether the output encoding needs to be specified on a non-Latin OS.
try
{
await processInvoker.ExecuteAsync(
workingDirectory: _context.Variables.GetValueOrDefault("agent.workfolder")?.Value,
fileName: _svn,
arguments: arguments,
environment: null,
requireExitCodeZero: true,
cancellationToken: _cancellationToken);
}
catch (ProcessExitCodeException)
{
// The command failed. Dump the output and throw.
output.ForEach(x => _context.Output(x ?? string.Empty));
throw;
}
// Note, string.join gracefully handles a null element within the IEnumerable<string>.
return string.Join(Environment.NewLine, output);
}
}
/// <summary>
/// Removes unused and duplicate mappings.
/// </summary>
/// <param name="allMappings"></param>
/// <returns></returns>
public Dictionary<string, SvnMappingDetails> NormalizeMappings(List<SvnMappingDetails> allMappings)
{
// We use Ordinal comparer because SVN is case sensetive and keys in the dictionary are URLs.
Dictionary<string, SvnMappingDetails> distinctMappings = new Dictionary<string, SvnMappingDetails>(StringComparer.Ordinal);
HashSet<string> localPaths = new HashSet<string>(StringComparer.Ordinal);
foreach (SvnMappingDetails map in allMappings)
{
string localPath = NormalizeRelativePath(map.LocalPath, Path.DirectorySeparatorChar, '/');
string serverPath = NormalizeRelativePath(map.ServerPath, '/', '\\');
if (string.IsNullOrEmpty(serverPath))
{
_context.Debug(StringUtil.Loc("SvnEmptyServerPath", localPath));
_context.Debug(StringUtil.Loc("SvnMappingIgnored"));
distinctMappings.Clear();
distinctMappings.Add(string.Empty, map);
break;
}
if (localPaths.Contains(localPath))
{
_context.Debug(StringUtil.Loc("SvnMappingDuplicateLocal", localPath));
continue;
}
else
{
localPaths.Add(localPath);
}
if (distinctMappings.ContainsKey(serverPath))
{
_context.Debug(StringUtil.Loc("SvnMappingDuplicateServer", serverPath));
continue;
}
// Put normalized values of the local and server paths back into the mapping.
map.LocalPath = localPath;
map.ServerPath = serverPath;
distinctMappings.Add(serverPath, map);
}
return distinctMappings;
}
/// <summary>
/// Normalizes path separator for server and local paths.
/// </summary>
/// <param name="path"></param>
/// <param name="pathSeparator"></param>
/// <param name="altPathSeparator"></param>
/// <returns></returns>
public string NormalizeRelativePath(string path, char pathSeparator, char altPathSeparator)
{
string relativePath = (path ?? string.Empty).Replace(altPathSeparator, pathSeparator);
relativePath = relativePath.Trim(pathSeparator, ' ');
if (relativePath.Contains(":") || relativePath.Contains(".."))
{
throw new Exception(StringUtil.Loc("SvnIncorrectRelativePath", relativePath));
}
return relativePath;
}
// The cancellation token used to stop svn command execution
private CancellationToken _cancellationToken;
// The Subversion repository providing URL and untrusted certs acceptace information
private Pipelines.RepositoryResource _repository;
// The build commands' execution context
private AgentTaskPluginExecutionContext _context;
// The svn command line utility location
private string _svn;
// The svn user name from SVN repository connection endpoint
private string _username;
// The svn user password from SVN repository connection endpoint
private string _password;
// The acceptUntrustedCerts property from SVN repository connection endpoint
private bool _acceptUntrusted;
}
////////////////////////////////////////////////////////////////////////////////
// svn info data objects
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "info", Namespace = "")]
public sealed class SvnInfo
{
[XmlElement(ElementName = "entry", Namespace = "")]
public SvnInfoEntry[] Entries { get; set; }
}
public sealed class SvnInfoEntry
{
[XmlAttribute(AttributeName = "kind", Namespace = "")]
public string Kind { get; set; }
[XmlAttribute(AttributeName = "path", Namespace = "")]
public string Path { get; set; }
[XmlAttribute(AttributeName = "revision", Namespace = "")]
public string Revision { get; set; }
[XmlElement(ElementName = "url", Namespace = "")]
public string Url { get; set; }
[XmlElement(ElementName = "relative-url", Namespace = "")]
public string RelativeUrl { get; set; }
[XmlElement(ElementName = "repository", Namespace = "")]
public SvnInfoRepository[] Repository { get; set; }
[XmlElement(ElementName = "wc-info", Namespace = "", IsNullable = true)]
public SvnInfoWorkingCopy[] WorkingCopyInfo { get; set; }
[XmlElement(ElementName = "commit", Namespace = "")]
public SvnInfoCommit Commit { get; set; }
}
public sealed class SvnInfoRepository
{
[XmlElement(ElementName = "wcroot-abspath", Namespace = "")]
public string AbsPath { get; set; }
[XmlElement(ElementName = "schedule", Namespace = "")]
public string Schedule { get; set; }
[XmlElement(ElementName = "depth", Namespace = "")]
public string Depth { get; set; }
}
public sealed class SvnInfoWorkingCopy
{
[XmlElement(ElementName = "root", Namespace = "")]
public string Root { get; set; }
[XmlElement(ElementName = "uuid", Namespace = "")]
public Guid Uuid { get; set; }
}
public sealed class SvnInfoCommit
{
[XmlAttribute(AttributeName = "revision", Namespace = "")]
public string Revision { get; set; }
[XmlElement(ElementName = "author", Namespace = "")]
public string Author { get; set; }
[XmlElement(ElementName = "date", Namespace = "")]
public string Date { get; set; }
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Numerics;
using System.Text;
using Scriban.Runtime;
using Scriban.Syntax;
namespace Scriban.Parsing
{
public partial class Parser
{
private ScriptExpression ParseVariableOrLiteral()
{
ScriptExpression literal = null;
switch (Current.Type)
{
case TokenType.Identifier:
case TokenType.IdentifierSpecial:
literal = ParseVariable();
break;
case TokenType.Integer:
literal = ParseInteger();
break;
case TokenType.HexaInteger:
literal = ParseHexaInteger();
break;
case TokenType.BinaryInteger:
literal = ParseBinaryInteger();
break;
case TokenType.Float:
literal = ParseFloat();
break;
case TokenType.String:
literal = ParseString();
break;
case TokenType.ImplicitString:
literal = ParseImplicitString();
break;
case TokenType.VerbatimString:
literal = ParseVerbatimString();
break;
default:
LogError(Current, "Unexpected token found `{GetAsText(Current)}` while parsing a variable or literal");
break;
}
return literal;
}
private ScriptLiteral ParseFloat()
{
var literal = Open<ScriptLiteral>();
var text = GetAsText(Current);
var c = text[text.Length - 1];
if (c == 'f' || c == 'F')
{
float floatResult;
if (float.TryParse(text.Substring(0, text.Length - 1), NumberStyles.Float, CultureInfo.InvariantCulture, out floatResult))
{
literal.Value = floatResult;
}
else
{
LogError($"Unable to parse float value `{text}`");
}
}
else
{
var explicitDecimal = c == 'm' || c == 'M';
if ((Options.ParseFloatAsDecimal || explicitDecimal) && decimal.TryParse(explicitDecimal ? text.Substring(0, text.Length - 1) : text, NumberStyles.Float, CultureInfo.InvariantCulture, out var decimalResult))
{
literal.Value = decimalResult;
}
else
{
double floatResult;
if (double.TryParse(c == 'd' || c == 'D' ? text.Substring(0, text.Length-1) : text, NumberStyles.Float, CultureInfo.InvariantCulture, out floatResult))
{
literal.Value = floatResult;
}
}
if (literal.Value == null)
{
LogError($"Unable to parse double value `{text}`");
}
}
NextToken(); // Skip the float
return Close(literal);
}
private ScriptLiteral ParseImplicitString()
{
var literal = Open<ScriptLiteral>();
literal.Value = GetAsText(Current);
Close(literal);
NextToken();
return literal;
}
private ScriptLiteral ParseInteger()
{
var literal = Open<ScriptLiteral>();
var text = GetAsText(Current).Replace("_", string.Empty);
long result;
if (!long.TryParse(text, NumberStyles.Integer|NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out result))
{
bool isValid = false;
if (BigInteger.TryParse(text, NumberStyles.Integer | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var bigResult))
{
literal.Value = bigResult;
isValid = true;
}
if (!isValid)
{
LogError($"Unable to parse the integer {text}");
}
}
else
{
if (result >= int.MinValue && result <= int.MaxValue)
{
literal.Value = (int) result;
}
else
{
literal.Value = result;
}
}
NextToken(); // Skip the literal
return Close(literal);
}
private ScriptLiteral ParseHexaInteger()
{
var literal = Open<ScriptLiteral>();
var text = GetAsText(Current).Substring(2).Replace("_", string.Empty);
bool isUnsigned = false;
if (text.EndsWith("u", StringComparison.OrdinalIgnoreCase))
{
text = text.Substring(0, text.Length - 1);
isUnsigned = true;
}
ulong tempResult;
if (!ulong.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out tempResult))
{
bool isValid = false;
if (BigInteger.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var bigResult))
{
literal.Value = bigResult;
isValid = true;
}
if (!isValid)
{
LogError($"Unable to parse the integer {text}");
}
}
else
{
if (tempResult <= uint.MaxValue)
{
if (isUnsigned)
{
literal.Value = (long)(uint)tempResult;
}
else
{
literal.Value = unchecked((int)(uint)tempResult);
}
}
else
{
if (isUnsigned)
{
literal.Value = new BigInteger(tempResult);
}
if (literal.Value == null)
{
literal.Value = unchecked((long)tempResult);
}
}
}
NextToken(); // Skip the literal
return Close(literal);
}
private ScriptLiteral ParseBinaryInteger()
{
var literal = Open<ScriptLiteral>();
var text = GetAsText(Current).Replace("_", string.Empty);
bool isUnsigned = false;
if (text.EndsWith("u", StringComparison.OrdinalIgnoreCase))
{
text = text.Substring(0, text.Length - 1);
isUnsigned = true;
}
var dotIndex = text.IndexOf('.');
var isDoubleOrFloat = dotIndex > 2;
if (isDoubleOrFloat)
{
bool isFloat = false;
if (text.EndsWith("f", StringComparison.OrdinalIgnoreCase))
{
text = text.Substring(0, text.Length - 1);
isFloat = true;
}
else if (text.EndsWith("d", StringComparison.OrdinalIgnoreCase))
{
text = text.Substring(0, text.Length - 1);
}
int exponent = dotIndex - 2;
var number = BigInteger.Zero;
int digit = 0;
for (int i = 2; i < text.Length; i++)
{
var c = text[i];
if (c == '.') continue;
number <<= 1;
number |= c == '0' ? 0U : 1U;
digit++;
}
if (isFloat)
{
literal.Value = (float)number * (float)Math.Pow(2, exponent - digit);
}
else
{
literal.Value = (double)number * Math.Pow(2, exponent - digit);
}
}
else
{
var number = BigInteger.Zero;
for (int i = 2; i < text.Length; i++)
{
var c = text[i];
number <<= 1;
number |= c == '0' ? 0U : 1U;
}
if (number <= uint.MaxValue)
{
if (isUnsigned)
{
literal.Value = (long) (uint) number;
}
else
{
literal.Value = unchecked((int) (uint) number);
}
}
else if (number <= ulong.MaxValue)
{
if (isUnsigned)
{
literal.Value = number;
}
if (literal.Value == null)
{
literal.Value = unchecked((long) (ulong) number);
}
}
else
{
literal.Value = number;
}
}
NextToken(); // Skip the literal
return Close(literal);
}
private ScriptLiteral ParseString()
{
var literal = Open<ScriptLiteral>();
var text = _lexer.Text;
var builder = new StringBuilder(Current.End.Offset - Current.Start.Offset - 1);
literal.StringQuoteType =
_lexer.Text[Current.Start.Offset] == '\''
? ScriptLiteralStringQuoteType.SimpleQuote
: ScriptLiteralStringQuoteType.DoubleQuote;
var end = Current.End.Offset;
for (int i = Current.Start.Offset + 1; i < end; i++)
{
var c = text[i];
// Handle escape characters
if (text[i] == '\\')
{
i++;
switch (text[i])
{
case '0':
builder.Append((char) 0);
break;
case '\n':
break;
case '\r':
i++; // skip next \n that was validated by the lexer
break;
case '\'':
builder.Append('\'');
break;
case '"':
builder.Append('"');
break;
case '\\':
builder.Append('\\');
break;
case 'b':
builder.Append('\b');
break;
case 'f':
builder.Append('\f');
break;
case 'n':
builder.Append('\n');
break;
case 'r':
builder.Append('\r');
break;
case 't':
builder.Append('\t');
break;
case 'v':
builder.Append('\v');
break;
case 'u':
{
i++;
int value = 0;
if (i < text.Length) value = text[i++].HexToInt();
if (i < text.Length) value = (value << 4) | text[i++].HexToInt();
if (i < text.Length) value = (value << 4) | text[i++].HexToInt();
if (i < text.Length) value = (value << 4) | text[i].HexToInt();
// Is it correct?
builder.Append(ConvertFromUtf32(value));
break;
}
case 'x':
{
i++;
int value = 0;
if (i < text.Length) value = text[i++].HexToInt();
if (i < text.Length) value = (value << 4) | text[i].HexToInt();
builder.Append((char) value);
break;
}
default:
// This should not happen as the lexer is supposed to prevent this
LogError($"Unexpected escape character `{text[i]}` in string");
break;
}
}
else
{
builder.Append(c);
}
}
literal.Value = builder.ToString();
NextToken();
return Close(literal);
}
private ScriptExpression ParseVariable()
{
var currentToken = Current;
var currentSpan = CurrentSpan;
var endSpan = currentSpan;
var text = GetAsText(currentToken);
// Return ScriptLiteral for null, true, false
// Return ScriptAnonymousFunction
switch (text)
{
case "null":
var nullValue = Open<ScriptLiteral>();
NextToken();
return Close(nullValue);
case "true":
var trueValue = Open<ScriptLiteral>();
trueValue.Value = true;
NextToken();
return Close(trueValue);
case "false":
var falseValue = Open<ScriptLiteral>();
falseValue.Value = false;
NextToken();
return Close(falseValue);
case "do":
var functionExp = Open<ScriptAnonymousFunction>();
functionExp.Function = ParseFunctionStatement(true);
var func = Close(functionExp);
return func;
case "this":
if (!_isLiquid)
{
var thisExp = Open<ScriptThisExpression>();
ExpectAndParseKeywordTo(thisExp.ThisKeyword);
return Close(thisExp);
}
break;
}
// Keeps trivia before this token
List<ScriptTrivia> triviasBefore = null;
if (_isKeepTrivia && _trivias.Count > 0)
{
triviasBefore = new List<ScriptTrivia>();
triviasBefore.AddRange(_trivias);
_trivias.Clear();
}
NextToken();
var scope = ScriptVariableScope.Global;
if (text.StartsWith("$"))
{
scope = ScriptVariableScope.Local;
text = text.Substring(1);
// Convert $0, $1... $n variable into $[0] $[1]...$[n] variables
int index;
if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out index))
{
var target = new ScriptVariableLocal(ScriptVariable.Arguments.BaseName)
{
Span = currentSpan
};
var indexLiteral = new ScriptLiteral() {Span = currentSpan, Value = index};
var indexerExpression = new ScriptIndexerExpression
{
Span = currentSpan,
Target = target,
Index = indexLiteral
};
if (_isKeepTrivia)
{
if (triviasBefore != null)
{
target.AddTrivias(triviasBefore, true);
}
// Special case, we add the trivias to the index as the [] brackets
// won't be output-ed
FlushTrivias(indexLiteral, false);
_lastTerminalWithTrivias = indexLiteral;
}
return indexerExpression;
}
}
else if (text == "for" || text == "while" || text == "tablerow" || (_isLiquid && (text == "forloop" || text == "tablerowloop")))
{
if (Current.Type == TokenType.Dot)
{
scope = ScriptVariableScope.Loop;
var token = PeekToken();
if (token.Type == TokenType.Identifier)
{
//endSpan = GetSpanForToken(token);
var loopVariableText = GetAsText(token);
if (_isLiquid)
{
switch (loopVariableText)
{
case "first":
case "last":
case "index0":
case "rindex0":
case "index":
case "rindex":
case "length":
break;
case "col":
if (text != "tablerowloop")
{
// unit test: 108-variable-loop-error2.txt
LogError(currentToken, $"The loop variable <{text}.col> is invalid");
}
break;
default:
LogError(currentToken, $"The liquid loop variable <{text}.{loopVariableText}> is not supported");
break;
}
if (text == "forloop") text = "for";
else if (text == "tablerowloop") text = "tablerow";
}
else
{
switch (loopVariableText)
{
// supported by both for and while
case "first":
case "even":
case "odd":
case "index":
break;
case "last":
case "changed":
case "length":
case "rindex":
if (text == "while")
{
// unit test: 108-variable-loop-error2.txt
LogError(currentToken, $"The loop variable <while.{loopVariableText}> is invalid");
}
break;
case "col":
if (text != "tablerow")
{
// unit test: 108-variable-loop-error2.txt
LogError(currentToken, $"The loop variable <{text}.col> is invalid");
}
break;
default:
// unit test: 108-variable-loop-error1.txt
LogError(currentToken, $"The loop variable <{text}.{loopVariableText}> is not supported");
break;
}
}
}
else
{
LogError(currentToken, $"Invalid token `{GetAsText(Current)}`. The loop variable <{text}> dot must be followed by an identifier");
}
}
}
else if (_isLiquid && text == "continue")
{
scope = ScriptVariableScope.Local;
}
var result = ScriptVariable.Create(text, scope);
result.Span = new SourceSpan
{
FileName = currentSpan.FileName,
Start = currentSpan.Start,
End = endSpan.End
};
// A liquid variable can have `-` in its identifier
// If this is the case, we need to translate it to `this["this"]` instead
if (_isLiquid && text.IndexOf('-') >= 0)
{
var target = new ScriptThisExpression()
{
Span = result.Span
};
var newExp = new ScriptIndexerExpression
{
Target = target,
Index = new ScriptLiteral(text)
{
Span = result.Span
},
Span = result.Span
};
// Flush any trivias after
if (_isKeepTrivia)
{
if (triviasBefore != null)
{
target.ThisKeyword.AddTrivias(triviasBefore, true);
}
FlushTrivias(newExp.CloseBracket, false);
_lastTerminalWithTrivias = newExp.CloseBracket;
}
// Return the expression
return newExp;
}
if (_isKeepTrivia)
{
// Flush any trivias after
if (triviasBefore != null)
{
result.AddTrivias(triviasBefore, true);
}
FlushTrivias(result, false);
_lastTerminalWithTrivias = result;
}
return result;
}
private ScriptLiteral ParseVerbatimString()
{
var literal = Open<ScriptLiteral>();
var text = _lexer.Text;
literal.StringQuoteType = ScriptLiteralStringQuoteType.Verbatim;
StringBuilder builder = null;
// startOffset start at the first character (`a` in the string `abc`)
var startOffset = Current.Start.Offset + 1;
// endOffset is at the last character (`c` in the string `abc`)
var endOffset = Current.End.Offset - 1;
int offset = startOffset;
while (true)
{
// Go to the next escape (the lexer verified that there was a following `)
var nextOffset = text.IndexOf("`", offset, endOffset - offset + 1, StringComparison.OrdinalIgnoreCase);
if (nextOffset < 0)
{
break;
}
if (builder == null)
{
builder = new StringBuilder(endOffset - startOffset + 1);
}
builder.Append(text.Substring(offset, nextOffset - offset + 1));
// Skip the escape ``
offset = nextOffset + 2;
}
if (builder != null)
{
var count = endOffset - offset + 1;
if (count > 0)
{
builder.Append(text.Substring(offset, count));
}
literal.Value = builder.ToString();
}
else
{
literal.Value = text.Substring(offset, endOffset - offset + 1);
}
NextToken();
return Close(literal);
}
private static string ConvertFromUtf32(int utf32)
{
if (utf32 < 65536)
return ((char)utf32).ToString();
utf32 -= 65536;
return new string(new char[2]
{
(char) (utf32 / 1024 + 55296),
(char) (utf32 % 1024 + 56320)
});
}
private static bool IsVariableOrLiteral(Token token)
{
switch (token.Type)
{
case TokenType.Identifier:
case TokenType.IdentifierSpecial:
case TokenType.Integer:
case TokenType.HexaInteger:
case TokenType.BinaryInteger:
case TokenType.Float:
case TokenType.String:
case TokenType.ImplicitString:
case TokenType.VerbatimString:
return true;
}
return 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;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
/*****************************************************
*
* XMLRPCModule
*
* Module for accepting incoming communications from
* external XMLRPC client and calling a remote data
* procedure for a registered data channel/prim.
*
*
* 1. On module load, open a listener port
* 2. Attach an XMLRPC handler
* 3. When a request is received:
* 3.1 Parse into components: channel key, int, string
* 3.2 Look up registered channel listeners
* 3.3 Call the channel (prim) remote data method
* 3.4 Capture the response (llRemoteDataReply)
* 3.5 Return response to client caller
* 3.6 If no response from llRemoteDataReply within
* RemoteReplyScriptTimeout, generate script timeout fault
*
* Prims in script must:
* 1. Open a remote data channel
* 1.1 Generate a channel ID
* 1.2 Register primid,channelid pair with module
* 2. Implement the remote data procedure handler
*
* llOpenRemoteDataChannel
* llRemoteDataReply
* remote_data(integer type, key channel, key messageid, string sender, integer ival, string sval)
* llCloseRemoteDataChannel
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
{
public class XMLRPCModule : IRegionModule, IXMLRPC
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_name = "XMLRPCModule";
// <channel id, RPCChannelInfo>
private Dictionary<UUID, RPCChannelInfo> m_openChannels;
private Dictionary<UUID, SendRemoteDataRequest> m_pendingSRDResponses;
private int m_remoteDataPort = 0;
private Dictionary<UUID, RPCRequestInfo> m_rpcPending;
private Dictionary<UUID, RPCRequestInfo> m_rpcPendingResponses;
private List<Scene> m_scenes = new List<Scene>();
private int RemoteReplyScriptTimeout = 9000;
private int RemoteReplyScriptWait = 300;
private object XMLRPCListLock = new object();
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
// We need to create these early because the scripts might be calling
// But since this gets called for every region, we need to make sure they
// get called only one time (or we lose any open channels)
if (null == m_openChannels)
{
m_openChannels = new Dictionary<UUID, RPCChannelInfo>();
m_rpcPending = new Dictionary<UUID, RPCRequestInfo>();
m_rpcPendingResponses = new Dictionary<UUID, RPCRequestInfo>();
m_pendingSRDResponses = new Dictionary<UUID, SendRemoteDataRequest>();
try
{
m_remoteDataPort = config.Configs["XMLRPC"].GetInt("XmlRpcPort", m_remoteDataPort);
}
catch (Exception)
{
}
}
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
scene.RegisterModuleInterface<IXMLRPC>(this);
}
}
public void PostInitialise()
{
if (IsEnabled())
{
// Start http server
// Attach xmlrpc handlers
m_log.Info("[REMOTE_DATA]: " +
"Starting XMLRPC Server on port " + m_remoteDataPort + " for llRemoteData commands.");
BaseHttpServer httpServer = new BaseHttpServer((uint) m_remoteDataPort);
httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData);
httpServer.Start();
}
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public bool IsSharedModule
{
get { return true; }
}
public int Port
{
get { return m_remoteDataPort; }
}
#endregion
#region IXMLRPC Members
public bool IsEnabled()
{
return (m_remoteDataPort > 0);
}
/**********************************************
* OpenXMLRPCChannel
*
* Generate a UUID channel key and add it and
* the prim id to dictionary <channelUUID, primUUID>
*
* A custom channel key can be proposed.
* Otherwise, passing UUID.Zero will generate
* and return a random channel
*
* First check if there is a channel assigned for
* this itemID. If there is, then someone called
* llOpenRemoteDataChannel twice. Just return the
* original channel. Other option is to delete the
* current channel and assign a new one.
*
* ********************************************/
public UUID OpenXMLRPCChannel(uint localID, UUID itemID, UUID channelID)
{
UUID newChannel = UUID.Zero;
// This should no longer happen, but the check is reasonable anyway
if (null == m_openChannels)
{
m_log.Warn("[RemoteDataReply] Attempt to open channel before initialization is complete");
return newChannel;
}
//Is a dupe?
foreach (RPCChannelInfo ci in m_openChannels.Values)
{
if (ci.GetItemID().Equals(itemID))
{
// return the original channel ID for this item
newChannel = ci.GetChannelID();
break;
}
}
if (newChannel == UUID.Zero)
{
newChannel = (channelID == UUID.Zero) ? UUID.Random() : channelID;
RPCChannelInfo rpcChanInfo = new RPCChannelInfo(localID, itemID, newChannel);
lock (XMLRPCListLock)
{
m_openChannels.Add(newChannel, rpcChanInfo);
}
}
return newChannel;
}
// Delete channels based on itemID
// for when a script is deleted
public void DeleteChannels(UUID itemID)
{
if (m_openChannels != null)
{
ArrayList tmp = new ArrayList();
lock (XMLRPCListLock)
{
foreach (RPCChannelInfo li in m_openChannels.Values)
{
if (li.GetItemID().Equals(itemID))
{
tmp.Add(itemID);
}
}
IEnumerator tmpEnumerator = tmp.GetEnumerator();
while (tmpEnumerator.MoveNext())
m_openChannels.Remove((UUID) tmpEnumerator.Current);
}
}
}
/**********************************************
* Remote Data Reply
*
* Response to RPC message
*
*********************************************/
public void RemoteDataReply(string channel, string message_id, string sdata, int idata)
{
UUID message_key = new UUID(message_id);
UUID channel_key = new UUID(channel);
RPCRequestInfo rpcInfo = null;
if (message_key == UUID.Zero)
{
foreach (RPCRequestInfo oneRpcInfo in m_rpcPendingResponses.Values)
if (oneRpcInfo.GetChannelKey() == channel_key)
rpcInfo = oneRpcInfo;
}
else
{
m_rpcPendingResponses.TryGetValue(message_key, out rpcInfo);
}
if (rpcInfo != null)
{
rpcInfo.SetStrRetval(sdata);
rpcInfo.SetIntRetval(idata);
rpcInfo.SetProcessed(true);
m_rpcPendingResponses.Remove(message_key);
}
else
{
m_log.Warn("[RemoteDataReply]: Channel or message_id not found");
}
}
/**********************************************
* CloseXMLRPCChannel
*
* Remove channel from dictionary
*
*********************************************/
public void CloseXMLRPCChannel(UUID channelKey)
{
if (m_openChannels.ContainsKey(channelKey))
m_openChannels.Remove(channelKey);
}
public bool hasRequests()
{
lock (XMLRPCListLock)
{
if (m_rpcPending != null)
return (m_rpcPending.Count > 0);
else
return false;
}
}
public IXmlRpcRequestInfo GetNextCompletedRequest()
{
if (m_rpcPending != null)
{
lock (XMLRPCListLock)
{
foreach (UUID luid in m_rpcPending.Keys)
{
RPCRequestInfo tmpReq;
if (m_rpcPending.TryGetValue(luid, out tmpReq))
{
if (!tmpReq.IsProcessed()) return tmpReq;
}
}
}
}
return null;
}
public void RemoveCompletedRequest(UUID id)
{
lock (XMLRPCListLock)
{
RPCRequestInfo tmp;
if (m_rpcPending.TryGetValue(id, out tmp))
{
m_rpcPending.Remove(id);
m_rpcPendingResponses.Add(id, tmp);
}
else
{
m_log.Error("UNABLE TO REMOVE COMPLETED REQUEST");
}
}
}
public UUID SendRemoteData(uint localID, UUID itemID, string channel, string dest, int idata, string sdata)
{
SendRemoteDataRequest req = new SendRemoteDataRequest(
localID, itemID, channel, dest, idata, sdata
);
m_pendingSRDResponses.Add(req.GetReqID(), req);
req.Process();
return req.ReqID;
}
public IServiceRequest GetNextCompletedSRDRequest()
{
if (m_pendingSRDResponses != null)
{
lock (XMLRPCListLock)
{
foreach (UUID luid in m_pendingSRDResponses.Keys)
{
SendRemoteDataRequest tmpReq;
if (m_pendingSRDResponses.TryGetValue(luid, out tmpReq))
{
if (tmpReq.Finished)
return tmpReq;
}
}
}
}
return null;
}
public void RemoveCompletedSRDRequest(UUID id)
{
lock (XMLRPCListLock)
{
SendRemoteDataRequest tmpReq;
if (m_pendingSRDResponses.TryGetValue(id, out tmpReq))
{
m_pendingSRDResponses.Remove(id);
}
}
}
public void CancelSRDRequests(UUID itemID)
{
if (m_pendingSRDResponses != null)
{
lock (XMLRPCListLock)
{
foreach (SendRemoteDataRequest li in m_pendingSRDResponses.Values)
{
if (li.ItemID.Equals(itemID))
m_pendingSRDResponses.Remove(li.GetReqID());
}
}
}
}
#endregion
public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable) request.Params[0];
bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") &&
requestData.Contains("StringValue"));
if (GoodXML)
{
UUID channel = new UUID((string) requestData["Channel"]);
RPCChannelInfo rpcChanInfo;
if (m_openChannels.TryGetValue(channel, out rpcChanInfo))
{
string intVal = Convert.ToInt32(requestData["IntValue"]).ToString();
string strVal = (string) requestData["StringValue"];
RPCRequestInfo rpcInfo;
lock (XMLRPCListLock)
{
rpcInfo =
new RPCRequestInfo(rpcChanInfo.GetLocalID(), rpcChanInfo.GetItemID(), channel, strVal,
intVal);
m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo);
}
int timeoutCtr = 0;
while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout))
{
Thread.Sleep(RemoteReplyScriptWait);
timeoutCtr += RemoteReplyScriptWait;
}
if (rpcInfo.IsProcessed())
{
Hashtable param = new Hashtable();
param["StringValue"] = rpcInfo.GetStrRetval();
param["IntValue"] = rpcInfo.GetIntRetval();
ArrayList parameters = new ArrayList();
parameters.Add(param);
response.Value = parameters;
rpcInfo = null;
}
else
{
response.SetFault(-1, "Script timeout");
rpcInfo = null;
}
}
else
{
response.SetFault(-1, "Invalid channel");
}
}
return response;
}
}
public class RPCRequestInfo: IXmlRpcRequestInfo
{
private UUID m_ChannelKey;
private string m_IntVal;
private UUID m_ItemID;
private uint m_localID;
private UUID m_MessageID;
private bool m_processed;
private int m_respInt;
private string m_respStr;
private string m_StrVal;
public RPCRequestInfo(uint localID, UUID itemID, UUID channelKey, string strVal, string intVal)
{
m_localID = localID;
m_StrVal = strVal;
m_IntVal = intVal;
m_ItemID = itemID;
m_ChannelKey = channelKey;
m_MessageID = UUID.Random();
m_processed = false;
m_respStr = String.Empty;
m_respInt = 0;
}
public bool IsProcessed()
{
return m_processed;
}
public UUID GetChannelKey()
{
return m_ChannelKey;
}
public void SetProcessed(bool processed)
{
m_processed = processed;
}
public void SetStrRetval(string resp)
{
m_respStr = resp;
}
public string GetStrRetval()
{
return m_respStr;
}
public void SetIntRetval(int resp)
{
m_respInt = resp;
}
public int GetIntRetval()
{
return m_respInt;
}
public uint GetLocalID()
{
return m_localID;
}
public UUID GetItemID()
{
return m_ItemID;
}
public string GetStrVal()
{
return m_StrVal;
}
public int GetIntValue()
{
return int.Parse(m_IntVal);
}
public UUID GetMessageID()
{
return m_MessageID;
}
}
public class RPCChannelInfo
{
private UUID m_ChannelKey;
private UUID m_itemID;
private uint m_localID;
public RPCChannelInfo(uint localID, UUID itemID, UUID channelID)
{
m_ChannelKey = channelID;
m_localID = localID;
m_itemID = itemID;
}
public UUID GetItemID()
{
return m_itemID;
}
public UUID GetChannelID()
{
return m_ChannelKey;
}
public uint GetLocalID()
{
return m_localID;
}
}
public class SendRemoteDataRequest: IServiceRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Channel;
public string DestURL;
private bool _finished;
public bool Finished
{
get { return _finished; }
set { _finished = value; }
}
private Thread httpThread;
public int Idata;
private UUID _itemID;
public UUID ItemID
{
get { return _itemID; }
set { _itemID = value; }
}
private uint _localID;
public uint LocalID
{
get { return _localID; }
set { _localID = value; }
}
private UUID _reqID;
public UUID ReqID
{
get { return _reqID; }
set { _reqID = value; }
}
public XmlRpcRequest Request;
public int ResponseIdata;
public string ResponseSdata;
public string Sdata;
public SendRemoteDataRequest(uint localID, UUID itemID, string channel, string dest, int idata, string sdata)
{
this.Channel = channel;
DestURL = dest;
this.Idata = idata;
this.Sdata = sdata;
ItemID = itemID;
LocalID = localID;
ReqID = UUID.Random();
}
public void Process()
{
httpThread = new Thread(SendRequest);
httpThread.Name = "HttpRequestThread";
httpThread.Priority = ThreadPriority.BelowNormal;
httpThread.IsBackground = true;
_finished = false;
httpThread.Start();
}
/*
* TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception
*/
public void SendRequest()
{
Hashtable param = new Hashtable();
// Check if channel is an UUID
// if not, use as method name
UUID parseUID;
string mName = "llRemoteData";
if ((Channel != null) && (Channel != ""))
if (!UUID.TryParse(Channel, out parseUID))
mName = Channel;
else
param["Channel"] = Channel;
param["StringValue"] = Sdata;
param["IntValue"] = Convert.ToString(Idata);
ArrayList parameters = new ArrayList();
parameters.Add(param);
XmlRpcRequest req = new XmlRpcRequest(mName, parameters);
try
{
XmlRpcResponse resp = req.Send(DestURL, 30000);
if (resp != null)
{
Hashtable respParms;
if (resp.Value.GetType().Equals(typeof(Hashtable)))
{
respParms = (Hashtable) resp.Value;
}
else
{
ArrayList respData = (ArrayList) resp.Value;
respParms = (Hashtable) respData[0];
}
if (respParms != null)
{
if (respParms.Contains("StringValue"))
{
Sdata = (string) respParms["StringValue"];
}
if (respParms.Contains("IntValue"))
{
Idata = Convert.ToInt32((string) respParms["IntValue"]);
}
if (respParms.Contains("faultString"))
{
Sdata = (string) respParms["faultString"];
}
if (respParms.Contains("faultCode"))
{
Idata = Convert.ToInt32(respParms["faultCode"]);
}
}
}
}
catch (Exception we)
{
Sdata = we.Message;
m_log.Warn("[SendRemoteDataRequest]: Request failed");
m_log.Warn(we.StackTrace);
}
_finished = true;
}
public void Stop()
{
try
{
httpThread.Abort();
}
catch (Exception)
{
}
}
public UUID GetReqID()
{
return ReqID;
}
}
}
| |
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using FileFormatWavefront;
using FileFormatWavefront.Model;
using Face = FileFormatWavefront.Model.Face;
using Group = FileFormatWavefront.Model.Group;
using FaceCollection = System.Collections.ObjectModel.ReadOnlyCollection<FileFormatWavefront.Model.Face>;
//using RvtFace = Autodesk.Revit.DB.Face;
#endregion
namespace DirectObjLoader
{
[Transaction( TransactionMode.Manual )]
public class Command : IExternalCommand
{
/// <summary>
/// Remember last selected filename for the
/// duration of the current session.
/// </summary>
static string _filename = string.Empty;
/// <summary>
/// Category to use for the DirectShape elements
/// generated.
/// </summary>
static ElementId _categoryId = new ElementId(
BuiltInCategory.OST_GenericModel );
/// <summary>
/// Troubleshooting web page URL for use in
/// warning message on too many mesh vertices.
/// </summary>
public const string TroubleshootingUrl
= "http://truevis.com/troubleshoot-revit-mesh-import";
/// <summary>
/// Create a new DirectShape element from given
/// list of faces and return the number of faces
/// processed.
/// Return -1 if a face vertex index exceeds the
/// total number of available vertices,
/// representing a fatal error.
/// </summary>
static int NewDirectShape(
List<XYZ> vertices,
FaceCollection faces,
Document doc,
ElementId graphicsStyleId,
string appGuid,
string shapeName )
{
int nFaces = 0;
int nFacesFailed = 0;
TessellatedShapeBuilder builder
= new TessellatedShapeBuilder();
builder.LogString = shapeName;
List<XYZ> corners = new List<XYZ>( 4 );
builder.OpenConnectedFaceSet( false );
foreach( Face f in faces )
{
builder.LogInteger = nFaces;
if( corners.Capacity < f.Indices.Count )
{
corners = new List<XYZ>( f.Indices.Count );
}
corners.Clear();
foreach( Index i in f.Indices )
{
Debug.Assert( vertices.Count > i.vertex,
"how can the face vertex index be larger "
+ "than the total number of vertices?" );
if( i.vertex >= vertices.Count )
{
return -1;
}
corners.Add( vertices[i.vertex] );
}
try
{
builder.AddFace( new TessellatedFace( corners,
ElementId.InvalidElementId ) );
++nFaces;
}
catch( Autodesk.Revit.Exceptions.ArgumentException ex )
{
// Remember something went wrong here.
++nFacesFailed;
Debug.Print(
"Revit API argument exception {0}\r\n"
+ "Failed to add face with {1} corners: {2}",
ex.Message, corners.Count,
string.Join( ", ",
corners.Select<XYZ, string>(
p => Util.PointString( p ) ) ) );
}
}
builder.CloseConnectedFaceSet();
// Refer to StlImport sample for more clever
// handling of target and fallback and the
// possible combinations.
//TessellatedShapeBuilderResult r // 2015
// = builder.Build(
// TessellatedShapeBuilderTarget.AnyGeometry,
// TessellatedShapeBuilderFallback.Mesh,
// graphicsStyleId );
builder.Target = TessellatedShapeBuilderTarget.AnyGeometry; // 2017
builder.Fallback = TessellatedShapeBuilderFallback.Mesh; // 2017
builder.GraphicsStyleId = graphicsStyleId; // 2017
builder.Build(); // 2017
//TessellatedShapeBuilderResult r // 2015
DirectShape ds = DirectShape.CreateElement(
//doc, _categoryId, appGuid, shapeName ); // 2015
doc, _categoryId ); // 2017
ds.ApplicationId = appGuid; // 2017
ds.ApplicationDataId = shapeName; // 2017
//ds.SetShape( r.GetGeometricalObjects() ); // 2015
ds.SetShape( builder.GetBuildResult().GetGeometricalObjects() ); // 2017
ds.Name = shapeName;
Debug.Print(
"Shape '{0}': added {1} face{2}, {3} face{4} failed.",
shapeName, nFaces, Util.PluralSuffix( nFaces ),
nFacesFailed, Util.PluralSuffix( nFacesFailed ) );
return nFaces;
}
/// <summary>
/// External command mainline.
/// </summary>
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
IWin32Window revit_window
= new JtWindowHandle( Autodesk.Windows
.ComponentManager.ApplicationWindow );
if( !Util.FileSelectObj(
Config.DefaultFolderObj,
ref _filename ) )
{
return Result.Cancelled;
}
Config.DefaultFolderObj
= Path.GetDirectoryName( _filename );
long fileSize = Util.GetFileSize( _filename );
if( fileSize > Config.MaxFileSize )
{
string msg = string.Format( "Excuse me, but "
+ "you are attempting to load a file that is "
+ "{0} bytes in size. We suggest ensuring "
+ "that the file size is no larger than {1} "
+ "bytes, since Revit will refuse to handle "
+ "meshes exceeding a certain size anyway. "
+ "Please refer to the troubleshooting page "
+ "at\r\n\r\n{2}\r\n\r\n"
+ "for suggestions on how to optimise the "
+ "mesh and thus reduce file size.",
fileSize, Config.MaxFileSize,
TroubleshootingUrl );
TaskDialog.Show( App.Caption, msg );
return Result.Failed;
}
FileLoadResult<Scene> obj_load_result = null;
List<XYZ> vertices = null;
try
{
bool loadTextureImages = true;
obj_load_result = FileFormatObj.Load(
_filename, loadTextureImages );
foreach( var m in obj_load_result.Messages )
{
Debug.Print( "{0}: {1} line {2} in {3}",
m.MessageType, m.Details,
m.FileName, m.LineNumber );
}
// Convert OBJ vertices to Revit XYZ.
// OBJ assumes X to the right, Y up and Z out of the screen.
// Revit 3D view assumes X right, Y away
// from the screen and Z up.
double scale = Config.InputScaleFactor;
int n = obj_load_result.Model.Vertices.Count;
vertices = new List<XYZ>( n );
XYZ w;
foreach( Vertex v in obj_load_result.Model.Vertices )
{
w = new XYZ( v.x * scale,
-v.z * scale, v.y * scale );
Debug.Print( "({0},{1},{2}) --> {3}",
Util.RealString( v.x ),
Util.RealString( v.y ),
Util.RealString( v.z ),
Util.PointString( w ) );
vertices.Add( w );
}
foreach( Face f in obj_load_result.Model.UngroupedFaces )
{
n = f.Indices.Count;
Debug.Assert( 3 == n || 4 == n,
"expected triangles or quadrilaterals" );
Debug.Print( string.Join( ", ",
f.Indices.Select<Index, string>(
i => i.vertex.ToString() ) ) );
}
}
catch( System.Exception ex )
{
message = string.Format(
"Exception reading '{0}':"
+ "\r\n{1}:\r\n{2}",
_filename,
ex.GetType().FullName,
ex.Message );
return Result.Failed;
}
if( vertices.Count > Config.MaxNumberOfVertices )
{
string msg = string.Format( "Excuse me, but "
+ "you are attempting to load a mesh defining "
+ "{0} vertices. We suggest using no more than "
+ "{1}, since Revit will refuse to handle such "
+ "a large mesh anyway. "
+ "Please refer to the troubleshooting page at "
+ "\r\n\r\n{2}\r\n\r\n"
+ "for suggestions on how to optimise the mesh "
+ "and thus reduce its size.",
vertices.Count, Config.MaxNumberOfVertices,
TroubleshootingUrl );
TaskDialog.Show( App.Caption, msg );
return Result.Failed;
}
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;
string appGuid
= uiapp.ActiveAddInId.GetGUID().ToString();
string shapeName = Util.Capitalize(
Path.GetFileNameWithoutExtension( _filename )
.Replace( '_', ' ' ) );
// Retrieve "<Sketch>" graphics style,
// if it exists.
FilteredElementCollector collector
= new FilteredElementCollector( doc )
.OfClass( typeof( GraphicsStyle ) );
GraphicsStyle style
= collector.Cast<GraphicsStyle>()
.FirstOrDefault<GraphicsStyle>( gs
=> gs.Name.Equals( "<Sketch>" ) );
ElementId graphicsStyleId = null;
if( style != null )
{
graphicsStyleId = style.Id;
}
Result rc = Result.Failed;
try
{
using( Transaction tx = new Transaction( doc ) )
{
tx.Start( "Create DirectShape from OBJ" );
int nFaces = 0; // set to -1 on fatal error
int nFacesTotal = 0;
if( 0 < obj_load_result.Model.UngroupedFaces.Count )
{
nFacesTotal = nFaces = NewDirectShape( vertices,
obj_load_result.Model.UngroupedFaces, doc,
graphicsStyleId, appGuid, shapeName );
}
if( -1 < nFaces )
{
foreach( Group g in obj_load_result.Model.Groups )
{
string s = string.Join( ".", g.Names );
if( 0 < s.Length ) { s = "." + s; }
nFaces = NewDirectShape( vertices, g.Faces,
doc, graphicsStyleId, appGuid,
shapeName + s );
if( -1 == nFaces )
{
break;
}
nFacesTotal += nFaces;
}
}
if( -1 == nFaces )
{
message = "Invalid OBJ file. Error: face "
+ "vertex index exceeds total vertex count.";
}
else if( 0 == nFacesTotal )
{
message = "Invalid OBJ file. Zero faces found.";
}
else
{
tx.Commit();
rc = Result.Succeeded;
}
}
}
catch( System.Exception ex )
{
message = string.Format(
"Exception generating DirectShape '{0}':"
+ "\r\n{1}:\r\n{2}",
shapeName,
ex.GetType().FullName,
ex.Message );
return Result.Failed;
}
return rc;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Json.Tests
{
public class JsonValueTests
{
[Fact]
public void JsonValue_Load_LoadWithTrailingCommaInDictionary()
{
Parse("{ \"a\": \"b\",}", value =>
{
Assert.Equal(1, value.Count);
Assert.Equal(JsonType.String, value["a"].JsonType);
Assert.Equal("b", value["a"]);
JsonValue.Parse("[{ \"a\": \"b\",}]");
});
}
[Theory]
[InlineData("[]")]
[InlineData(" \t \r \n [ \t \r \n ] \t \r \n ")]
public void Parse_EmptyArray(string jsonString)
{
Parse(jsonString, value =>
{
Assert.Equal(0, value.Count);
Assert.Equal(JsonType.Array, value.JsonType);
});
}
[Theory]
[InlineData("{}")]
[InlineData(" \t \r \n { \t \r \n } \t \r \n ")]
public void Parse_EmptyDictionary(string jsonString)
{
Parse(jsonString, value =>
{
Assert.Equal(0, value.Count);
Assert.Equal(JsonType.Object, value.JsonType);
});
}
public static IEnumerable<object[]> ParseIntegralBoundaries_TestData()
{
yield return new object[] { "2147483649", "2147483649" };
yield return new object[] { "4294967297", "4294967297" };
yield return new object[] { "9223372036854775807", "9223372036854775807" };
yield return new object[] { "18446744073709551615", "18446744073709551615" };
yield return new object[] { "79228162514264337593543950335", "79228162514264337593543950335" };
}
public static IEnumerable<object[]> ParseIntegralBoundaries_TestData_NetFramework()
{
yield return new object[] { "79228162514264337593543950336", "7.9228162514264338E+28" };
}
public static IEnumerable<object[]> ParseIntegralBoundaries_TestData_NotNetFramework()
{
yield return new object[] { "79228162514264337593543950336", "7.922816251426434E+28" };
}
[Theory]
[MemberData(nameof(ParseIntegralBoundaries_TestData))]
public void Parse_IntegralBoundaries_LessThanMaxDouble_Works(string jsonString, string expectedToString)
{
Parse(jsonString, value =>
{
Assert.Equal(JsonType.Number, value.JsonType);
Assert.Equal(expectedToString, value.ToString());
});
}
[Theory]
[MemberData(nameof(ParseIntegralBoundaries_TestData_NetFramework))]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void Parse_IntegralBoundaries_LessThanMaxDouble_Works_NetFramework(string jsonString, string expectedToString)
{
Parse(jsonString, value =>
{
Assert.Equal(JsonType.Number, value.JsonType);
Assert.Equal(expectedToString, value.ToString());
});
}
[Theory]
[MemberData(nameof(ParseIntegralBoundaries_TestData_NotNetFramework))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void Parse_IntegralBoundaries_LessThanMaxDouble_Works_NotNetFramework(string jsonString, string expectedToString)
{
Parse(jsonString, value =>
{
Assert.Equal(JsonType.Number, value.JsonType);
Assert.Equal(expectedToString, value.ToString());
});
}
[Fact]
public void Parse_TrueFalse()
{
Parse("[true, false]", value =>
{
Assert.Equal(2, value.Count);
Assert.Equal("true", value[0].ToString());
Assert.Equal("false", value[1].ToString());
});
}
[Fact]
public void JsonValue_Load_ToString_JsonArrayWithNulls()
{
Parse("[1,2,3,null]", value =>
{
Assert.Equal(4, value.Count);
Assert.Equal(JsonType.Array, value.JsonType);
Assert.Equal("[1, 2, 3, null]", value.ToString());
((JsonArray) value).Add(null);
Assert.Equal("[1, 2, 3, null, null]", value.ToString());
});
}
[Fact]
public void JsonValue_ToString_JsonObjectWithNulls()
{
Parse("{\"a\":null,\"b\":2}", value =>
{
Assert.Equal(2, value.Count);
Assert.Equal(JsonType.Object, value.JsonType);
Assert.Equal("{\"a\": null, \"b\": 2}", value.ToString());
});
}
[Fact]
public void JsonObject_ToString_OrderingMaintained()
{
var obj = new JsonObject();
obj["a"] = 1;
obj["c"] = 3;
obj["b"] = 2;
Assert.Equal("{\"a\": 1, \"b\": 2, \"c\": 3}", obj.ToString());
}
[Fact]
public void JsonPrimitive_QuoteEscape()
{
Assert.Equal((new JsonPrimitive("\"\"")).ToString(), "\"\\\"\\\"\"");
}
[Fact]
public void Load_NullStream_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("stream", () => JsonValue.Load((Stream)null));
}
[Fact]
public void Load_NullTextReader_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("textReader", () => JsonValue.Load((TextReader)null));
}
[Fact]
public void Parse_NullJsonString_ThrowArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("jsonString", () => JsonValue.Parse(null));
}
[Theory]
[InlineData("")]
[InlineData("-")]
[InlineData("- ")]
[InlineData("1.")]
[InlineData("1. ")]
[InlineData("1e+")]
[InlineData("1 2")]
[InlineData("077")]
[InlineData("[1,]")]
[InlineData("NaN")]
[InlineData("Infinity")]
[InlineData("-Infinity")]
[InlineData("[")]
[InlineData("[1")]
[InlineData("{")]
[InlineData("{ ")]
[InlineData("{1")]
[InlineData("{\"")]
[InlineData("{\"u")]
[InlineData("{\"\\")]
[InlineData("{\"\\u")]
[InlineData("{\"\\uABC")]
[InlineData("{\"\\/")]
[InlineData("{\"\\\\")]
[InlineData("{\"\\\"")]
[InlineData("{\"\\!")]
[InlineData("[tru]")]
[InlineData("[fals]")]
[InlineData("{\"name\"}")]
[InlineData("{\"name\":}")]
[InlineData("{\"name\":1")]
[InlineData("1e")]
[InlineData("1e-")]
[InlineData("1.1a")]
[InlineData("\0")]
[InlineData("\u000B1")]
[InlineData("\u000C1")]
[InlineData("\"\\u\"")]
[InlineData("{\"\\a\"}")]
[InlineData("{\"\\z\"}")]
public void Parse_InvalidInput_ThrowsArgumentException(string value)
{
AssertExtensions.Throws<ArgumentException>(null, () => JsonValue.Parse(value));
using (StringReader textReader = new StringReader(value))
{
AssertExtensions.Throws<ArgumentException>(null, () => JsonValue.Load(textReader));
}
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(value)))
{
AssertExtensions.Throws<ArgumentException>(null, () => JsonValue.Load(stream));
}
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void Parse_DoubleTooLarge_ThrowsOverflowException()
{
Assert.Throws<OverflowException>(() => JsonValue.Parse("1.7976931348623157E+309"));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void Parse_DoubleTooLarge_ReturnsInfinity()
{
Assert.Equal(double.PositiveInfinity, (double)JsonValue.Parse("1.7976931348623157E+309"));
}
[Fact]
public void Parse_InvalidNumericString_ThrowsFormatException()
{
Assert.Throws<FormatException>(() => JsonValue.Parse("1E!"));
}
[Theory]
[InlineData("0", 0)]
[InlineData("9", 9)]
[InlineData("-0", 0)]
[InlineData("0.00", 0)]
[InlineData("-0.00", 0)]
[InlineData("1", 1)]
[InlineData("1.1", 1.1)]
[InlineData("-1", -1)]
[InlineData("-1.1", -1.1)]
[InlineData("1e-10", 1e-10)]
[InlineData("1e+10", 1e+10)]
[InlineData("1e-30", 1e-30)]
[InlineData("1e+30", 1e+30)]
[InlineData("\"1\"", 1)]
[InlineData("\"1.1\"", 1.1)]
[InlineData("\"-1\"", -1)]
[InlineData("\"-1.1\"", -1.1)]
[InlineData("\"NaN\"", double.NaN)]
[InlineData("\"Infinity\"", double.PositiveInfinity)]
[InlineData("\"-Infinity\"", double.NegativeInfinity)]
[InlineData("0.000000000000000000000000000011", 1.1E-29)]
public void JsonValue_Parse_Double(string json, double expected)
{
RemoteExecutor.Invoke((jsonInner, expectedInner) =>
{
foreach (string culture in new[] { "en", "fr", "de" })
{
CultureInfo.CurrentCulture = new CultureInfo(culture);
Assert.Equal(double.Parse(expectedInner, CultureInfo.InvariantCulture), (double)JsonValue.Parse(jsonInner));
}
}, json, expected.ToString("R", CultureInfo.InvariantCulture)).Dispose();
}
[Theory]
[InlineData("\"\"", "")]
[InlineData("\"abc\"", "abc")]
[InlineData("\"\\u1234\"", "\u1234")]
[InlineData("\"\\u@234\"", "\u0234")]
[InlineData("\"\\b\\f\\n\\r\\t\"", "\b\f\n\r\t")]
public void JsonValue_Parse_String(string json, string expected)
{
Assert.Equal(expected, (string)JsonValue.Parse(json));
}
// Convert a number to json and parse the string, then compare the result to the original value
[Theory]
[InlineData(1)]
[InlineData(1.1)]
[InlineData(1.25)]
[InlineData(-1)]
[InlineData(-1.1)]
[InlineData(-1.25)]
[InlineData(1e-20)]
[InlineData(1e+20)]
[InlineData(1e-30)]
[InlineData(1e+30)]
[InlineData(3.1415926535897932384626433)]
[InlineData(3.1415926535897932384626433e-20)]
[InlineData(3.1415926535897932384626433e+20)]
[InlineData(double.NaN)]
[InlineData(double.PositiveInfinity)]
[InlineData(double.NegativeInfinity)]
[InlineData(double.MinValue)]
[InlineData(double.MaxValue)]
[InlineData(18014398509481982.0)] // A number which needs 17 digits (see http://stackoverflow.com/questions/6118231/why-do-i-need-17-significant-digits-and-not-16-to-represent-a-double)
[InlineData(1.123456789e-29)]
[InlineData(1.123456789e-28)] // Values around the smallest positive decimal value
public void JsonValue_Parse_Double_ViaJsonPrimitive(double number)
{
RemoteExecutor.Invoke(numberText =>
{
double numberInner = double.Parse(numberText, CultureInfo.InvariantCulture);
foreach (string culture in new[] { "en", "fr", "de" })
{
CultureInfo.CurrentCulture = new CultureInfo(culture);
Assert.Equal(numberInner, (double)JsonValue.Parse(new JsonPrimitive(numberInner).ToString()));
}
}, number.ToString("R", CultureInfo.InvariantCulture)).Dispose();
}
[Fact]
public void JsonValue_Parse_MinMax_Integers_ViaJsonPrimitive()
{
Assert.Equal(sbyte.MinValue, (sbyte)JsonValue.Parse(new JsonPrimitive(sbyte.MinValue).ToString()));
Assert.Equal(sbyte.MaxValue, (sbyte)JsonValue.Parse(new JsonPrimitive(sbyte.MaxValue).ToString()));
Assert.Equal(byte.MinValue, (byte)JsonValue.Parse(new JsonPrimitive(byte.MinValue).ToString()));
Assert.Equal(byte.MaxValue, (byte)JsonValue.Parse(new JsonPrimitive(byte.MaxValue).ToString()));
Assert.Equal(short.MinValue, (short)JsonValue.Parse(new JsonPrimitive(short.MinValue).ToString()));
Assert.Equal(short.MaxValue, (short)JsonValue.Parse(new JsonPrimitive(short.MaxValue).ToString()));
Assert.Equal(ushort.MinValue, (ushort)JsonValue.Parse(new JsonPrimitive(ushort.MinValue).ToString()));
Assert.Equal(ushort.MaxValue, (ushort)JsonValue.Parse(new JsonPrimitive(ushort.MaxValue).ToString()));
Assert.Equal(int.MinValue, (int)JsonValue.Parse(new JsonPrimitive(int.MinValue).ToString()));
Assert.Equal(int.MaxValue, (int)JsonValue.Parse(new JsonPrimitive(int.MaxValue).ToString()));
Assert.Equal(uint.MinValue, (uint)JsonValue.Parse(new JsonPrimitive(uint.MinValue).ToString()));
Assert.Equal(uint.MaxValue, (uint)JsonValue.Parse(new JsonPrimitive(uint.MaxValue).ToString()));
Assert.Equal(long.MinValue, (long)JsonValue.Parse(new JsonPrimitive(long.MinValue).ToString()));
Assert.Equal(long.MaxValue, (long)JsonValue.Parse(new JsonPrimitive(long.MaxValue).ToString()));
Assert.Equal(ulong.MinValue, (ulong)JsonValue.Parse(new JsonPrimitive(ulong.MinValue).ToString()));
Assert.Equal(ulong.MaxValue, (ulong)JsonValue.Parse(new JsonPrimitive(ulong.MaxValue).ToString()));
Assert.Equal("1E-30", JsonValue.Parse("1e-30").ToString());
Assert.Equal("1E+30", JsonValue.Parse("1e+30").ToString());
}
[Theory]
[InlineData("Fact\b\f\n\r\t\"\\/</\0x")]
[InlineData("x\ud800")]
[InlineData("\udfff\ud800")]
[InlineData("\ude03\ud912")]
[InlineData("\uc000\ubfff")]
[InlineData("\udfffx")]
public void JsonPrimitive_Roundtrip_ValidUnicode(string str)
{
string json = new JsonPrimitive(str).ToString();
new UTF8Encoding(false, true).GetBytes(json);
Assert.Equal(str, JsonValue.Parse(json));
}
[Fact]
public void JsonPrimitive_Roundtrip_ValidUnicode_AllChars()
{
for (int i = 0; i <= char.MaxValue; i++)
{
JsonPrimitive_Roundtrip_ValidUnicode("x" + (char)i);
}
}
// String handling: http://tools.ietf.org/html/rfc7159#section-7
[Fact]
public void JsonPrimitive_StringHandling()
{
Assert.Equal("\"Fact\"", new JsonPrimitive("Fact").ToString());
// Handling of characters
Assert.Equal("\"f\"", new JsonPrimitive('f').ToString());
Assert.Equal('f', (char)JsonValue.Parse("\"f\""));
// Control characters with special escape sequence
Assert.Equal("\"\\b\\f\\n\\r\\t\"", new JsonPrimitive("\b\f\n\r\t").ToString());
// Other characters which must be escaped
Assert.Equal(@"""\""\\""", new JsonPrimitive("\"\\").ToString());
// Control characters without special escape sequence
for (int i = 0; i < 32; i++)
{
if (i != '\b' && i != '\f' && i != '\n' && i != '\r' && i != '\t')
{
Assert.Equal("\"\\u" + i.ToString("x04") + "\"", new JsonPrimitive("" + (char)i).ToString());
}
}
// JSON does not require U+2028 and U+2029 to be escaped, but
// JavaScript does require this:
// http://stackoverflow.com/questions/2965293/javascript-parse-error-on-u2028-unicode-character/9168133#9168133
Assert.Equal("\"\\u2028\\u2029\"", new JsonPrimitive("\u2028\u2029").ToString());
// '/' also does not have to be escaped, but escaping it when
// preceeded by a '<' avoids problems with JSON in HTML <script> tags
Assert.Equal("\"<\\/\"", new JsonPrimitive("</").ToString());
// Don't escape '/' in other cases as this makes the JSON hard to read
Assert.Equal("\"/bar\"", new JsonPrimitive("/bar").ToString());
Assert.Equal("\"foo/bar\"", new JsonPrimitive("foo/bar").ToString());
// Valid strings should not be escaped:
Assert.Equal("\"\ud7ff\"", new JsonPrimitive("\ud7ff").ToString());
Assert.Equal("\"\ue000\"", new JsonPrimitive("\ue000").ToString());
Assert.Equal("\"\ud800\udc00\"", new JsonPrimitive("\ud800\udc00").ToString());
Assert.Equal("\"\ud912\ude03\"", new JsonPrimitive("\ud912\ude03").ToString());
Assert.Equal("\"\udbff\udfff\"", new JsonPrimitive("\udbff\udfff").ToString());
Assert.Equal("\"{\\\"\\\\uD800\\\\uDC00\\\": 1}\"", new JsonPrimitive("{\"\\uD800\\uDC00\": 1}").ToString());
}
[Fact]
public void GetEnumerator_ThrowsInvalidOperationException()
{
JsonValue value = JsonValue.Parse("1");
Assert.Throws<InvalidOperationException>(() => ((IEnumerable)value).GetEnumerator());
}
[Fact]
public void Count_ThrowsInvalidOperationException()
{
JsonValue value = JsonValue.Parse("1");
Assert.Throws<InvalidOperationException>(() => value.Count);
}
[Fact]
public void Item_Int_ThrowsInvalidOperationException()
{
JsonValue value = JsonValue.Parse("1");
Assert.Throws<InvalidOperationException>(() => value[0]);
Assert.Throws<InvalidOperationException>(() => value[0] = 0);
}
[Fact]
public void Item_String_ThrowsInvalidOperationException()
{
JsonValue value = JsonValue.Parse("1");
Assert.Throws<InvalidOperationException>(() => value["abc"]);
Assert.Throws<InvalidOperationException>(() => value["abc"] = 0);
}
[Fact]
public void ContainsKey_ThrowsInvalidOperationException()
{
JsonValue value = JsonValue.Parse("1");
Assert.Throws<InvalidOperationException>(() => value.ContainsKey("key"));
}
[Fact]
public void Save_Stream()
{
JsonSubValue value = new JsonSubValue();
using (MemoryStream stream = new MemoryStream())
{
value.Save(stream);
string json = Encoding.UTF8.GetString(stream.ToArray());
Assert.True(stream.CanWrite);
Assert.Equal("Hello", json);
}
}
[Fact]
public void Save_TextWriter()
{
JsonSubValue value = new JsonSubValue();
using (StringWriter writer = new StringWriter())
{
value.Save(writer);
string json = writer.ToString();
Assert.Equal("Hello", json);
}
}
[Fact]
public void Save_Null_ThrowsArgumentNullException()
{
JsonValue value = new JsonSubValue();
AssertExtensions.Throws<ArgumentNullException>("stream", () => value.Save((Stream)null));
}
[Fact]
public void ImplicitConversion_NullJsonValue_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => { bool i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { byte i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { char i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { decimal i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { double i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { float i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { int i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { long i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { sbyte i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { short i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { uint i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { ulong i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { ushort i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { DateTime i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { DateTimeOffset i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { TimeSpan i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { Guid i = (JsonValue)null; });
AssertExtensions.Throws<ArgumentNullException>("value", () => { Uri i = (JsonValue)null; });
}
[Fact]
public void ImplicitConversion_NotJsonPrimitive_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => { bool i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { byte i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { char i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { decimal i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { double i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { float i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { int i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { long i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { sbyte i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { short i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { string i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { uint i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { ulong i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { ushort i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { DateTime i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { DateTimeOffset i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { TimeSpan i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { Guid i = new JsonArray(); });
Assert.Throws<InvalidCastException>(() => { Uri i = new JsonArray(); });
}
[Fact]
public void ImplicitCast_Bool()
{
JsonPrimitive primitive = new JsonPrimitive(true);
bool toPrimitive = primitive;
Assert.True(toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_Byte()
{
JsonPrimitive primitive = new JsonPrimitive(1);
byte toPrimitive = primitive;
Assert.Equal(1, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_Char()
{
JsonPrimitive primitive = new JsonPrimitive(1);
char toPrimitive = primitive;
Assert.Equal(1, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_Decimal()
{
JsonPrimitive primitive = new JsonPrimitive(1m);
decimal toPrimitive = primitive;
Assert.Equal(1m, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_Double()
{
JsonPrimitive primitive = new JsonPrimitive(1);
double toPrimitive = primitive;
Assert.Equal(1.0, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_Float()
{
JsonPrimitive primitive = new JsonPrimitive(1);
float toPrimitive = primitive;
Assert.Equal(1.0f, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_Int()
{
JsonPrimitive primitive = new JsonPrimitive(1);
int toPrimitive = primitive;
Assert.Equal(1, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_Long()
{
JsonPrimitive primitive = new JsonPrimitive(1);
long toPrimitive = primitive;
Assert.Equal(1, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_SByte()
{
JsonPrimitive primitive = new JsonPrimitive(1);
sbyte toPrimitive = primitive;
Assert.Equal(1, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_Short()
{
JsonPrimitive primitive = new JsonPrimitive(1);
short toPrimitive = primitive;
Assert.Equal(1, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Theory]
[InlineData("abc")]
[InlineData(null)]
public void ImplicitCast_String(string value)
{
JsonPrimitive primitive = new JsonPrimitive(value);
string toPrimitive = primitive;
Assert.Equal(value, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_String_NullString()
{
string toPrimitive = (JsonPrimitive)null;
Assert.Equal(null, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(new JsonPrimitive((string)null), toPrimitive);
}
[Fact]
public void ImplicitCast_UInt()
{
JsonPrimitive primitive = new JsonPrimitive(1);
uint toPrimitive = primitive;
Assert.Equal((uint)1, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_ULong()
{
JsonPrimitive primitive = new JsonPrimitive(1);
ulong toPrimitive = primitive;
Assert.Equal((ulong)1, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_UShort()
{
JsonPrimitive primitive = new JsonPrimitive(1);
ushort toPrimitive = primitive;
Assert.Equal((ushort)1, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_DateTime()
{
JsonPrimitive primitive = new JsonPrimitive(DateTime.MinValue);
DateTime toPrimitive = primitive;
Assert.Equal(DateTime.MinValue, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_DateTimeOffset()
{
JsonPrimitive primitive = new JsonPrimitive(DateTimeOffset.MinValue);
DateTimeOffset toPrimitive = primitive;
Assert.Equal(DateTimeOffset.MinValue, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_TimeSpan()
{
JsonPrimitive primitive = new JsonPrimitive(TimeSpan.Zero);
TimeSpan toPrimitive = primitive;
Assert.Equal(TimeSpan.Zero, toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_Guid()
{
JsonPrimitive primitive = new JsonPrimitive(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
Guid toPrimitive = primitive;
Assert.Equal(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ImplicitCast_Uri()
{
JsonPrimitive primitive = new JsonPrimitive(new Uri("scheme://host/"));
Uri toPrimitive = primitive;
Assert.Equal(new Uri("scheme://host/"), toPrimitive);
JsonValue fromPrimitive = toPrimitive;
Assert.Equal(primitive, toPrimitive);
}
[Fact]
public void ToString_InvalidJsonType_ThrowsInvalidCastException()
{
InvalidJsonValue value = new InvalidJsonValue();
Assert.Throws<InvalidCastException>(() => value.ToString());
}
private static void Parse(string jsonString, Action<JsonValue> action)
{
action(JsonValue.Parse(jsonString));
using (StringReader textReader = new StringReader(jsonString))
{
action(JsonValue.Load(textReader));
}
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
action(JsonValue.Load(stream));
}
}
public class JsonSubValue : JsonValue
{
public override JsonType JsonType => JsonType.String;
public override void Save(TextWriter textWriter) => textWriter.Write("Hello");
}
public class InvalidJsonValue : JsonValue
{
public override JsonType JsonType => (JsonType)(-1);
}
}
}
| |
/*
* 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.Reflection;
using BulletDotNET;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
using log4net;
namespace OpenSim.Region.Physics.BulletDotNETPlugin
{
public class BulletDotNETCharacter : PhysicsActor
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public btRigidBody Body;
public btCollisionShape Shell;
public btVector3 tempVector1;
public btVector3 tempVector2;
public btVector3 tempVector3;
public btVector3 tempVector4;
public btVector3 tempVector5RayCast;
public btVector3 tempVector6RayCast;
public btVector3 tempVector7RayCast;
public btQuaternion tempQuat1;
public btTransform tempTrans1;
public ClosestNotMeRayResultCallback ClosestCastResult;
private btTransform m_bodyTransform;
private btVector3 m_bodyPosition;
private btVector3 m_CapsuleOrientationAxis;
private btQuaternion m_bodyOrientation;
private btDefaultMotionState m_bodyMotionState;
private btGeneric6DofConstraint m_aMotor;
// private Vector3 m_movementComparision;
private Vector3 m_position;
private Vector3 m_zeroPosition;
private bool m_zeroFlag = false;
private bool m_lastUpdateSent = false;
private Vector3 m_velocity;
private Vector3 m_target_velocity;
private Vector3 m_acceleration;
private Vector3 m_rotationalVelocity;
private bool m_pidControllerActive = true;
public float PID_D = 80.0f;
public float PID_P = 90.0f;
public float CAPSULE_RADIUS = 0.37f;
public float CAPSULE_LENGTH = 2.140599f;
public float heightFudgeFactor = 0.52f;
public float walkDivisor = 1.3f;
public float runDivisor = 0.8f;
private float m_mass = 80f;
public float m_density = 60f;
private bool m_flying = false;
private bool m_iscolliding = false;
private bool m_iscollidingGround = false;
private bool m_wascolliding = false;
private bool m_wascollidingGround = false;
private bool m_iscollidingObj = false;
private bool m_alwaysRun = false;
private bool m_hackSentFall = false;
private bool m_hackSentFly = false;
public uint m_localID = 0;
public bool m_returnCollisions = false;
// taints and their non-tainted counterparts
public bool m_isPhysical = false; // the current physical status
public bool m_tainted_isPhysical = false; // set when the physical status is tainted (false=not existing in physics engine, true=existing)
private float m_tainted_CAPSULE_LENGTH; // set when the capsule length changes.
private bool m_taintRemove = false;
// private bool m_taintedPosition = false;
// private Vector3 m_taintedPosition_value;
private Vector3 m_taintedForce;
private float m_buoyancy = 0f;
// private CollisionLocker ode;
// private string m_name = String.Empty;
private bool[] m_colliderarr = new bool[11];
private bool[] m_colliderGroundarr = new bool[11];
private BulletDotNETScene m_parent_scene;
public int m_eventsubscription = 0;
// private CollisionEventUpdate CollisionEventsThisFrame = new CollisionEventUpdate();
public BulletDotNETCharacter(string avName, BulletDotNETScene parent_scene, Vector3 pos, Vector3 size, float pid_d, float pid_p, float capsule_radius, float tensor, float density, float height_fudge_factor, float walk_divisor, float rundivisor)
{
m_position = pos;
m_zeroPosition = pos;
m_parent_scene = parent_scene;
PID_D = pid_d;
PID_P = pid_p;
CAPSULE_RADIUS = capsule_radius;
m_density = density;
heightFudgeFactor = height_fudge_factor;
walkDivisor = walk_divisor;
runDivisor = rundivisor;
for (int i = 0; i < 11; i++)
{
m_colliderarr[i] = false;
}
for (int i = 0; i < 11; i++)
{
m_colliderGroundarr[i] = false;
}
CAPSULE_LENGTH = (size.Z * 1.15f) - CAPSULE_RADIUS * 2.0f;
m_tainted_CAPSULE_LENGTH = CAPSULE_LENGTH;
m_isPhysical = false; // current status: no ODE information exists
m_tainted_isPhysical = true; // new tainted status: need to create ODE information
m_parent_scene.AddPhysicsActorTaint(this);
// m_name = avName;
tempVector1 = new btVector3(0, 0, 0);
tempVector2 = new btVector3(0, 0, 0);
tempVector3 = new btVector3(0, 0, 0);
tempVector4 = new btVector3(0, 0, 0);
tempVector5RayCast = new btVector3(0, 0, 0);
tempVector6RayCast = new btVector3(0, 0, 0);
tempVector7RayCast = new btVector3(0, 0, 0);
tempQuat1 = new btQuaternion(0, 0, 0, 1);
tempTrans1 = new btTransform(tempQuat1, tempVector1);
// m_movementComparision = new PhysicsVector(0, 0, 0);
m_CapsuleOrientationAxis = new btVector3(1, 0, 1);
}
/// <summary>
/// This creates the Avatar's physical Surrogate at the position supplied
/// </summary>
/// <param name="npositionX"></param>
/// <param name="npositionY"></param>
/// <param name="npositionZ"></param>
// WARNING: This MUST NOT be called outside of ProcessTaints, else we can have unsynchronized access
// to ODE internals. ProcessTaints is called from within thread-locked Simulate(), so it is the only
// place that is safe to call this routine AvatarGeomAndBodyCreation.
private void AvatarGeomAndBodyCreation(float npositionX, float npositionY, float npositionZ)
{
if (CAPSULE_LENGTH <= 0)
{
m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
CAPSULE_LENGTH = 0.01f;
}
if (CAPSULE_RADIUS <= 0)
{
m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
CAPSULE_RADIUS = 0.01f;
}
Shell = new btCapsuleShape(CAPSULE_RADIUS, CAPSULE_LENGTH);
if (m_bodyPosition == null)
m_bodyPosition = new btVector3(npositionX, npositionY, npositionZ);
m_bodyPosition.setValue(npositionX, npositionY, npositionZ);
if (m_bodyOrientation == null)
m_bodyOrientation = new btQuaternion(m_CapsuleOrientationAxis, (Utils.DEG_TO_RAD * 90));
if (m_bodyTransform == null)
m_bodyTransform = new btTransform(m_bodyOrientation, m_bodyPosition);
else
{
m_bodyTransform.Dispose();
m_bodyTransform = new btTransform(m_bodyOrientation, m_bodyPosition);
}
if (m_bodyMotionState == null)
m_bodyMotionState = new btDefaultMotionState(m_bodyTransform);
else
m_bodyMotionState.setWorldTransform(m_bodyTransform);
m_mass = Mass;
Body = new btRigidBody(m_mass, m_bodyMotionState, Shell);
Body.setUserPointer(new IntPtr((int)Body.Handle));
if (ClosestCastResult != null)
ClosestCastResult.Dispose();
ClosestCastResult = new ClosestNotMeRayResultCallback(Body);
m_parent_scene.AddRigidBody(Body);
Body.setActivationState(4);
if (m_aMotor != null)
{
if (m_aMotor.Handle != IntPtr.Zero)
{
m_parent_scene.getBulletWorld().removeConstraint(m_aMotor);
m_aMotor.Dispose();
}
m_aMotor = null;
}
m_aMotor = new btGeneric6DofConstraint(Body, m_parent_scene.TerrainBody,
m_parent_scene.TransZero,
m_parent_scene.TransZero, false);
m_aMotor.setAngularLowerLimit(m_parent_scene.VectorZero);
m_aMotor.setAngularUpperLimit(m_parent_scene.VectorZero);
}
public void Remove()
{
m_taintRemove = true;
}
public override bool Stopped
{
get { return m_zeroFlag; }
}
public override Vector3 Size
{
get { return new Vector3(CAPSULE_RADIUS * 2, CAPSULE_RADIUS * 2, CAPSULE_LENGTH); }
set
{
m_pidControllerActive = true;
Vector3 SetSize = value;
m_tainted_CAPSULE_LENGTH = (SetSize.Z * 1.15f) - CAPSULE_RADIUS * 2.0f;
//m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
Velocity = Vector3.Zero;
m_parent_scene.AddPhysicsActorTaint(this);
}
}
/// <summary>
/// turn the PID controller on or off.
/// The PID Controller will turn on all by itself in many situations
/// </summary>
/// <param name="status"></param>
public void SetPidStatus(bool status)
{
m_pidControllerActive = status;
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override uint LocalID
{
set { m_localID = value; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override void CrossingFailure()
{
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
public override Vector3 Position
{
get { return m_position; }
set
{
// m_taintedPosition_value = value;
m_position = value;
// m_taintedPosition = true;
}
}
public override float Mass
{
get
{
float AVvolume = (float)(Math.PI * Math.Pow(CAPSULE_RADIUS, 2) * CAPSULE_LENGTH);
return m_density * AVvolume;
}
}
public override Vector3 Force
{
get { return m_target_velocity; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void SetVolumeDetect(int param)
{
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 Velocity
{
get
{
if (m_zeroFlag)
return Vector3.Zero;
m_lastUpdateSent = false;
return m_velocity;
}
set
{
m_pidControllerActive = true;
m_target_velocity = value;
}
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Vector3 Acceleration
{
get { return m_acceleration; }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set
{
}
}
public override int PhysicsActorType
{
get { return (int)ActorTypes.Agent; }
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return m_flying; }
set { m_flying = value; }
}
public override bool SetAlwaysRun
{
get { return m_alwaysRun; }
set { m_alwaysRun = value; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
/// <summary>
/// Returns if the avatar is colliding in general.
/// This includes the ground and objects and avatar.
/// </summary>
public override bool IsColliding
{
get { return m_iscolliding; }
set
{
int i;
int truecount = 0;
int falsecount = 0;
if (m_colliderarr.Length >= 10)
{
for (i = 0; i < 10; i++)
{
m_colliderarr[i] = m_colliderarr[i + 1];
}
}
m_colliderarr[10] = value;
for (i = 0; i < 11; i++)
{
if (m_colliderarr[i])
{
truecount++;
}
else
{
falsecount++;
}
}
// Equal truecounts and false counts means we're colliding with something.
m_log.DebugFormat("[PHYSICS]: TrueCount:{0}, FalseCount:{1}",truecount,falsecount);
if (falsecount > 1.2 * truecount)
{
m_iscolliding = false;
}
else
{
m_iscolliding = true;
}
if (m_wascolliding != m_iscolliding)
{
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
m_wascolliding = m_iscolliding;
}
}
/// <summary>
/// Returns if an avatar is colliding with the ground
/// </summary>
public override bool CollidingGround
{
get { return m_iscollidingGround; }
set
{
// Collisions against the ground are not really reliable
// So, to get a consistant value we have to average the current result over time
// Currently we use 1 second = 10 calls to this.
int i;
int truecount = 0;
int falsecount = 0;
if (m_colliderGroundarr.Length >= 10)
{
for (i = 0; i < 10; i++)
{
m_colliderGroundarr[i] = m_colliderGroundarr[i + 1];
}
}
m_colliderGroundarr[10] = value;
for (i = 0; i < 11; i++)
{
if (m_colliderGroundarr[i])
{
truecount++;
}
else
{
falsecount++;
}
}
// Equal truecounts and false counts means we're colliding with something.
if (falsecount > 1.2 * truecount)
{
m_iscollidingGround = false;
}
else
{
m_iscollidingGround = true;
}
if (m_wascollidingGround != m_iscollidingGround)
{
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
m_wascollidingGround = m_iscollidingGround;
}
}
/// <summary>
/// Returns if the avatar is colliding with an object
/// </summary>
public override bool CollidingObj
{
get { return m_iscollidingObj; }
set
{
m_iscollidingObj = value;
if (value)
m_pidControllerActive = false;
else
m_pidControllerActive = true;
}
}
public override bool FloatOnWater
{
set { return; }
}
public override Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool Kinematic
{
get { return false; }
set { }
}
public override float Buoyancy
{
get { return m_buoyancy; }
set { m_buoyancy = value; }
}
public override Vector3 PIDTarget { set { return; } }
public override bool PIDActive { set { return; } }
public override float PIDTau { set { return; } }
public override bool PIDHoverActive
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
/// <summary>
/// Adds the force supplied to the Target Velocity
/// The PID controller takes this target velocity and tries to make it a reality
/// </summary>
/// <param name="force"></param>
/// <param name="pushforce">Is this a push by a script?</param>
public override void AddForce(Vector3 force, bool pushforce)
{
if (pushforce)
{
m_pidControllerActive = false;
force *= 100f;
doForce(force, false);
//System.Console.WriteLine("Push!");
//_target_velocity.X += force.X;
// _target_velocity.Y += force.Y;
//_target_velocity.Z += force.Z;
}
else
{
m_pidControllerActive = true;
m_target_velocity.X += force.X;
m_target_velocity.Y += force.Y;
m_target_velocity.Z += force.Z;
}
//m_lastUpdateSent = false;
}
public void doForce(Vector3 force, bool now)
{
tempVector3.setValue(force.X, force.Y, force.Z);
if (now)
{
Body.applyCentralForce(tempVector3);
}
else
{
m_taintedForce += force;
m_parent_scene.AddPhysicsActorTaint(this);
}
}
public void doImpulse(Vector3 force, bool now)
{
tempVector3.setValue(force.X, force.Y, force.Z);
if (now)
{
Body.applyCentralImpulse(tempVector3);
}
else
{
m_taintedForce += force;
m_parent_scene.AddPhysicsActorTaint(this);
}
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override void SetMomentum(Vector3 momentum)
{
}
public override void SubscribeEvents(int ms)
{
m_eventsubscription = ms;
m_parent_scene.addCollisionEventReporting(this);
}
public override void UnSubscribeEvents()
{
m_parent_scene.remCollisionEventReporting(this);
m_eventsubscription = 0;
}
public override bool SubscribedEvents()
{
if (m_eventsubscription > 0)
return true;
return false;
}
internal void Dispose()
{
if (Body.isInWorld())
m_parent_scene.removeFromWorld(Body);
if (m_aMotor.Handle != IntPtr.Zero)
m_parent_scene.getBulletWorld().removeConstraint(m_aMotor);
m_aMotor.Dispose(); m_aMotor = null;
ClosestCastResult.Dispose(); ClosestCastResult = null;
Body.Dispose(); Body = null;
Shell.Dispose(); Shell = null;
tempQuat1.Dispose();
tempTrans1.Dispose();
tempVector1.Dispose();
tempVector2.Dispose();
tempVector3.Dispose();
tempVector4.Dispose();
tempVector5RayCast.Dispose();
tempVector6RayCast.Dispose();
}
public void ProcessTaints(float timestep)
{
if (m_tainted_isPhysical != m_isPhysical)
{
if (m_tainted_isPhysical)
{
// Create avatar capsule and related ODE data
if (!(Shell == null && Body == null))
{
m_log.Warn("[PHYSICS]: re-creating the following avatar ODE data, even though it already exists - "
+ (Shell != null ? "Shell " : "")
+ (Body != null ? "Body " : ""));
}
AvatarGeomAndBodyCreation(m_position.X, m_position.Y, m_position.Z);
}
else
{
// destroy avatar capsule and related ODE data
Dispose();
tempVector1 = new btVector3(0, 0, 0);
tempVector2 = new btVector3(0, 0, 0);
tempVector3 = new btVector3(0, 0, 0);
tempVector4 = new btVector3(0, 0, 0);
tempVector5RayCast = new btVector3(0, 0, 0);
tempVector6RayCast = new btVector3(0, 0, 0);
tempVector7RayCast = new btVector3(0, 0, 0);
tempQuat1 = new btQuaternion(0, 0, 0, 1);
tempTrans1 = new btTransform(tempQuat1, tempVector1);
// m_movementComparision = new PhysicsVector(0, 0, 0);
m_CapsuleOrientationAxis = new btVector3(1, 0, 1);
}
m_isPhysical = m_tainted_isPhysical;
}
if (m_tainted_CAPSULE_LENGTH != CAPSULE_LENGTH)
{
if (Body != null)
{
m_pidControllerActive = true;
// no lock needed on _parent_scene.OdeLock because we are called from within the thread lock in OdePlugin's simulate()
//d.JointDestroy(Amotor);
float prevCapsule = CAPSULE_LENGTH;
CAPSULE_LENGTH = m_tainted_CAPSULE_LENGTH;
//m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
Dispose();
tempVector1 = new btVector3(0, 0, 0);
tempVector2 = new btVector3(0, 0, 0);
tempVector3 = new btVector3(0, 0, 0);
tempVector4 = new btVector3(0, 0, 0);
tempVector5RayCast = new btVector3(0, 0, 0);
tempVector6RayCast = new btVector3(0, 0, 0);
tempVector7RayCast = new btVector3(0, 0, 0);
tempQuat1 = new btQuaternion(0, 0, 0, 1);
tempTrans1 = new btTransform(tempQuat1, tempVector1);
// m_movementComparision = new PhysicsVector(0, 0, 0);
m_CapsuleOrientationAxis = new btVector3(1, 0, 1);
AvatarGeomAndBodyCreation(m_position.X, m_position.Y,
m_position.Z + (Math.Abs(CAPSULE_LENGTH - prevCapsule) * 2));
Velocity = Vector3.Zero;
}
else
{
m_log.Warn("[PHYSICS]: trying to change capsule size, but the following ODE data is missing - "
+ (Shell == null ? "Shell " : "")
+ (Body == null ? "Body " : ""));
}
}
if (m_taintRemove)
{
Dispose();
}
}
/// <summary>
/// Called from Simulate
/// This is the avatar's movement control + PID Controller
/// </summary>
/// <param name="timeStep"></param>
public void Move(float timeStep)
{
// no lock; for now it's only called from within Simulate()
// If the PID Controller isn't active then we set our force
// calculating base velocity to the current position
if (Body == null)
return;
tempTrans1.Dispose();
tempTrans1 = Body.getInterpolationWorldTransform();
tempVector1.Dispose();
tempVector1 = tempTrans1.getOrigin();
tempVector2.Dispose();
tempVector2 = Body.getInterpolationLinearVelocity();
if (m_pidControllerActive == false)
{
m_zeroPosition.X = tempVector1.getX();
m_zeroPosition.Y = tempVector1.getY();
m_zeroPosition.Z = tempVector1.getZ();
}
//PidStatus = true;
Vector3 vec = Vector3.Zero;
Vector3 vel = new Vector3(tempVector2.getX(), tempVector2.getY(), tempVector2.getZ());
float movementdivisor = 1f;
if (!m_alwaysRun)
{
movementdivisor = walkDivisor;
}
else
{
movementdivisor = runDivisor;
}
// if velocity is zero, use position control; otherwise, velocity control
if (m_target_velocity.X == 0.0f && m_target_velocity.Y == 0.0f && m_target_velocity.Z == 0.0f && m_iscolliding)
{
// keep track of where we stopped. No more slippin' & slidin'
if (!m_zeroFlag)
{
m_zeroFlag = true;
m_zeroPosition.X = tempVector1.getX();
m_zeroPosition.Y = tempVector1.getY();
m_zeroPosition.Z = tempVector1.getZ();
}
if (m_pidControllerActive)
{
// We only want to deactivate the PID Controller if we think we want to have our surrogate
// react to the physics scene by moving it's position.
// Avatar to Avatar collisions
// Prim to avatar collisions
Vector3 pos = new Vector3(tempVector1.getX(), tempVector1.getY(), tempVector1.getZ());
vec.X = (m_target_velocity.X - vel.X) * (PID_D) + (m_zeroPosition.X - pos.X) * (PID_P * 2);
vec.Y = (m_target_velocity.Y - vel.Y) * (PID_D) + (m_zeroPosition.Y - pos.Y) * (PID_P * 2);
if (m_flying)
{
vec.Z = (m_target_velocity.Z - vel.Z) * (PID_D) + (m_zeroPosition.Z - pos.Z) * PID_P;
}
}
//PidStatus = true;
}
else
{
m_pidControllerActive = true;
m_zeroFlag = false;
if (m_iscolliding && !m_flying)
{
// We're standing on something
vec.X = ((m_target_velocity.X / movementdivisor) - vel.X) * (PID_D);
vec.Y = ((m_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D);
}
else if (m_iscolliding && m_flying)
{
// We're flying and colliding with something
vec.X = ((m_target_velocity.X / movementdivisor) - vel.X) * (PID_D / 16);
vec.Y = ((m_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D / 16);
}
else if (!m_iscolliding && m_flying)
{
// we're in mid air suspended
vec.X = ((m_target_velocity.X / movementdivisor) - vel.X) * (PID_D / 6);
vec.Y = ((m_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D / 6);
// We don't want linear velocity to cause our avatar to bounce, so we check target Z and actual velocity X, Y
// rebound preventing
if (m_target_velocity.Z < 0.025f && m_velocity.X < 0.25f && m_velocity.Y < 0.25f)
m_zeroFlag = true;
}
if (m_iscolliding && !m_flying && m_target_velocity.Z > 0.0f)
{
// We're colliding with something and we're not flying but we're moving
// This means we're walking or running.
Vector3 pos = new Vector3(tempVector1.getX(), tempVector1.getY(), tempVector1.getZ());
vec.Z = (m_target_velocity.Z - vel.Z) * PID_D + (m_zeroPosition.Z - pos.Z) * PID_P;
if (m_target_velocity.X > 0)
{
vec.X = ((m_target_velocity.X - vel.X) / 1.2f) * PID_D;
}
if (m_target_velocity.Y > 0)
{
vec.Y = ((m_target_velocity.Y - vel.Y) / 1.2f) * PID_D;
}
}
else if (!m_iscolliding && !m_flying)
{
// we're not colliding and we're not flying so that means we're falling!
// m_iscolliding includes collisions with the ground.
// d.Vector3 pos = d.BodyGetPosition(Body);
if (m_target_velocity.X > 0)
{
vec.X = ((m_target_velocity.X - vel.X) / 1.2f) * PID_D;
}
if (m_target_velocity.Y > 0)
{
vec.Y = ((m_target_velocity.Y - vel.Y) / 1.2f) * PID_D;
}
}
if (m_flying)
{
vec.Z = (m_target_velocity.Z - vel.Z) * (PID_D);
}
}
if (m_flying)
{
// Slight PID correction
vec.Z += (((-1 * m_parent_scene.gravityz) * m_mass) * 0.06f);
//auto fly height. Kitto Flora
//d.Vector3 pos = d.BodyGetPosition(Body);
float target_altitude = m_parent_scene.GetTerrainHeightAtXY(m_position.X, m_position.Y) + 5.0f;
if (m_position.Z < target_altitude)
{
vec.Z += (target_altitude - m_position.Z) * PID_P * 5.0f;
}
}
if (Body != null && (((m_target_velocity.X > 0.2f || m_target_velocity.X < -0.2f) || (m_target_velocity.Y > 0.2f || m_target_velocity.Y < -0.2f))))
{
Body.setFriction(0.001f);
//m_log.DebugFormat("[PHYSICS]: Avatar force applied: {0}, Target:{1}", vec.ToString(), m_target_velocity.ToString());
}
if (Body != null)
{
int activationstate = Body.getActivationState();
if (activationstate == 0)
{
Body.forceActivationState(1);
}
}
doImpulse(vec, true);
}
/// <summary>
/// Updates the reported position and velocity. This essentially sends the data up to ScenePresence.
/// </summary>
public void UpdatePositionAndVelocity()
{
if (Body == null)
return;
//int val = Environment.TickCount;
CheckIfStandingOnObject();
//m_log.DebugFormat("time:{0}", Environment.TickCount - val);
//IsColliding = Body.checkCollideWith(m_parent_scene.TerrainBody);
tempTrans1.Dispose();
tempTrans1 = Body.getInterpolationWorldTransform();
tempVector1.Dispose();
tempVector1 = tempTrans1.getOrigin();
tempVector2.Dispose();
tempVector2 = Body.getInterpolationLinearVelocity();
// no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit!
Vector3 vec = new Vector3(tempVector1.getX(), tempVector1.getY(), tempVector1.getZ());
// kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!)
if (vec.X < -10.0f) vec.X = 0.0f;
if (vec.Y < -10.0f) vec.Y = 0.0f;
if (vec.X > (int)Constants.RegionSize + 10.2f) vec.X = (int)Constants.RegionSize + 10.2f;
if (vec.Y > (int)Constants.RegionSize + 10.2f) vec.Y = (int)Constants.RegionSize + 10.2f;
m_position.X = vec.X;
m_position.Y = vec.Y;
m_position.Z = vec.Z;
// Did we move last? = zeroflag
// This helps keep us from sliding all over
if (m_zeroFlag)
{
m_velocity.X = 0.0f;
m_velocity.Y = 0.0f;
m_velocity.Z = 0.0f;
// Did we send out the 'stopped' message?
if (!m_lastUpdateSent)
{
m_lastUpdateSent = true;
//base.RequestPhysicsterseUpdate();
}
}
else
{
m_lastUpdateSent = false;
vec = new Vector3(tempVector2.getX(), tempVector2.getY(), tempVector2.getZ());
m_velocity.X = (vec.X);
m_velocity.Y = (vec.Y);
m_velocity.Z = (vec.Z);
//m_log.Debug(m_target_velocity);
if (m_velocity.Z < -6 && !m_hackSentFall)
{
m_hackSentFall = true;
m_pidControllerActive = false;
}
else if (m_flying && !m_hackSentFly)
{
//m_hackSentFly = true;
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
else
{
m_hackSentFly = false;
m_hackSentFall = false;
}
}
if (Body != null)
{
if (Body.getFriction() < 0.9f)
Body.setFriction(0.9f);
}
//if (Body != null)
// Body.clearForces();
}
public void CheckIfStandingOnObject()
{
float capsuleHalfHeight = ((CAPSULE_LENGTH + 2*CAPSULE_RADIUS)*0.5f);
tempVector5RayCast.setValue(m_position.X, m_position.Y, m_position.Z);
tempVector6RayCast.setValue(m_position.X, m_position.Y, m_position.Z - 1 * capsuleHalfHeight * 1.1f);
ClosestCastResult.Dispose();
ClosestCastResult = new ClosestNotMeRayResultCallback(Body);
try
{
m_parent_scene.getBulletWorld().rayTest(tempVector5RayCast, tempVector6RayCast, ClosestCastResult);
}
catch (AccessViolationException)
{
m_log.Debug("BAD!");
}
if (ClosestCastResult.hasHit())
{
if (tempVector7RayCast != null)
tempVector7RayCast.Dispose();
//tempVector7RayCast = ClosestCastResult.getHitPointWorld();
/*if (tempVector7RayCast == null) // null == no result also
{
CollidingObj = false;
IsColliding = false;
CollidingGround = false;
return;
}
float zVal = tempVector7RayCast.getZ();
if (zVal != 0)
m_log.Debug("[PHYSICS]: HAAAA");
if (zVal < m_position.Z && zVal > ((CAPSULE_LENGTH + 2 * CAPSULE_RADIUS) *0.5f))
{
CollidingObj = true;
IsColliding = true;
}
else
{
CollidingObj = false;
IsColliding = false;
CollidingGround = false;
}*/
//height+2*radius = capsule full length
//CollidingObj = true;
//IsColliding = true;
m_iscolliding = true;
}
else
{
//CollidingObj = false;
//IsColliding = false;
//CollidingGround = false;
m_iscolliding = false;
}
}
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.IO;
using Belikov.GenuineChannels.Messaging;
namespace Belikov.GenuineChannels.Logbook
{
/// <summary>
/// Implements writing of log messages into a memory stream. The implementation will ignore all messages if the summary size of
/// put messages exceed the specified boundary.
/// </summary>
public class MemoryWritingStream : Stream
{
/// <summary>
/// Constructs an instance of the MemoryWritingStream class.
/// </summary>
/// <param name="maximumSize">The maximum size of space allocated for debugging messages.</param>
public MemoryWritingStream(int maximumSize)
{
this._maximumSize = maximumSize;
}
/// <summary>
/// Gets an object that can be used to synchronize access to this instance.
/// </summary>
public object SyncRoot
{
get
{
return this;
}
}
/// <summary>
/// Gets or sets an indication of whether the log records can be written into this instance.
/// </summary>
public bool Enabled
{
get
{
lock (this.SyncRoot)
{
return this._enabled;
}
}
set
{
lock (this.SyncRoot)
{
this._enabled = value;
}
}
}
private bool _enabled = true;
/// <summary>
/// Stops logging and releases all memory chunks.
/// </summary>
public void StopLogging()
{
this.Enabled = false;
this._baseStream.WriteTo(Stream.Null);
}
#region -- Allocated Size counting ---------------------------------------------------------
private int _bytesWritten = 0;
private int _maximumSize;
private bool _isCurrentRecordIgnored = true;
/// <summary>
/// Checks whether the current record must be ignored.
/// </summary>
private void CheckIfAllowedSizeExceeded()
{
this._isCurrentRecordIgnored = ( ! this.Enabled ) || this._bytesWritten >= this._maximumSize;
}
#endregion
#region -- Writing -------------------------------------------------------------------------
private GenuineChunkedStream _baseStream = new GenuineChunkedStream(true);
private bool _isRecordStarted = false;
private int _sizeOfRecord = 0;
/// <summary>
/// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
public override void Write(byte[] buffer, int offset, int count)
{
lock (this.SyncRoot)
{
if (! this._isRecordStarted)
{
this.CheckIfAllowedSizeExceeded();
this._isRecordStarted = true;
}
if (! this._isCurrentRecordIgnored)
{
this._baseStream.Write(buffer, offset, count);
this._sizeOfRecord += count;
}
}
}
/// <summary>
/// Writes a byte to the current position in the stream and advances the position within the stream by one byte.
/// </summary>
/// <param name="val">The byte to write to the stream.</param>
public override void WriteByte(byte val)
{
lock (this.SyncRoot)
{
if (! this._isRecordStarted)
{
this.CheckIfAllowedSizeExceeded();
this._isRecordStarted = true;
}
if (! this._isCurrentRecordIgnored)
{
this._baseStream.WriteByte(val);
this._sizeOfRecord ++;
}
}
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
public override void Flush()
{
lock (this.SyncRoot)
{
this._baseStream.Flush();
this._isRecordStarted = false;
this._bytesWritten += this._sizeOfRecord;
this._sizeOfRecord = 0;
}
}
#endregion
#region -- Reading -------------------------------------------------------------------------
/// <summary>
/// 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.</param>
/// <param name="offset">The zero-based byte offset in 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.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
lock (this.SyncRoot)
{
int bytesRead = this._baseStream.Read(buffer, offset, Math.Min(this._bytesWritten - this._sizeOfRecord, count));
this._bytesWritten -= bytesRead;
return bytesRead;
}
}
#endregion
#region -- Insignificat Stream members -----------------------------------------------------
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
public override bool CanRead
{
get
{
return true;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
public override bool CanSeek
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
public override bool CanWrite
{
get
{
return true;
}
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
public override long Length
{
get
{
// is used for tests
return this._bytesWritten;
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// Always fires NotSupportedException exception.
/// </summary>
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
/// <summary>
/// Closes the stream.
/// </summary>
public override void Close()
{
}
/// <summary>
/// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
/// </summary>
/// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>
public override int ReadByte()
{
throw new NotSupportedException();
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type 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 offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Sets the length of the current stream.
/// </summary>
/// <param name="val">The desired length of the current stream in bytes.</param>
public override void SetLength(long val)
{
throw new NotSupportedException();
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Microsoft.WindowsAzure.MobileServices
{
internal abstract class ExpressionVisitor
{
protected ExpressionVisitor()
{
}
public virtual Expression Visit(Expression exp)
{
if (exp == null)
{
return exp;
}
switch (exp.NodeType)
{
case ExpressionType.UnaryPlus:
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
return this.VisitUnary((UnaryExpression)exp);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
return this.VisitBinary((BinaryExpression)exp);
case ExpressionType.TypeIs:
return this.VisitTypeIs((TypeBinaryExpression)exp);
case ExpressionType.Conditional:
return this.VisitConditional((ConditionalExpression)exp);
case ExpressionType.Constant:
return this.VisitConstant((ConstantExpression)exp);
case ExpressionType.Parameter:
return this.VisitParameter((ParameterExpression)exp);
case ExpressionType.MemberAccess:
return this.VisitMember((MemberExpression)exp);
case ExpressionType.Call:
return this.VisitMethodCall((MethodCallExpression)exp);
case ExpressionType.Lambda:
return this.VisitLambda((LambdaExpression)exp);
case ExpressionType.New:
return this.VisitNew((NewExpression)exp);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return this.VisitNewArray((NewArrayExpression)exp);
case ExpressionType.Invoke:
return this.VisitInvocation((InvocationExpression)exp);
case ExpressionType.MemberInit:
return this.VisitMemberInit((MemberInitExpression)exp);
case ExpressionType.ListInit:
return this.VisitListInit((ListInitExpression)exp);
default:
throw new NotSupportedException(string.Format("Unhandled expression type: '{0}'", exp.NodeType));
}
}
protected virtual MemberBinding VisitBinding(MemberBinding binding)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
return this.VisitMemberAssignment((MemberAssignment)binding);
case MemberBindingType.MemberBinding:
return this.VisitMemberMemberBinding((MemberMemberBinding)binding);
case MemberBindingType.ListBinding:
return this.VisitMemberListBinding((MemberListBinding)binding);
default:
throw new NotSupportedException(string.Format("Unhandled binding type '{0}'", binding.BindingType));
}
}
protected virtual ElementInit VisitElementInitializer(ElementInit initializer)
{
ReadOnlyCollection<Expression> arguments = this.VisitExpressionList(initializer.Arguments);
if (arguments != initializer.Arguments)
{
return Expression.ElementInit(initializer.AddMethod, arguments);
}
return initializer;
}
protected virtual Expression VisitUnary(UnaryExpression u)
{
Expression operand = this.Visit(u.Operand);
if (operand != u.Operand)
{
return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method);
}
return u;
}
protected virtual Expression VisitBinary(BinaryExpression b)
{
Expression left = this.Visit(b.Left);
Expression right = this.Visit(b.Right);
Expression conversion = this.Visit(b.Conversion);
if (left != b.Left || right != b.Right || conversion != b.Conversion)
{
if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null)
{
return Expression.Coalesce(left, right, conversion as LambdaExpression);
}
else
{
return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
}
}
return b;
}
protected virtual Expression VisitTypeIs(TypeBinaryExpression b)
{
Expression expr = this.Visit(b.Expression);
if (expr != b.Expression)
{
return Expression.TypeIs(expr, b.TypeOperand);
}
return b;
}
protected virtual Expression VisitConstant(ConstantExpression c)
{
return c;
}
protected virtual Expression VisitConditional(ConditionalExpression c)
{
Expression test = this.Visit(c.Test);
Expression ifTrue = this.Visit(c.IfTrue);
Expression ifFalse = this.Visit(c.IfFalse);
if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse)
{
return Expression.Condition(test, ifTrue, ifFalse);
}
return c;
}
protected virtual Expression VisitParameter(ParameterExpression p)
{
return p;
}
protected virtual Expression VisitMember(MemberExpression m)
{
Expression exp = this.Visit(m.Expression);
if (exp != m.Expression)
{
return Expression.MakeMemberAccess(exp, m.Member);
}
return m;
}
protected virtual Expression VisitMethodCall(MethodCallExpression m)
{
Expression obj = this.Visit(m.Object);
IEnumerable<Expression> args = this.VisitExpressionList(m.Arguments);
if (obj != m.Object || args != m.Arguments)
{
return Expression.Call(obj, m.Method, args);
}
return m;
}
protected virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original)
{
List<Expression> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
Expression p = this.Visit(original[i]);
if (list != null)
{
list.Add(p);
}
else if (p != original[i])
{
list = new List<Expression>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(p);
}
}
if (list != null)
{
return new ReadOnlyCollection<Expression>(list);
}
return original;
}
protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment)
{
Expression e = this.Visit(assignment.Expression);
if (e != assignment.Expression)
{
return Expression.Bind(assignment.Member, e);
}
return assignment;
}
protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding)
{
IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings);
if (bindings != binding.Bindings)
{
return Expression.MemberBind(binding.Member, bindings);
}
return binding;
}
protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding)
{
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers);
if (initializers != binding.Initializers)
{
return Expression.ListBind(binding.Member, initializers);
}
return binding;
}
protected virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original)
{
List<MemberBinding> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
MemberBinding b = this.VisitBinding(original[i]);
if (list != null)
{
list.Add(b);
}
else if (b != original[i])
{
list = new List<MemberBinding>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(b);
}
}
if (list != null)
{
return list;
}
return original;
}
protected virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original)
{
List<ElementInit> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
ElementInit init = this.VisitElementInitializer(original[i]);
if (list != null)
{
list.Add(init);
}
else if (init != original[i])
{
list = new List<ElementInit>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(init);
}
}
if (list != null)
{
return list;
}
return original;
}
protected virtual Expression VisitLambda(LambdaExpression lambda)
{
Expression body = this.Visit(lambda.Body);
// make sure we also visit the ParameterExpressions here.
ParameterExpression[] parameters = lambda.Parameters.Select(p => (ParameterExpression)this.Visit(p)).ToArray();
if (body != lambda.Body || !parameters.SequenceEqual(lambda.Parameters))
{
return Expression.Lambda(lambda.Type, body, parameters);
}
return lambda;
}
protected virtual NewExpression VisitNew(NewExpression nex)
{
IEnumerable<Expression> args = this.VisitExpressionList(nex.Arguments);
if (args != nex.Arguments)
{
if (nex.Members != null)
{
return Expression.New(nex.Constructor, args, nex.Members);
}
else
{
return Expression.New(nex.Constructor, args);
}
}
return nex;
}
protected virtual Expression VisitMemberInit(MemberInitExpression init)
{
NewExpression n = this.VisitNew(init.NewExpression);
IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings);
if (n != init.NewExpression || bindings != init.Bindings)
{
return Expression.MemberInit(n, bindings);
}
return init;
}
protected virtual Expression VisitListInit(ListInitExpression init)
{
NewExpression n = this.VisitNew(init.NewExpression);
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers);
if (n != init.NewExpression || initializers != init.Initializers)
{
return Expression.ListInit(n, initializers);
}
return init;
}
protected virtual Expression VisitNewArray(NewArrayExpression na)
{
IEnumerable<Expression> exprs = this.VisitExpressionList(na.Expressions);
if (exprs != na.Expressions)
{
if (na.NodeType == ExpressionType.NewArrayInit)
{
return Expression.NewArrayInit(na.Type.GetElementType(), exprs);
}
else
{
return Expression.NewArrayBounds(na.Type.GetElementType(), exprs);
}
}
return na;
}
protected virtual Expression VisitInvocation(InvocationExpression iv)
{
IEnumerable<Expression> args = this.VisitExpressionList(iv.Arguments);
Expression expr = this.Visit(iv.Expression);
if (args != iv.Arguments || expr != iv.Expression)
{
return Expression.Invoke(expr, args);
}
return iv;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/datastore/v1/entity.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Datastore.V1 {
/// <summary>Holder for reflection information generated from google/datastore/v1/entity.proto</summary>
public static partial class EntityReflection {
#region Descriptor
/// <summary>File descriptor for google/datastore/v1/entity.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static EntityReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiBnb29nbGUvZGF0YXN0b3JlL3YxL2VudGl0eS5wcm90bxITZ29vZ2xlLmRh",
"dGFzdG9yZS52MRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90bxocZ29v",
"Z2xlL3Byb3RvYnVmL3N0cnVjdC5wcm90bxofZ29vZ2xlL3Byb3RvYnVmL3Rp",
"bWVzdGFtcC5wcm90bxoYZ29vZ2xlL3R5cGUvbGF0bG5nLnByb3RvIjcKC1Bh",
"cnRpdGlvbklkEhIKCnByb2plY3RfaWQYAiABKAkSFAoMbmFtZXNwYWNlX2lk",
"GAQgASgJIrcBCgNLZXkSNgoMcGFydGl0aW9uX2lkGAEgASgLMiAuZ29vZ2xl",
"LmRhdGFzdG9yZS52MS5QYXJ0aXRpb25JZBIyCgRwYXRoGAIgAygLMiQuZ29v",
"Z2xlLmRhdGFzdG9yZS52MS5LZXkuUGF0aEVsZW1lbnQaRAoLUGF0aEVsZW1l",
"bnQSDAoEa2luZBgBIAEoCRIMCgJpZBgCIAEoA0gAEg4KBG5hbWUYAyABKAlI",
"AEIJCgdpZF90eXBlIjgKCkFycmF5VmFsdWUSKgoGdmFsdWVzGAEgAygLMhou",
"Z29vZ2xlLmRhdGFzdG9yZS52MS5WYWx1ZSLxAwoFVmFsdWUSMAoKbnVsbF92",
"YWx1ZRgLIAEoDjIaLmdvb2dsZS5wcm90b2J1Zi5OdWxsVmFsdWVIABIXCg1i",
"b29sZWFuX3ZhbHVlGAEgASgISAASFwoNaW50ZWdlcl92YWx1ZRgCIAEoA0gA",
"EhYKDGRvdWJsZV92YWx1ZRgDIAEoAUgAEjUKD3RpbWVzdGFtcF92YWx1ZRgK",
"IAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBIABItCglrZXlfdmFs",
"dWUYBSABKAsyGC5nb29nbGUuZGF0YXN0b3JlLnYxLktleUgAEhYKDHN0cmlu",
"Z192YWx1ZRgRIAEoCUgAEhQKCmJsb2JfdmFsdWUYEiABKAxIABIuCg9nZW9f",
"cG9pbnRfdmFsdWUYCCABKAsyEy5nb29nbGUudHlwZS5MYXRMbmdIABIzCgxl",
"bnRpdHlfdmFsdWUYBiABKAsyGy5nb29nbGUuZGF0YXN0b3JlLnYxLkVudGl0",
"eUgAEjYKC2FycmF5X3ZhbHVlGAkgASgLMh8uZ29vZ2xlLmRhdGFzdG9yZS52",
"MS5BcnJheVZhbHVlSAASDwoHbWVhbmluZxgOIAEoBRIcChRleGNsdWRlX2Zy",
"b21faW5kZXhlcxgTIAEoCEIMCgp2YWx1ZV90eXBlIr8BCgZFbnRpdHkSJQoD",
"a2V5GAEgASgLMhguZ29vZ2xlLmRhdGFzdG9yZS52MS5LZXkSPwoKcHJvcGVy",
"dGllcxgDIAMoCzIrLmdvb2dsZS5kYXRhc3RvcmUudjEuRW50aXR5LlByb3Bl",
"cnRpZXNFbnRyeRpNCg9Qcm9wZXJ0aWVzRW50cnkSCwoDa2V5GAEgASgJEikK",
"BXZhbHVlGAIgASgLMhouZ29vZ2xlLmRhdGFzdG9yZS52MS5WYWx1ZToCOAFC",
"KAoXY29tLmdvb2dsZS5kYXRhc3RvcmUudjFCC0VudGl0eVByb3RvUAFiBnBy",
"b3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Type.LatlngReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Datastore.V1.PartitionId), global::Google.Datastore.V1.PartitionId.Parser, new[]{ "ProjectId", "NamespaceId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Datastore.V1.Key), global::Google.Datastore.V1.Key.Parser, new[]{ "PartitionId", "Path" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Datastore.V1.Key.Types.PathElement), global::Google.Datastore.V1.Key.Types.PathElement.Parser, new[]{ "Kind", "Id", "Name" }, new[]{ "IdType" }, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Datastore.V1.ArrayValue), global::Google.Datastore.V1.ArrayValue.Parser, new[]{ "Values" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Datastore.V1.Value), global::Google.Datastore.V1.Value.Parser, new[]{ "NullValue", "BooleanValue", "IntegerValue", "DoubleValue", "TimestampValue", "KeyValue", "StringValue", "BlobValue", "GeoPointValue", "EntityValue", "ArrayValue", "Meaning", "ExcludeFromIndexes" }, new[]{ "ValueType" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Datastore.V1.Entity), global::Google.Datastore.V1.Entity.Parser, new[]{ "Key", "Properties" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, })
}));
}
#endregion
}
#region Messages
/// <summary>
/// A partition ID identifies a grouping of entities. The grouping is always
/// by project and namespace, however the namespace ID may be empty.
///
/// A partition ID contains several dimensions:
/// project ID and namespace ID.
///
/// Partition dimensions:
///
/// - May be `""`.
/// - Must be valid UTF-8 bytes.
/// - Must have values that match regex `[A-Za-z\d\.\-_]{1,100}`
/// If the value of any dimension matches regex `__.*__`, the partition is
/// reserved/read-only.
/// A reserved/read-only partition ID is forbidden in certain documented
/// contexts.
///
/// Foreign partition IDs (in which the project ID does
/// not match the context project ID ) are discouraged.
/// Reads and writes of foreign partition IDs may fail if the project is not in an active state.
/// </summary>
public sealed partial class PartitionId : pb::IMessage<PartitionId> {
private static readonly pb::MessageParser<PartitionId> _parser = new pb::MessageParser<PartitionId>(() => new PartitionId());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PartitionId> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Datastore.V1.EntityReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PartitionId() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PartitionId(PartitionId other) : this() {
projectId_ = other.projectId_;
namespaceId_ = other.namespaceId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PartitionId Clone() {
return new PartitionId(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 2;
private string projectId_ = "";
/// <summary>
/// The ID of the project to which the entities belong.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "namespace_id" field.</summary>
public const int NamespaceIdFieldNumber = 4;
private string namespaceId_ = "";
/// <summary>
/// If not empty, the ID of the namespace to which the entities belong.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string NamespaceId {
get { return namespaceId_; }
set {
namespaceId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PartitionId);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PartitionId other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (NamespaceId != other.NamespaceId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (NamespaceId.Length != 0) hash ^= NamespaceId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ProjectId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(ProjectId);
}
if (NamespaceId.Length != 0) {
output.WriteRawTag(34);
output.WriteString(NamespaceId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (NamespaceId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NamespaceId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PartitionId other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.NamespaceId.Length != 0) {
NamespaceId = other.NamespaceId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 18: {
ProjectId = input.ReadString();
break;
}
case 34: {
NamespaceId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// A unique identifier for an entity.
/// If a key's partition ID or any of its path kinds or names are
/// reserved/read-only, the key is reserved/read-only.
/// A reserved/read-only key is forbidden in certain documented contexts.
/// </summary>
public sealed partial class Key : pb::IMessage<Key> {
private static readonly pb::MessageParser<Key> _parser = new pb::MessageParser<Key>(() => new Key());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Key> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Datastore.V1.EntityReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Key() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Key(Key other) : this() {
PartitionId = other.partitionId_ != null ? other.PartitionId.Clone() : null;
path_ = other.path_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Key Clone() {
return new Key(this);
}
/// <summary>Field number for the "partition_id" field.</summary>
public const int PartitionIdFieldNumber = 1;
private global::Google.Datastore.V1.PartitionId partitionId_;
/// <summary>
/// Entities are partitioned into subsets, currently identified by a project
/// ID and namespace ID.
/// Queries are scoped to a single partition.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Datastore.V1.PartitionId PartitionId {
get { return partitionId_; }
set {
partitionId_ = value;
}
}
/// <summary>Field number for the "path" field.</summary>
public const int PathFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Datastore.V1.Key.Types.PathElement> _repeated_path_codec
= pb::FieldCodec.ForMessage(18, global::Google.Datastore.V1.Key.Types.PathElement.Parser);
private readonly pbc::RepeatedField<global::Google.Datastore.V1.Key.Types.PathElement> path_ = new pbc::RepeatedField<global::Google.Datastore.V1.Key.Types.PathElement>();
/// <summary>
/// The entity path.
/// An entity path consists of one or more elements composed of a kind and a
/// string or numerical identifier, which identify entities. The first
/// element identifies a _root entity_, the second element identifies
/// a _child_ of the root entity, the third element identifies a child of the
/// second entity, and so forth. The entities identified by all prefixes of
/// the path are called the element's _ancestors_.
///
/// An entity path is always fully complete: *all* of the entity's ancestors
/// are required to be in the path along with the entity identifier itself.
/// The only exception is that in some documented cases, the identifier in the
/// last path element (for the entity) itself may be omitted. For example,
/// the last path element of the key of `Mutation.insert` may have no
/// identifier.
///
/// A path can never be empty, and a path can have at most 100 elements.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Datastore.V1.Key.Types.PathElement> Path {
get { return path_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Key);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Key other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(PartitionId, other.PartitionId)) return false;
if(!path_.Equals(other.path_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (partitionId_ != null) hash ^= PartitionId.GetHashCode();
hash ^= path_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (partitionId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(PartitionId);
}
path_.WriteTo(output, _repeated_path_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (partitionId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PartitionId);
}
size += path_.CalculateSize(_repeated_path_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Key other) {
if (other == null) {
return;
}
if (other.partitionId_ != null) {
if (partitionId_ == null) {
partitionId_ = new global::Google.Datastore.V1.PartitionId();
}
PartitionId.MergeFrom(other.PartitionId);
}
path_.Add(other.path_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (partitionId_ == null) {
partitionId_ = new global::Google.Datastore.V1.PartitionId();
}
input.ReadMessage(partitionId_);
break;
}
case 18: {
path_.AddEntriesFrom(input, _repeated_path_codec);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the Key message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// A (kind, ID/name) pair used to construct a key path.
///
/// If either name or ID is set, the element is complete.
/// If neither is set, the element is incomplete.
/// </summary>
public sealed partial class PathElement : pb::IMessage<PathElement> {
private static readonly pb::MessageParser<PathElement> _parser = new pb::MessageParser<PathElement>(() => new PathElement());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PathElement> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Datastore.V1.Key.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PathElement() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PathElement(PathElement other) : this() {
kind_ = other.kind_;
switch (other.IdTypeCase) {
case IdTypeOneofCase.Id:
Id = other.Id;
break;
case IdTypeOneofCase.Name:
Name = other.Name;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PathElement Clone() {
return new PathElement(this);
}
/// <summary>Field number for the "kind" field.</summary>
public const int KindFieldNumber = 1;
private string kind_ = "";
/// <summary>
/// The kind of the entity.
/// A kind matching regex `__.*__` is reserved/read-only.
/// A kind must not contain more than 1500 bytes when UTF-8 encoded.
/// Cannot be `""`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Kind {
get { return kind_; }
set {
kind_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 2;
/// <summary>
/// The auto-allocated ID of the entity.
/// Never equal to zero. Values less than zero are discouraged and may not
/// be supported in the future.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Id {
get { return idTypeCase_ == IdTypeOneofCase.Id ? (long) idType_ : 0L; }
set {
idType_ = value;
idTypeCase_ = IdTypeOneofCase.Id;
}
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 3;
/// <summary>
/// The name of the entity.
/// A name matching regex `__.*__` is reserved/read-only.
/// A name must not be more than 1500 bytes when UTF-8 encoded.
/// Cannot be `""`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return idTypeCase_ == IdTypeOneofCase.Name ? (string) idType_ : ""; }
set {
idType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
idTypeCase_ = IdTypeOneofCase.Name;
}
}
private object idType_;
/// <summary>Enum of possible cases for the "id_type" oneof.</summary>
public enum IdTypeOneofCase {
None = 0,
Id = 2,
Name = 3,
}
private IdTypeOneofCase idTypeCase_ = IdTypeOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public IdTypeOneofCase IdTypeCase {
get { return idTypeCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearIdType() {
idTypeCase_ = IdTypeOneofCase.None;
idType_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PathElement);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PathElement other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Kind != other.Kind) return false;
if (Id != other.Id) return false;
if (Name != other.Name) return false;
if (IdTypeCase != other.IdTypeCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Kind.Length != 0) hash ^= Kind.GetHashCode();
if (idTypeCase_ == IdTypeOneofCase.Id) hash ^= Id.GetHashCode();
if (idTypeCase_ == IdTypeOneofCase.Name) hash ^= Name.GetHashCode();
hash ^= (int) idTypeCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Kind.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Kind);
}
if (idTypeCase_ == IdTypeOneofCase.Id) {
output.WriteRawTag(16);
output.WriteInt64(Id);
}
if (idTypeCase_ == IdTypeOneofCase.Name) {
output.WriteRawTag(26);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Kind.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Kind);
}
if (idTypeCase_ == IdTypeOneofCase.Id) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Id);
}
if (idTypeCase_ == IdTypeOneofCase.Name) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PathElement other) {
if (other == null) {
return;
}
if (other.Kind.Length != 0) {
Kind = other.Kind;
}
switch (other.IdTypeCase) {
case IdTypeOneofCase.Id:
Id = other.Id;
break;
case IdTypeOneofCase.Name:
Name = other.Name;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Kind = input.ReadString();
break;
}
case 16: {
Id = input.ReadInt64();
break;
}
case 26: {
Name = input.ReadString();
break;
}
}
}
}
}
}
#endregion
}
/// <summary>
/// An array value.
/// </summary>
public sealed partial class ArrayValue : pb::IMessage<ArrayValue> {
private static readonly pb::MessageParser<ArrayValue> _parser = new pb::MessageParser<ArrayValue>(() => new ArrayValue());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ArrayValue> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Datastore.V1.EntityReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrayValue() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrayValue(ArrayValue other) : this() {
values_ = other.values_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrayValue Clone() {
return new ArrayValue(this);
}
/// <summary>Field number for the "values" field.</summary>
public const int ValuesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Datastore.V1.Value> _repeated_values_codec
= pb::FieldCodec.ForMessage(10, global::Google.Datastore.V1.Value.Parser);
private readonly pbc::RepeatedField<global::Google.Datastore.V1.Value> values_ = new pbc::RepeatedField<global::Google.Datastore.V1.Value>();
/// <summary>
/// Values in the array.
/// The order of this array may not be preserved if it contains a mix of
/// indexed and unindexed values.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Datastore.V1.Value> Values {
get { return values_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ArrayValue);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ArrayValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!values_.Equals(other.values_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= values_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
values_.WriteTo(output, _repeated_values_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += values_.CalculateSize(_repeated_values_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ArrayValue other) {
if (other == null) {
return;
}
values_.Add(other.values_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
values_.AddEntriesFrom(input, _repeated_values_codec);
break;
}
}
}
}
}
/// <summary>
/// A message that can hold any of the supported value types and associated
/// metadata.
/// </summary>
public sealed partial class Value : pb::IMessage<Value> {
private static readonly pb::MessageParser<Value> _parser = new pb::MessageParser<Value>(() => new Value());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Value> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Datastore.V1.EntityReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value(Value other) : this() {
meaning_ = other.meaning_;
excludeFromIndexes_ = other.excludeFromIndexes_;
switch (other.ValueTypeCase) {
case ValueTypeOneofCase.NullValue:
NullValue = other.NullValue;
break;
case ValueTypeOneofCase.BooleanValue:
BooleanValue = other.BooleanValue;
break;
case ValueTypeOneofCase.IntegerValue:
IntegerValue = other.IntegerValue;
break;
case ValueTypeOneofCase.DoubleValue:
DoubleValue = other.DoubleValue;
break;
case ValueTypeOneofCase.TimestampValue:
TimestampValue = other.TimestampValue.Clone();
break;
case ValueTypeOneofCase.KeyValue:
KeyValue = other.KeyValue.Clone();
break;
case ValueTypeOneofCase.StringValue:
StringValue = other.StringValue;
break;
case ValueTypeOneofCase.BlobValue:
BlobValue = other.BlobValue;
break;
case ValueTypeOneofCase.GeoPointValue:
GeoPointValue = other.GeoPointValue.Clone();
break;
case ValueTypeOneofCase.EntityValue:
EntityValue = other.EntityValue.Clone();
break;
case ValueTypeOneofCase.ArrayValue:
ArrayValue = other.ArrayValue.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value Clone() {
return new Value(this);
}
/// <summary>Field number for the "null_value" field.</summary>
public const int NullValueFieldNumber = 11;
/// <summary>
/// A null value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.NullValue NullValue {
get { return valueTypeCase_ == ValueTypeOneofCase.NullValue ? (global::Google.Protobuf.WellKnownTypes.NullValue) valueType_ : 0; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.NullValue;
}
}
/// <summary>Field number for the "boolean_value" field.</summary>
public const int BooleanValueFieldNumber = 1;
/// <summary>
/// A boolean value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool BooleanValue {
get { return valueTypeCase_ == ValueTypeOneofCase.BooleanValue ? (bool) valueType_ : false; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.BooleanValue;
}
}
/// <summary>Field number for the "integer_value" field.</summary>
public const int IntegerValueFieldNumber = 2;
/// <summary>
/// An integer value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long IntegerValue {
get { return valueTypeCase_ == ValueTypeOneofCase.IntegerValue ? (long) valueType_ : 0L; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.IntegerValue;
}
}
/// <summary>Field number for the "double_value" field.</summary>
public const int DoubleValueFieldNumber = 3;
/// <summary>
/// A double value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double DoubleValue {
get { return valueTypeCase_ == ValueTypeOneofCase.DoubleValue ? (double) valueType_ : 0D; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.DoubleValue;
}
}
/// <summary>Field number for the "timestamp_value" field.</summary>
public const int TimestampValueFieldNumber = 10;
/// <summary>
/// A timestamp value.
/// When stored in the Datastore, precise only to microseconds;
/// any additional precision is rounded down.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp TimestampValue {
get { return valueTypeCase_ == ValueTypeOneofCase.TimestampValue ? (global::Google.Protobuf.WellKnownTypes.Timestamp) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.TimestampValue;
}
}
/// <summary>Field number for the "key_value" field.</summary>
public const int KeyValueFieldNumber = 5;
/// <summary>
/// A key value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Datastore.V1.Key KeyValue {
get { return valueTypeCase_ == ValueTypeOneofCase.KeyValue ? (global::Google.Datastore.V1.Key) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.KeyValue;
}
}
/// <summary>Field number for the "string_value" field.</summary>
public const int StringValueFieldNumber = 17;
/// <summary>
/// A UTF-8 encoded string value.
/// When `exclude_from_indexes` is false (it is indexed) , may have at most 1500 bytes.
/// Otherwise, may be set to at least 1,000,000 bytes.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string StringValue {
get { return valueTypeCase_ == ValueTypeOneofCase.StringValue ? (string) valueType_ : ""; }
set {
valueType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
valueTypeCase_ = ValueTypeOneofCase.StringValue;
}
}
/// <summary>Field number for the "blob_value" field.</summary>
public const int BlobValueFieldNumber = 18;
/// <summary>
/// A blob value.
/// May have at most 1,000,000 bytes.
/// When `exclude_from_indexes` is false, may have at most 1500 bytes.
/// In JSON requests, must be base64-encoded.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString BlobValue {
get { return valueTypeCase_ == ValueTypeOneofCase.BlobValue ? (pb::ByteString) valueType_ : pb::ByteString.Empty; }
set {
valueType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
valueTypeCase_ = ValueTypeOneofCase.BlobValue;
}
}
/// <summary>Field number for the "geo_point_value" field.</summary>
public const int GeoPointValueFieldNumber = 8;
/// <summary>
/// A geo point value representing a point on the surface of Earth.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Type.LatLng GeoPointValue {
get { return valueTypeCase_ == ValueTypeOneofCase.GeoPointValue ? (global::Google.Type.LatLng) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.GeoPointValue;
}
}
/// <summary>Field number for the "entity_value" field.</summary>
public const int EntityValueFieldNumber = 6;
/// <summary>
/// An entity value.
///
/// - May have no key.
/// - May have a key with an incomplete key path.
/// - May have a reserved/read-only key.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Datastore.V1.Entity EntityValue {
get { return valueTypeCase_ == ValueTypeOneofCase.EntityValue ? (global::Google.Datastore.V1.Entity) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.EntityValue;
}
}
/// <summary>Field number for the "array_value" field.</summary>
public const int ArrayValueFieldNumber = 9;
/// <summary>
/// An array value.
/// Cannot contain another array value.
/// A `Value` instance that sets field `array_value` must not set fields
/// `meaning` or `exclude_from_indexes`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Datastore.V1.ArrayValue ArrayValue {
get { return valueTypeCase_ == ValueTypeOneofCase.ArrayValue ? (global::Google.Datastore.V1.ArrayValue) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.ArrayValue;
}
}
/// <summary>Field number for the "meaning" field.</summary>
public const int MeaningFieldNumber = 14;
private int meaning_;
/// <summary>
/// The `meaning` field should only be populated for backwards compatibility.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Meaning {
get { return meaning_; }
set {
meaning_ = value;
}
}
/// <summary>Field number for the "exclude_from_indexes" field.</summary>
public const int ExcludeFromIndexesFieldNumber = 19;
private bool excludeFromIndexes_;
/// <summary>
/// If the value should be excluded from all indexes including those defined
/// explicitly.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ExcludeFromIndexes {
get { return excludeFromIndexes_; }
set {
excludeFromIndexes_ = value;
}
}
private object valueType_;
/// <summary>Enum of possible cases for the "value_type" oneof.</summary>
public enum ValueTypeOneofCase {
None = 0,
NullValue = 11,
BooleanValue = 1,
IntegerValue = 2,
DoubleValue = 3,
TimestampValue = 10,
KeyValue = 5,
StringValue = 17,
BlobValue = 18,
GeoPointValue = 8,
EntityValue = 6,
ArrayValue = 9,
}
private ValueTypeOneofCase valueTypeCase_ = ValueTypeOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ValueTypeOneofCase ValueTypeCase {
get { return valueTypeCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearValueType() {
valueTypeCase_ = ValueTypeOneofCase.None;
valueType_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Value);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Value other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (NullValue != other.NullValue) return false;
if (BooleanValue != other.BooleanValue) return false;
if (IntegerValue != other.IntegerValue) return false;
if (DoubleValue != other.DoubleValue) return false;
if (!object.Equals(TimestampValue, other.TimestampValue)) return false;
if (!object.Equals(KeyValue, other.KeyValue)) return false;
if (StringValue != other.StringValue) return false;
if (BlobValue != other.BlobValue) return false;
if (!object.Equals(GeoPointValue, other.GeoPointValue)) return false;
if (!object.Equals(EntityValue, other.EntityValue)) return false;
if (!object.Equals(ArrayValue, other.ArrayValue)) return false;
if (Meaning != other.Meaning) return false;
if (ExcludeFromIndexes != other.ExcludeFromIndexes) return false;
if (ValueTypeCase != other.ValueTypeCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (valueTypeCase_ == ValueTypeOneofCase.NullValue) hash ^= NullValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.BooleanValue) hash ^= BooleanValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.IntegerValue) hash ^= IntegerValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.DoubleValue) hash ^= DoubleValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) hash ^= TimestampValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.KeyValue) hash ^= KeyValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.StringValue) hash ^= StringValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.BlobValue) hash ^= BlobValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) hash ^= GeoPointValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.EntityValue) hash ^= EntityValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) hash ^= ArrayValue.GetHashCode();
if (Meaning != 0) hash ^= Meaning.GetHashCode();
if (ExcludeFromIndexes != false) hash ^= ExcludeFromIndexes.GetHashCode();
hash ^= (int) valueTypeCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (valueTypeCase_ == ValueTypeOneofCase.BooleanValue) {
output.WriteRawTag(8);
output.WriteBool(BooleanValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.IntegerValue) {
output.WriteRawTag(16);
output.WriteInt64(IntegerValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.DoubleValue) {
output.WriteRawTag(25);
output.WriteDouble(DoubleValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.KeyValue) {
output.WriteRawTag(42);
output.WriteMessage(KeyValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.EntityValue) {
output.WriteRawTag(50);
output.WriteMessage(EntityValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) {
output.WriteRawTag(66);
output.WriteMessage(GeoPointValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) {
output.WriteRawTag(74);
output.WriteMessage(ArrayValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) {
output.WriteRawTag(82);
output.WriteMessage(TimestampValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.NullValue) {
output.WriteRawTag(88);
output.WriteEnum((int) NullValue);
}
if (Meaning != 0) {
output.WriteRawTag(112);
output.WriteInt32(Meaning);
}
if (valueTypeCase_ == ValueTypeOneofCase.StringValue) {
output.WriteRawTag(138, 1);
output.WriteString(StringValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.BlobValue) {
output.WriteRawTag(146, 1);
output.WriteBytes(BlobValue);
}
if (ExcludeFromIndexes != false) {
output.WriteRawTag(152, 1);
output.WriteBool(ExcludeFromIndexes);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (valueTypeCase_ == ValueTypeOneofCase.NullValue) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) NullValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.BooleanValue) {
size += 1 + 1;
}
if (valueTypeCase_ == ValueTypeOneofCase.IntegerValue) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(IntegerValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.DoubleValue) {
size += 1 + 8;
}
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TimestampValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.KeyValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(KeyValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.StringValue) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(StringValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.BlobValue) {
size += 2 + pb::CodedOutputStream.ComputeBytesSize(BlobValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(GeoPointValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.EntityValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ArrayValue);
}
if (Meaning != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Meaning);
}
if (ExcludeFromIndexes != false) {
size += 2 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Value other) {
if (other == null) {
return;
}
if (other.Meaning != 0) {
Meaning = other.Meaning;
}
if (other.ExcludeFromIndexes != false) {
ExcludeFromIndexes = other.ExcludeFromIndexes;
}
switch (other.ValueTypeCase) {
case ValueTypeOneofCase.NullValue:
NullValue = other.NullValue;
break;
case ValueTypeOneofCase.BooleanValue:
BooleanValue = other.BooleanValue;
break;
case ValueTypeOneofCase.IntegerValue:
IntegerValue = other.IntegerValue;
break;
case ValueTypeOneofCase.DoubleValue:
DoubleValue = other.DoubleValue;
break;
case ValueTypeOneofCase.TimestampValue:
TimestampValue = other.TimestampValue;
break;
case ValueTypeOneofCase.KeyValue:
KeyValue = other.KeyValue;
break;
case ValueTypeOneofCase.StringValue:
StringValue = other.StringValue;
break;
case ValueTypeOneofCase.BlobValue:
BlobValue = other.BlobValue;
break;
case ValueTypeOneofCase.GeoPointValue:
GeoPointValue = other.GeoPointValue;
break;
case ValueTypeOneofCase.EntityValue:
EntityValue = other.EntityValue;
break;
case ValueTypeOneofCase.ArrayValue:
ArrayValue = other.ArrayValue;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
BooleanValue = input.ReadBool();
break;
}
case 16: {
IntegerValue = input.ReadInt64();
break;
}
case 25: {
DoubleValue = input.ReadDouble();
break;
}
case 42: {
global::Google.Datastore.V1.Key subBuilder = new global::Google.Datastore.V1.Key();
if (valueTypeCase_ == ValueTypeOneofCase.KeyValue) {
subBuilder.MergeFrom(KeyValue);
}
input.ReadMessage(subBuilder);
KeyValue = subBuilder;
break;
}
case 50: {
global::Google.Datastore.V1.Entity subBuilder = new global::Google.Datastore.V1.Entity();
if (valueTypeCase_ == ValueTypeOneofCase.EntityValue) {
subBuilder.MergeFrom(EntityValue);
}
input.ReadMessage(subBuilder);
EntityValue = subBuilder;
break;
}
case 66: {
global::Google.Type.LatLng subBuilder = new global::Google.Type.LatLng();
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) {
subBuilder.MergeFrom(GeoPointValue);
}
input.ReadMessage(subBuilder);
GeoPointValue = subBuilder;
break;
}
case 74: {
global::Google.Datastore.V1.ArrayValue subBuilder = new global::Google.Datastore.V1.ArrayValue();
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) {
subBuilder.MergeFrom(ArrayValue);
}
input.ReadMessage(subBuilder);
ArrayValue = subBuilder;
break;
}
case 82: {
global::Google.Protobuf.WellKnownTypes.Timestamp subBuilder = new global::Google.Protobuf.WellKnownTypes.Timestamp();
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) {
subBuilder.MergeFrom(TimestampValue);
}
input.ReadMessage(subBuilder);
TimestampValue = subBuilder;
break;
}
case 88: {
valueType_ = input.ReadEnum();
valueTypeCase_ = ValueTypeOneofCase.NullValue;
break;
}
case 112: {
Meaning = input.ReadInt32();
break;
}
case 138: {
StringValue = input.ReadString();
break;
}
case 146: {
BlobValue = input.ReadBytes();
break;
}
case 152: {
ExcludeFromIndexes = input.ReadBool();
break;
}
}
}
}
}
/// <summary>
/// A Datastore data object.
///
/// An entity is limited to 1 megabyte when stored. That _roughly_
/// corresponds to a limit of 1 megabyte for the serialized form of this
/// message.
/// </summary>
public sealed partial class Entity : pb::IMessage<Entity> {
private static readonly pb::MessageParser<Entity> _parser = new pb::MessageParser<Entity>(() => new Entity());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Entity> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Datastore.V1.EntityReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Entity() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Entity(Entity other) : this() {
Key = other.key_ != null ? other.Key.Clone() : null;
properties_ = other.properties_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Entity Clone() {
return new Entity(this);
}
/// <summary>Field number for the "key" field.</summary>
public const int KeyFieldNumber = 1;
private global::Google.Datastore.V1.Key key_;
/// <summary>
/// The entity's key.
///
/// An entity must have a key, unless otherwise documented (for example,
/// an entity in `Value.entity_value` may have no key).
/// An entity's kind is its key path's last element's kind,
/// or null if it has no key.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Datastore.V1.Key Key {
get { return key_; }
set {
key_ = value;
}
}
/// <summary>Field number for the "properties" field.</summary>
public const int PropertiesFieldNumber = 3;
private static readonly pbc::MapField<string, global::Google.Datastore.V1.Value>.Codec _map_properties_codec
= new pbc::MapField<string, global::Google.Datastore.V1.Value>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Datastore.V1.Value.Parser), 26);
private readonly pbc::MapField<string, global::Google.Datastore.V1.Value> properties_ = new pbc::MapField<string, global::Google.Datastore.V1.Value>();
/// <summary>
/// The entity's properties.
/// The map's keys are property names.
/// A property name matching regex `__.*__` is reserved.
/// A reserved property name is forbidden in certain documented contexts.
/// The name must not contain more than 500 characters.
/// The name cannot be `""`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, global::Google.Datastore.V1.Value> Properties {
get { return properties_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Entity);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Entity other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Key, other.Key)) return false;
if (!Properties.Equals(other.Properties)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (key_ != null) hash ^= Key.GetHashCode();
hash ^= Properties.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (key_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Key);
}
properties_.WriteTo(output, _map_properties_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (key_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Key);
}
size += properties_.CalculateSize(_map_properties_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Entity other) {
if (other == null) {
return;
}
if (other.key_ != null) {
if (key_ == null) {
key_ = new global::Google.Datastore.V1.Key();
}
Key.MergeFrom(other.Key);
}
properties_.Add(other.properties_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (key_ == null) {
key_ = new global::Google.Datastore.V1.Key();
}
input.ReadMessage(key_);
break;
}
case 26: {
properties_.AddEntriesFrom(input, _map_properties_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
namespace Revit.SDK.Samples.LevelsProperty.CS
{
/// <summary>
/// Provides static functions to convert unit
/// </summary>
static class Unit
{
#region Methods
/// <summary>
/// Convert the value get from RevitAPI to the value indicated by DisplayUnitType
/// </summary>
/// <param name="to">DisplayUnitType indicates unit of target value</param>
/// <param name="value">value get from RevitAPI</param>
/// <returns>Target value</returns>
public static double CovertFromAPI(DisplayUnitType to, double value)
{
switch (to)
{
case DisplayUnitType.DUT_FAHRENHEIT:
return value * ImperialDutRatio(to) - 459.67;
case DisplayUnitType.DUT_CELSIUS:
return value - 273.15;
default:
return value *= ImperialDutRatio(to);
}
}
/// <summary>
/// Convert a value indicated by DisplayUnitType to the value used by RevitAPI
/// </summary>
/// <param name="value">Value to be converted</param>
/// <param name="from">DisplayUnitType indicates the unit of the value to be converted</param>
/// <returns>Target value</returns>
public static double CovertToAPI(double value, DisplayUnitType from)
{
switch (from)
{
case DisplayUnitType.DUT_FAHRENHEIT:
return (value + 459.67) / ImperialDutRatio(from);
case DisplayUnitType.DUT_CELSIUS:
return value + 273.15;
default:
return value /= ImperialDutRatio(from);
}
}
/// <summary>
/// Get ratio between value in RevitAPI and value to display indicated by DisplayUnitType
/// </summary>
/// <param name="dut">DisplayUnitType indicates display unit type</param>
/// <returns>Ratio </returns>
private static double ImperialDutRatio(DisplayUnitType dut)
{
switch (dut)
{
case DisplayUnitType.DUT_ACRES: return 2.29568411386593E-05;
case DisplayUnitType.DUT_AMPERES: return 1;
case DisplayUnitType.DUT_ATMOSPHERES: return 3.23793722675857E-05;
case DisplayUnitType.DUT_BARS: return 3.28083989501312E-05;
case DisplayUnitType.DUT_BRITISH_THERMAL_UNITS: return 8.80550918411529E-05;
case DisplayUnitType.DUT_BRITISH_THERMAL_UNITS_PER_HOUR: return 0.316998330628151;
case DisplayUnitType.DUT_BRITISH_THERMAL_UNITS_PER_SECOND: return 8.80550918411529E-05;
case DisplayUnitType.DUT_CALORIES: return 0.0221895098882201;
case DisplayUnitType.DUT_CALORIES_PER_SECOND: return 0.0221895098882201;
case DisplayUnitType.DUT_CANDELAS: return 1;
case DisplayUnitType.DUT_CANDELAS_PER_SQUARE_METER: return 10.7639104167097;
case DisplayUnitType.DUT_CANDLEPOWER: return 1;
case DisplayUnitType.DUT_CELSIUS: return 1;
case DisplayUnitType.DUT_CENTIMETERS: return 30.48;
case DisplayUnitType.DUT_CENTIMETERS_PER_MINUTE: return 1828.8;
case DisplayUnitType.DUT_CENTIPOISES: return 3280.83989501312;
case DisplayUnitType.DUT_CUBIC_CENTIMETERS: return 28316.846592;
case DisplayUnitType.DUT_CUBIC_FEET: return 1;
case DisplayUnitType.DUT_CUBIC_FEET_PER_KIP: return 14593.9029372064;
case DisplayUnitType.DUT_CUBIC_FEET_PER_MINUTE: return 60;
case DisplayUnitType.DUT_CUBIC_INCHES: return 1728;
case DisplayUnitType.DUT_CUBIC_METERS: return 0.028316846592;
case DisplayUnitType.DUT_CUBIC_METERS_PER_HOUR: return 101.9406477312;
case DisplayUnitType.DUT_CUBIC_METERS_PER_KILONEWTON: return 92.90304;
case DisplayUnitType.DUT_CUBIC_METERS_PER_SECOND: return 0.028316846592;
case DisplayUnitType.DUT_CUBIC_MILLIMETERS: return 28316846.592;
case DisplayUnitType.DUT_CUBIC_YARDS: return 0.037037037037037;
case DisplayUnitType.DUT_CYCLES_PER_SECOND: return 1;
case DisplayUnitType.DUT_DECANEWTONS: return 0.03048;
case DisplayUnitType.DUT_DECANEWTONS_PER_METER: return 0.1;
case DisplayUnitType.DUT_DECANEWTONS_PER_SQUARE_METER: return 0.328083989501312;
case DisplayUnitType.DUT_DECANEWTON_METERS: return 0.009290304;
case DisplayUnitType.DUT_DECANEWTON_METERS_PER_METER: return 0.03048;
case DisplayUnitType.DUT_DECIMAL_DEGREES: return 57.2957795130823;
case DisplayUnitType.DUT_DECIMAL_FEET: return 1;
case DisplayUnitType.DUT_DECIMAL_INCHES: return 12;
case DisplayUnitType.DUT_DEGREES_AND_MINUTES: return 57.2957795130823;
case DisplayUnitType.DUT_FAHRENHEIT: return 1.8;
case DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES: return 1;
case DisplayUnitType.DUT_FEET_OF_WATER: return 0.00109764531546318;
case DisplayUnitType.DUT_FEET_OF_WATER_PER_100FT: return 0.109761336731934;
case DisplayUnitType.DUT_FEET_PER_KIP: return 14593.9029372064;
case DisplayUnitType.DUT_FEET_PER_MINUTE: return 60;
case DisplayUnitType.DUT_FEET_PER_SECOND: return 1;
case DisplayUnitType.DUT_FIXED: return 1;
case DisplayUnitType.DUT_FOOTCANDLES: return 1.0000000387136;
case DisplayUnitType.DUT_FOOTLAMBERTS: return 3.1415927449471;
case DisplayUnitType.DUT_FRACTIONAL_INCHES: return 12;
case DisplayUnitType.DUT_GALLONS_US: return 7.48051905367236;
case DisplayUnitType.DUT_GALLONS_US_PER_HOUR: return 26929.8685932205;
case DisplayUnitType.DUT_GALLONS_US_PER_MINUTE: return 448.831143220342;
case DisplayUnitType.DUT_GENERAL: return 1;
case DisplayUnitType.DUT_HECTARES: return 9.290304E-06;
case DisplayUnitType.DUT_HERTZ: return 1;
case DisplayUnitType.DUT_HORSEPOWER: return 0.00012458502883053;
case DisplayUnitType.DUT_INCHES_OF_MERCURY: return 0.000968831370233344;
case DisplayUnitType.DUT_INCHES_OF_WATER: return 0.0131845358262865;
case DisplayUnitType.DUT_INCHES_OF_WATER_PER_100FT: return 1.31845358262865;
case DisplayUnitType.DUT_INV_CELSIUS: return 1;
case DisplayUnitType.DUT_INV_FAHRENHEIT: return 0.555555555555556;
case DisplayUnitType.DUT_INV_KILONEWTONS: return 3280.83989501312;
case DisplayUnitType.DUT_INV_KIPS: return 14593.9029372064;
case DisplayUnitType.DUT_JOULES: return 0.09290304;
case DisplayUnitType.DUT_KELVIN: return 1;
case DisplayUnitType.DUT_KILOAMPERES: return 0.001;
case DisplayUnitType.DUT_KILOCALORIES: return 2.21895098882201E-05;
case DisplayUnitType.DUT_KILOCALORIES_PER_SECOND: return 2.21895098882201E-05;
case DisplayUnitType.DUT_KILOGRAMS_FORCE: return 0.0310810655372411;
case DisplayUnitType.DUT_KILOGRAMS_FORCE_PER_METER: return 0.101971999794098;
case DisplayUnitType.DUT_KILOGRAMS_FORCE_PER_SQUARE_METER: return 0.334553805098747;
case DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER: return 35.3146667214886;
case DisplayUnitType.DUT_KILOGRAM_FORCE_METERS: return 0.00947350877575109;
case DisplayUnitType.DUT_KILOGRAM_FORCE_METERS_PER_METER: return 0.0310810655372411;
case DisplayUnitType.DUT_KILONEWTONS: return 0.0003048;
case DisplayUnitType.DUT_KILONEWTONS_PER_CUBIC_METER: return 0.0107639104167097;
case DisplayUnitType.DUT_KILONEWTONS_PER_METER: return 0.001;
case DisplayUnitType.DUT_KILONEWTONS_PER_SQUARE_METER: return 0.00328083989501312;
case DisplayUnitType.DUT_KILONEWTON_METERS: return 9.290304E-05;
case DisplayUnitType.DUT_KILONEWTON_METERS_PER_DEGREE: return 9.290304E-05;
case DisplayUnitType.DUT_KILONEWTON_METERS_PER_DEGREE_PER_METER: return 0.0003048;
case DisplayUnitType.DUT_KILONEWTON_METERS_PER_METER: return 0.0003048;
case DisplayUnitType.DUT_KILOPASCALS: return 0.00328083989501312;
case DisplayUnitType.DUT_KILOVOLTS: return 9.290304E-05;
case DisplayUnitType.DUT_KILOVOLT_AMPERES: return 9.290304E-05;
case DisplayUnitType.DUT_KILOWATTS: return 9.290304E-05;
case DisplayUnitType.DUT_KILOWATT_HOURS: return 2.58064E-08;
case DisplayUnitType.DUT_KIPS: return 0.224808943099711;
case DisplayUnitType.DUT_KIPS_PER_CUBIC_FOOT: return 6.85217658567918E-05;
case DisplayUnitType.DUT_KIPS_PER_CUBIC_INCH: return 3.96537996856434E-08;
case DisplayUnitType.DUT_KIPS_PER_FOOT: return 6.85217658567918E-05;
case DisplayUnitType.DUT_KIPS_PER_INCH: return 5.71014715473265E-06;
case DisplayUnitType.DUT_KIPS_PER_SQUARE_FOOT: return 6.85217658567918E-05;
case DisplayUnitType.DUT_KIPS_PER_SQUARE_INCH: return 4.75845596227721E-07;
case DisplayUnitType.DUT_KIP_FEET: return 6.85217658567918E-05;
case DisplayUnitType.DUT_KIP_FEET_PER_DEGREE: return 2.08854342331501E-05;
case DisplayUnitType.DUT_KIP_FEET_PER_DEGREE_PER_FOOT: return 2.08854342331501E-05;
case DisplayUnitType.DUT_KIP_FEET_PER_FOOT: return 6.85217658567918E-05;
case DisplayUnitType.DUT_LITERS: return 28.316846592;
case DisplayUnitType.DUT_LITERS_PER_SECOND: return 28.316846592;
case DisplayUnitType.DUT_LUMENS: return 1;
case DisplayUnitType.DUT_LUX: return 10.7639104167097;
case DisplayUnitType.DUT_MEGANEWTONS: return 3.048E-07;
case DisplayUnitType.DUT_MEGANEWTONS_PER_METER: return 1E-06;
case DisplayUnitType.DUT_MEGANEWTONS_PER_SQUARE_METER: return 3.28083989501312E-06;
case DisplayUnitType.DUT_MEGANEWTON_METERS: return 9.290304E-08;
case DisplayUnitType.DUT_MEGANEWTON_METERS_PER_METER: return 3.048E-07;
case DisplayUnitType.DUT_MEGAPASCALS: return 3.28083989501312E-06;
case DisplayUnitType.DUT_METERS: return 0.3048;
case DisplayUnitType.DUT_METERS_CENTIMETERS: return 0.3048;
case DisplayUnitType.DUT_METERS_PER_KILONEWTON: return 1000;
case DisplayUnitType.DUT_METERS_PER_SECOND: return 0.3048;
case DisplayUnitType.DUT_MILLIAMPERES: return 1000;
case DisplayUnitType.DUT_MILLIMETERS: return 304.8;
case DisplayUnitType.DUT_MILLIMETERS_OF_MERCURY: return 0.0246083170946002;
case DisplayUnitType.DUT_MILLIVOLTS: return 92.90304;
case DisplayUnitType.DUT_NEWTONS: return 0.3048;
case DisplayUnitType.DUT_NEWTONS_PER_METER: return 1;
case DisplayUnitType.DUT_NEWTONS_PER_SQUARE_METER: return 3.28083989501312;
case DisplayUnitType.DUT_NEWTON_METERS: return 0.09290304;
case DisplayUnitType.DUT_NEWTON_METERS_PER_METER: return 0.3048;
case DisplayUnitType.DUT_PASCALS: return 3.28083989501312;
case DisplayUnitType.DUT_PASCALS_PER_METER: return 10.7639104167097;
case DisplayUnitType.DUT_PASCAL_SECONDS: return 3.28083989501312;
case DisplayUnitType.DUT_PERCENTAGE: return 100;
case DisplayUnitType.DUT_POUNDS_FORCE: return 224.80894309971;
case DisplayUnitType.DUT_POUNDS_FORCE_PER_CUBIC_FOOT: return 0.0685217658567918;
case DisplayUnitType.DUT_POUNDS_FORCE_PER_FOOT: return 0.0685217658567918;
case DisplayUnitType.DUT_POUNDS_FORCE_PER_SQUARE_FOOT: return 0.0685217658567917;
case DisplayUnitType.DUT_POUNDS_FORCE_PER_SQUARE_INCH: return 0.000475845616460903;
case DisplayUnitType.DUT_POUNDS_MASS_PER_CUBIC_FOOT: return 2.20462262184878;
case DisplayUnitType.DUT_POUNDS_MASS_PER_CUBIC_INCH: return 0.00127582327653286;
case DisplayUnitType.DUT_POUNDS_MASS_PER_FOOT_HOUR: return 7936.64143865559;
case DisplayUnitType.DUT_POUNDS_MASS_PER_FOOT_SECOND: return 2.20462262184878;
case DisplayUnitType.DUT_POUND_FORCE_FEET: return 0.0685217658567918;
case DisplayUnitType.DUT_POUND_FORCE_FEET_PER_FOOT: return 0.0685217658567918;
case DisplayUnitType.DUT_RANKINE: return 1.8;
case DisplayUnitType.DUT_SQUARE_CENTIMETERS: return 929.0304;
case DisplayUnitType.DUT_SQUARE_FEET: return 1;
case DisplayUnitType.DUT_SQUARE_FEET_PER_KIP: return 14593.9029372064;
case DisplayUnitType.DUT_SQUARE_INCHES: return 144;
case DisplayUnitType.DUT_SQUARE_METERS: return 0.09290304;
case DisplayUnitType.DUT_SQUARE_METERS_PER_KILONEWTON: return 304.8;
case DisplayUnitType.DUT_SQUARE_MILLIMETERS: return 92903.04;
case DisplayUnitType.DUT_THERMS: return 8.80547457016663E-10;
case DisplayUnitType.DUT_TONNES_FORCE: return 3.10810655372411E-05;
case DisplayUnitType.DUT_TONNES_FORCE_PER_METER: return 0.000101971999794098;
case DisplayUnitType.DUT_TONNES_FORCE_PER_SQUARE_METER: return 0.000334553805098747;
case DisplayUnitType.DUT_TONNE_FORCE_METERS: return 9.47350877575109E-06;
case DisplayUnitType.DUT_TONNE_FORCE_METERS_PER_METER: return 3.10810655372411E-05;
case DisplayUnitType.DUT_VOLTS: return 0.09290304;
case DisplayUnitType.DUT_VOLT_AMPERES: return 0.09290304;
case DisplayUnitType.DUT_WATTS: return 0.09290304;
case DisplayUnitType.DUT_WATTS_PER_SQUARE_FOOT: return 0.09290304;
case DisplayUnitType.DUT_WATTS_PER_SQUARE_METER: return 1;
default: return 1;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
namespace Microsoft.DotNet.Cli.Build
{
public class AzurePublisher
{
public enum Product
{
SharedFramework,
Host,
HostFxr,
Sdk,
}
private const string s_dotnetBlobContainerName = "dotnet";
private string _connectionString { get; set; }
private string _containerName { get; set; }
private CloudBlobContainer _blobContainer { get; set; }
public AzurePublisher(string containerName = s_dotnetBlobContainerName)
{
_connectionString = EnvVars.EnsureVariable("CONNECTION_STRING").Trim('"');
_containerName = containerName;
_blobContainer = GetDotnetBlobContainer(_connectionString, containerName);
}
public AzurePublisher(string accountName, string accountKey, string containerName = s_dotnetBlobContainerName)
{
_containerName = containerName;
_blobContainer = GetDotnetBlobContainer(accountName, accountKey, containerName);
}
private CloudBlobContainer GetDotnetBlobContainer(string connectionString, string containerName)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
return GetDotnetBlobContainer(storageAccount, containerName);
}
private CloudBlobContainer GetDotnetBlobContainer(string accountName, string accountKey, string containerName)
{
var storageCredentials = new StorageCredentials(accountName, accountKey);
var storageAccount = new CloudStorageAccount(storageCredentials, true);
return GetDotnetBlobContainer(storageAccount, containerName);
}
private CloudBlobContainer GetDotnetBlobContainer(CloudStorageAccount storageAccount, string containerName)
{
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
return blobClient.GetContainerReference(containerName);
}
public string UploadFile(string file, Product product, string version)
{
string url = CalculateRelativePathForFile(file, product, version);
CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(url);
blob.UploadFromFileAsync(file, FileMode.Open).Wait();
SetBlobPropertiesBasedOnFileType(blob);
return url;
}
public void PublishStringToBlob(string blob, string content)
{
CloudBlockBlob blockBlob = _blobContainer.GetBlockBlobReference(blob);
blockBlob.UploadTextAsync(content).Wait();
SetBlobPropertiesBasedOnFileType(blockBlob);
}
public void CopyBlob(string sourceBlob, string targetBlob)
{
CloudBlockBlob source = _blobContainer.GetBlockBlobReference(sourceBlob);
CloudBlockBlob target = _blobContainer.GetBlockBlobReference(targetBlob);
// Create the empty blob
using (MemoryStream ms = new MemoryStream())
{
target.UploadFromStreamAsync(ms).Wait();
}
// Copy actual blob data
target.StartCopyAsync(source).Wait();
}
public void SetBlobPropertiesBasedOnFileType(string path)
{
CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(path);
SetBlobPropertiesBasedOnFileType(blob);
}
private void SetBlobPropertiesBasedOnFileType(CloudBlockBlob blockBlob)
{
if (Path.GetExtension(blockBlob.Uri.AbsolutePath.ToLower()) == ".svg")
{
blockBlob.Properties.ContentType = "image/svg+xml";
blockBlob.Properties.CacheControl = "no-cache";
blockBlob.SetPropertiesAsync().Wait();
}
else if (Path.GetExtension(blockBlob.Uri.AbsolutePath.ToLower()) == ".version")
{
blockBlob.Properties.ContentType = "text/plain";
blockBlob.Properties.CacheControl = "no-cache";
blockBlob.SetPropertiesAsync().Wait();
}
}
public IEnumerable<string> ListBlobs(Product product, string version)
{
string virtualDirectory = $"{product}/{version}";
return ListBlobs(virtualDirectory);
}
public IEnumerable<string> ListBlobs(string virtualDirectory)
{
CloudBlobDirectory blobDir = _blobContainer.GetDirectoryReference(virtualDirectory);
BlobContinuationToken continuationToken = new BlobContinuationToken();
var blobFiles = blobDir.ListBlobsSegmentedAsync(continuationToken).Result;
return blobFiles.Results.Select(bf => bf.Uri.PathAndQuery.Replace($"/{_containerName}/", string.Empty));
}
public string AcquireLeaseOnBlob(
string blob,
TimeSpan? maxWaitDefault = null,
TimeSpan? delayDefault = null)
{
TimeSpan maxWait = maxWaitDefault ?? TimeSpan.FromSeconds(120);
TimeSpan delay = delayDefault ?? TimeSpan.FromMilliseconds(500);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// This will throw an exception with HTTP code 409 when we cannot acquire the lease
// But we should block until we can get this lease, with a timeout (maxWaitSeconds)
while (stopWatch.ElapsedMilliseconds < maxWait.TotalMilliseconds)
{
try
{
CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob);
Task<string> task = cloudBlob.AcquireLeaseAsync(TimeSpan.FromMinutes(1), null);
task.Wait();
return task.Result;
}
catch (Exception e)
{
Console.WriteLine($"Retrying lease acquisition on {blob}, {e.Message}");
Thread.Sleep(delay);
}
}
throw new Exception($"Unable to acquire lease on {blob}");
}
public void ReleaseLeaseOnBlob(string blob, string leaseId)
{
CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob);
AccessCondition ac = new AccessCondition() { LeaseId = leaseId };
cloudBlob.ReleaseLeaseAsync(ac).Wait();
}
public bool IsLatestSpecifiedVersion(string version)
{
Task<bool> task = _blobContainer.GetBlockBlobReference(version).ExistsAsync();
task.Wait();
return task.Result;
}
public void DropLatestSpecifiedVersion(string version)
{
CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(version);
using (MemoryStream ms = new MemoryStream())
{
blob.UploadFromStreamAsync(ms).Wait();
}
}
public void CreateBlobIfNotExists(string path)
{
Task<bool> task = _blobContainer.GetBlockBlobReference(path).ExistsAsync();
task.Wait();
if (!task.Result)
{
CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(path);
using (MemoryStream ms = new MemoryStream())
{
blob.UploadFromStreamAsync(ms).Wait();
}
}
}
public bool TryDeleteBlob(string path)
{
try
{
DeleteBlob(path);
return true;
}
catch (Exception e)
{
Console.WriteLine($"Deleting blob {path} failed with \r\n{e.Message}");
return false;
}
}
private void DeleteBlob(string path)
{
_blobContainer.GetBlockBlobReference(path).DeleteAsync().Wait();
}
private static string CalculateRelativePathForFile(string file, Product product, string version)
{
return $"{product}/{version}/{Path.GetFileName(file)}";
}
}
}
| |
//
// DNN Corp - http://www.dnnsoftware.com
// Copyright (c) 2002-2014
// by DNN Corp
//
// 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.
//
//ORIGINAL LINE: Imports DotNetNuke.Modules.Media.MediaInfoMembers
//INSTANT C# NOTE: The following line has been modified since C# non-aliased 'using' statements only operate on namespaces:
//INSTANT C# NOTE: Formerly VB project-level imports:
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Exceptions;
using System;
using System.Text.RegularExpressions;
using DotNetNuke.Services.FileSystem;
namespace DotNetNuke.Modules.Media
{
/// <summary>
/// Represents a piece of Media.
/// </summary>
[Serializable()]
public class MediaInfo : Entities.Modules.IHydratable, IMediaInfo
{
#region Constants
private const string FILE_PATH_PATTERN = @"^([\w-\s]+/)*([\w-\s]+\.\w{2,})$";
#endregion
#region Fields
private int p_ModuleID = Null.NullInteger;
private string p_Src = Null.NullString;
private string p_Alt = Null.NullString;
private int p_Width = Null.NullInteger;
private int p_Height = Null.NullInteger;
private string p_NavigateUrl = Null.NullString;
private bool p_NewWindow = Null.NullBoolean;
private bool p_TrackClicks = Null.NullBoolean;
// 03.02.03
private int p_MediaAlignment = Null.NullInteger;
// 03.03.00
private bool p_MediaLoop = Null.NullBoolean;
private bool p_AutoStart = Null.NullBoolean;
// 04.00.00
private int p_MediaType = Null.NullInteger;
// 04.01.00
private string p_MediaMessage = Null.NullString;
private int p_LastUpdatedBy = Null.NullInteger;
private DateTime p_LastUpdatedDate = Null.NullDate;
#endregion
#region Initialization
/// <summary>
/// Instantiates a new instance of the <c>ImageInfo</c> class.
/// </summary>
public MediaInfo()
{
this.p_ModuleID = -1;
this.p_Src = string.Empty;
this.p_Alt = string.Empty;
this.p_Width = -1;
this.p_Height = -1;
this.p_NavigateUrl = string.Empty;
this.p_NewWindow = false;
this.p_TrackClicks = false;
this.p_MediaAlignment = 0;
this.p_MediaLoop = false;
this.p_AutoStart = false;
this.p_MediaType = 0;
this.p_MediaMessage = string.Empty;
this.p_LastUpdatedBy = -1;
this.p_LastUpdatedDate = DateTime.MinValue;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the unique module identifier.
/// </summary>
public int ModuleId
{
get
{
return this.ModuleID;
}
set
{
this.ModuleID = value;
}
}
/// <summary>
/// ModuleId - backwards compatibility following the VB to C# conversion
/// </summary>
public int ModuleID
{
get
{
return this.p_ModuleID;
}
set
{
this.p_ModuleID = value;
}
}
/// <summary>
/// Gets or sets the URL of the Media to display.
/// </summary>
public string Src
{
get
{
return this.p_Src;
}
set
{
this.p_Src = value;
}
}
/// <summary>
/// Gets or sets the text to display if the Media cannot be displayed.
/// </summary>
public string Alt
{
get
{
return this.p_Alt;
}
set
{
this.p_Alt = value;
}
}
/// <summary>
/// Gets or sets the display width of the Media.
/// </summary>
public int Width
{
get
{
return this.p_Width;
}
set
{
this.p_Width = value;
}
}
/// <summary>
/// Gets or sets the display height of the Media.
/// </summary>
public int Height
{
get
{
return this.p_Height;
}
set
{
this.p_Height = value;
}
}
/// <summary>
/// Gets or sets the URL to navigate to when the Media is clicked.
/// </summary>
public string NavigateUrl
{
get
{
return this.p_NavigateUrl;
}
set
{
this.p_NavigateUrl = value;
}
}
/// <summary>
/// Gets or sets the target in which the <see cref="NavigateUrl"/> will be opened in.
/// </summary>
/// <value></value>
/// <remarks></remarks>
/// <history>
/// [Leigh] 26/02/2006 Created
/// </history>
public bool NewWindow
{
get
{
return this.p_NewWindow;
}
set
{
this.p_NewWindow = value;
}
}
/// <summary>
/// Gets or sets the TrackClicks in which the <see cref="NavigateUrl"/> will be opened in.
/// </summary>
/// <value></value>
/// <remarks></remarks>
/// <history>
/// [Leigh] 26/02/2006 Created
/// </history>
public bool TrackClicks
{
get
{
return this.p_TrackClicks;
}
set
{
this.p_TrackClicks = value;
}
}
/// <summary>
/// Gets or sets the MediaAlignment in which the media will use.
/// </summary>
/// <value></value>
/// <remarks></remarks>
/// <history>
/// [Leigh] 25/10/2006 Created
/// </history>
public int MediaAlignment
{
get
{
return this.p_MediaAlignment;
}
set
{
this.p_MediaAlignment = value;
}
}
/// <summary>
/// Gets or sets the MediaLoop in which the media will use.
/// </summary>
/// <value></value>
/// <remarks></remarks>
/// <history>
/// [wstrohl] - 01/31/2010 - Created
/// </history>
public bool MediaLoop
{
get
{
return this.p_MediaLoop;
}
set
{
this.p_MediaLoop = value;
}
}
/// <summary>
/// Gets or sets the AutoStart in which the media will use.
/// </summary>
/// <value></value>
/// <remarks></remarks>
/// <history>
/// [wstrohl] - 01/31/2010 - Created
/// </history>
public bool AutoStart
{
get
{
return this.p_AutoStart;
}
set
{
this.p_AutoStart = value;
}
}
/// <summary>
/// Gets or sets the MediaType in which the media will use.
/// </summary>
/// <value></value>
/// <remarks></remarks>
/// <history>
/// [wstrohl] - 20110319 - Created
/// </history>
public int MediaType
{
get
{
return this.p_MediaType;
}
set
{
this.p_MediaType = value;
}
}
/// <summary>
/// Gets or sets the MediaMessage in which will be displayed with the media.
/// </summary>
/// <value></value>
/// <remarks></remarks>
/// <history>
/// [wstrohl] - 20110708 - Created
/// </history>
public string MediaMessage
{
get
{
return this.p_MediaMessage;
}
set
{
this.p_MediaMessage = value;
}
}
/// <summary>
/// Gets or sets the LastUpdatedBy to keep track of who updates the content.
/// </summary>
/// <value></value>
/// <remarks></remarks>
/// <history>
/// [wstrohl] - 20110708 - Created
/// </history>
public int LastUpdatedBy
{
get
{
return this.p_LastUpdatedBy;
}
set
{
this.p_LastUpdatedBy = value;
}
}
/// <summary>
/// Gets or sets the LastUpdatedDate to keep track of when the content was last updated.
/// </summary>
/// <value></value>
/// <remarks></remarks>
/// <history>
/// [wstrohl] - 20110708 - Created
/// </history>
public DateTime LastUpdatedDate
{
get
{
return this.p_LastUpdatedDate;
}
set
{
this.p_LastUpdatedDate = value;
}
}
/// <summary>
/// WebFriendlyUrl - returns a URL that can immediately be used to display the media source path, regardless of folder provider
/// </summary>
public string WebFriendlyUrl
{
get
{
if (Regex.IsMatch(Src, @"^FileID=\d+$"))
{
int fileId = int.Parse(Regex.Replace(Src, @"FileID=", string.Empty));
IFileInfo oFile = FileManager.Instance.GetFile(fileId);
MediaController ctlMedia = new MediaController();
return ctlMedia.GetFileUrl(oFile);
}
else if (Regex.IsMatch(Src, FILE_PATH_PATTERN))
{
// IMPORTANT NOTE!!
// This code is not thread safe... The portal settings require an active web session
Entities.Portals.PortalSettings settings = Entities.Portals.PortalController.GetCurrentPortalSettings();
//string folderPath = Regex.Match(Src, FILE_PATH_PATTERN).Groups[1].Value;
//string fileName = Regex.Match(Src, FILE_PATH_PATTERN).Groups[2].Value;
// Fix suggested from Issue 23595
string fileName = Regex.Match(Src, FILE_PATH_PATTERN).Groups[2].Value;
string folderPath = Src.Substring(0, Src.Length - fileName.Length);
IFolderInfo oFolder = FolderManager.Instance.GetFolder(settings.PortalId, folderPath);
MediaController ctlMedia = new MediaController();
IFileInfo oFile = ctlMedia.GetFileFromProvider(settings.PortalId, oFolder, fileName);
return ctlMedia.GetFileUrl(oFile);
}
else
{
return Src;
}
}
set { }
}
/// <summary>
/// FileExtension - returns the extension for the file
/// </summary>
public string FileExtension
{
get
{
if (Regex.IsMatch(Src, @"^FileID=\d+$"))
{
int fileId = int.Parse(Regex.Replace(Src, @"FileID=", string.Empty));
IFileInfo oFile = FileManager.Instance.GetFile(fileId);
return oFile.Extension;
}
else if (Regex.IsMatch(Src, FILE_PATH_PATTERN))
{
return Regex.Match(Src, @"\.(\w{2,})$").Groups[1].Value;
}
else
{
return string.Empty;
}
}
set { }
}
/// <summary>
/// ContentType - returns the content type of the file
/// </summary>
public string ContentType
{
get
{
if (Regex.IsMatch(Src, @"^FileID=\d+$"))
{
int fileId = int.Parse(Regex.Replace(Src, @"FileID=", string.Empty));
IFileInfo oFile = FileManager.Instance.GetFile(fileId);
return oFile.ContentType;
}
else if (Regex.IsMatch(Src, FILE_PATH_PATTERN))
{
// IMPORTANT NOTE!!
// This code is not thread safe... The portal settings require an active web session
Entities.Portals.PortalSettings settings = Entities.Portals.PortalController.GetCurrentPortalSettings();
string folderPath = Regex.Match(Src, FILE_PATH_PATTERN).Groups[1].Value;
string fileName = Regex.Match(Src, FILE_PATH_PATTERN).Groups[2].Value;
IFolderInfo oFolder = FolderManager.Instance.GetFolder(settings.PortalId, folderPath);
MediaController ctlMedia = new MediaController();
IFileInfo oFile = ctlMedia.GetFileFromProvider(settings.PortalId, oFolder, fileName);
return oFile.ContentType;
}
else
{
return string.Empty;
}
}
set { }
}
#endregion
#region IHydratable Implementation
public void Fill(System.Data.IDataReader dr)
{
try
{
while (dr.Read())
{
if (dr[MediaInfoMembers.AltField] != null)
{
this.p_Alt = dr[MediaInfoMembers.AltField].ToString();
}
if (dr[MediaInfoMembers.HeightField] != null)
{
if (RegExUtility.IsNumber(dr[MediaInfoMembers.HeightField]))
{
this.p_Height = int.Parse(dr[MediaInfoMembers.HeightField].ToString(), System.Globalization.NumberStyles.Integer);
}
}
if (dr[MediaInfoMembers.MediaAlignmentField] != null)
{
if (RegExUtility.IsNumber(dr[MediaInfoMembers.MediaAlignmentField]))
{
this.p_MediaAlignment = int.Parse(dr[MediaInfoMembers.MediaAlignmentField].ToString(), System.Globalization.NumberStyles.Integer);
}
}
if (dr[MediaInfoMembers.ModuleIdField] != null)
{
if (RegExUtility.IsNumber(dr[MediaInfoMembers.ModuleIdField]))
{
this.p_ModuleID = int.Parse(dr[MediaInfoMembers.ModuleIdField].ToString(), System.Globalization.NumberStyles.Integer);
}
}
if (dr[MediaInfoMembers.NavigateUrlField] != null)
{
this.p_NavigateUrl = dr[MediaInfoMembers.NavigateUrlField].ToString();
}
if (dr[MediaInfoMembers.NewWindowField] != null)
{
if (RegExUtility.IsBoolean(dr[MediaInfoMembers.NewWindowField]))
{
this.p_NewWindow = bool.Parse(dr[MediaInfoMembers.NewWindowField].ToString());
}
}
if (dr[MediaInfoMembers.SrcField] != null)
{
this.p_Src = dr[MediaInfoMembers.SrcField].ToString();
}
if (dr[MediaInfoMembers.TrackClicksField] != null)
{
if (RegExUtility.IsBoolean(dr[MediaInfoMembers.TrackClicksField]))
{
this.p_TrackClicks = bool.Parse(dr[MediaInfoMembers.TrackClicksField].ToString());
}
}
if (dr[MediaInfoMembers.WidthField] != null)
{
if (RegExUtility.IsNumber(dr[MediaInfoMembers.WidthField]))
{
this.p_Width = int.Parse(dr[MediaInfoMembers.WidthField].ToString(), System.Globalization.NumberStyles.Integer);
}
}
if (dr[MediaInfoMembers.MediaLoopField] != null)
{
if (RegExUtility.IsBoolean(dr[MediaInfoMembers.MediaLoopField]))
{
this.p_MediaLoop = bool.Parse(dr[MediaInfoMembers.MediaLoopField].ToString());
}
}
if (dr[MediaInfoMembers.AutoStartField] != null)
{
if (RegExUtility.IsBoolean(dr[MediaInfoMembers.AutoStartField]))
{
this.p_AutoStart = bool.Parse(dr[MediaInfoMembers.AutoStartField].ToString());
}
}
if (dr[MediaInfoMembers.MediaTypeField] != null)
{
if (RegExUtility.IsNumber(dr[MediaInfoMembers.MediaTypeField]))
{
this.p_MediaType = int.Parse(dr[MediaInfoMembers.MediaTypeField].ToString(), System.Globalization.NumberStyles.Integer);
}
}
if (dr[MediaInfoMembers.MediaMessageField] != null)
{
this.p_MediaMessage = dr[MediaInfoMembers.MediaMessageField].ToString();
}
if (dr[MediaInfoMembers.LastUpdatedByField] != null)
{
if (RegExUtility.IsNumber(dr[MediaInfoMembers.LastUpdatedByField]))
{
this.p_LastUpdatedBy = int.Parse(dr[MediaInfoMembers.LastUpdatedByField].ToString(), System.Globalization.NumberStyles.Integer);
}
}
if (dr[MediaInfoMembers.LastUpdatedDateField] != null)
{
if (SimulateIsDate.IsDate(dr[MediaInfoMembers.LastUpdatedDateField]))
{
DateTime.TryParse(dr[MediaInfoMembers.LastUpdatedDateField].ToString(), out this.p_LastUpdatedDate);
}
}
}
}
catch (Exception ex)
{
Exceptions.LogException(ex);
}
finally
{
if (!dr.IsClosed)
{
dr.Close();
}
}
}
public int KeyID
{
get
{
return this.p_ModuleID;
}
set
{
this.p_ModuleID = value;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using Xunit;
public class ConvertToStringTests
{
[Fact]
public static void FromBoxedObject()
{
Object[] testValues =
{
// Boolean
true,
false,
// Byte
Byte.MinValue,
(Byte)100,
Byte.MaxValue,
// Decimal
Decimal.Zero,
Decimal.One,
Decimal.MinusOne,
Decimal.MaxValue,
Decimal.MinValue,
1.234567890123456789012345678m,
1234.56m,
-1234.56m,
// Double
-12.2364,
-12.236465923406483,
-1.7753E-83,
+12.345e+234,
+12e+1,
Double.NegativeInfinity,
Double.PositiveInfinity,
Double.NaN,
// Int16
Int16.MinValue,
0,
Int16.MaxValue,
// Int32
Int32.MinValue,
0,
Int32.MaxValue,
// Int64
Int64.MinValue,
(Int64)0,
Int64.MaxValue,
// SByte
SByte.MinValue,
(SByte)0,
SByte.MaxValue,
// Single
-12.2364f,
-12.2364659234064826243f,
-1.7753e-83f,
(float)+12.345e+234,
+12e+1f,
Single.NegativeInfinity,
Single.PositiveInfinity,
Single.NaN,
// TimeSpan
TimeSpan.Zero,
TimeSpan.Parse("1999.9:09:09"),
TimeSpan.Parse("-1111.1:11:11"),
TimeSpan.Parse("1:23:45"),
TimeSpan.Parse("-2:34:56"),
// UInt16
UInt16.MinValue,
(UInt16)100,
UInt16.MaxValue,
// UInt32
UInt32.MinValue,
(UInt32)100,
UInt32.MaxValue,
// UInt64
UInt64.MinValue,
(UInt64)100,
UInt64.MaxValue
};
String[] expectedValues =
{
// Boolean
"True",
"False",
// Byte
"0",
"100",
"255",
// Decimal
"0",
"1",
"-1",
"79228162514264337593543950335",
"-79228162514264337593543950335",
"1.234567890123456789012345678",
"1234.56",
"-1234.56",
// Double
"-12.2364",
"-12.2364659234065",
"-1.7753E-83",
"1.2345E+235",
"120",
"-Infinity",
"Infinity",
"NaN",
// Int16
"-32768",
"0",
"32767",
// Int32
"-2147483648",
"0",
"2147483647",
// Int64
"-9223372036854775808",
"0",
"9223372036854775807",
// SByte
"-128",
"0",
"127",
// Single
"-12.2364",
"-12.23647",
"0",
"Infinity",
"120",
"-Infinity",
"Infinity",
"NaN",
// TimeSpan
"00:00:00",
"1999.09:09:09",
"-1111.01:11:11",
"01:23:45",
"-02:34:56",
// UInt16
"0",
"100",
"65535",
// UInt32
"0",
"100",
"4294967295",
// UInt64
"0",
"100",
"18446744073709551615",
};
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], NumberFormatInfo.InvariantInfo));
}
}
[Fact]
public static void FromObject()
{
Assert.Equal("ConvertToStringTests", Convert.ToString(new ConvertToStringTests()));
}
[Fact]
public static void FromDateTime()
{
DateTime[] testValues = { new DateTime(2000, 8, 15, 16, 59, 59), new DateTime(1, 1, 1, 1, 1, 1) };
string[] expectedValues = { "08/15/2000 16:59:59", "01/01/0001 01:01:01" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(testValues[i].ToString(), Convert.ToString(testValues[i]));
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], DateTimeFormatInfo.InvariantInfo));
}
}
[Fact]
public static void FromChar()
{
Char[] testValues = { 'a', 'A', '@', '\n' };
String[] expectedValues = { "a", "A", "@", "\n" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i]));
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], CultureInfo.InvariantCulture));
}
}
private static void Verify<TInput>(Func<TInput, String> convert, Func<TInput, IFormatProvider, String> convertWithFormatProvider, TInput[] testValues, String[] expectedValues, IFormatProvider formatProvider = null)
{
Assert.Equal(expectedValues.Length, testValues.Length);
if (formatProvider == null)
{
formatProvider = CultureInfo.InvariantCulture;
}
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], convert(testValues[i]));
Assert.Equal(expectedValues[i], convertWithFormatProvider(testValues[i], formatProvider));
}
}
[Fact]
public static void FromByteBase2()
{
Byte[] testValues = { Byte.MinValue, 100, Byte.MaxValue };
String[] expectedValues = { "0", "1100100", "11111111" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2));
}
}
[Fact]
public static void FromByteBase8()
{
Byte[] testValues = { Byte.MinValue, 100, Byte.MaxValue };
String[] expectedValues = { "0", "144", "377" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8));
}
}
[Fact]
public static void FromByteBase10()
{
Byte[] testValues = { Byte.MinValue, 100, Byte.MaxValue };
String[] expectedValues = { "0", "100", "255" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10));
}
}
[Fact]
public static void FromByteBase16()
{
Byte[] testValues = { Byte.MinValue, 100, Byte.MaxValue };
String[] expectedValues = { "0", "64", "ff" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16));
}
}
[Fact]
public static void FromByteInvalidBase()
{
Assert.Throws<ArgumentException>(() => Convert.ToString(Byte.MaxValue, 13));
}
[Fact]
public static void FromInt16Base2()
{
Int16[] testValues = { Int16.MinValue, 0, Int16.MaxValue };
String[] expectedValues = { "1000000000000000", "0", "111111111111111" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2));
}
}
[Fact]
public static void FromInt16Base8()
{
Int16[] testValues = { Int16.MinValue, 0, Int16.MaxValue };
String[] expectedValues = { "100000", "0", "77777" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8));
}
}
[Fact]
public static void FromInt16Base10()
{
Int16[] testValues = { Int16.MinValue, 0, Int16.MaxValue };
String[] expectedValues = { "-32768", "0", "32767" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10));
}
}
[Fact]
public static void FromInt16Base16()
{
Int16[] testValues = { Int16.MinValue, 0, Int16.MaxValue };
String[] expectedValues = { "8000", "0", "7fff" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16));
}
}
[Fact]
public static void FromInt16InvalidBase()
{
Assert.Throws<ArgumentException>(() => Convert.ToString(Int16.MaxValue, 0));
}
[Fact]
public static void FromInt32Base2()
{
Int32[] testValues = { Int32.MinValue, 0, Int32.MaxValue };
String[] expectedValues = { "10000000000000000000000000000000", "0", "1111111111111111111111111111111" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2));
}
}
[Fact]
public static void FromInt32Base8()
{
Int32[] testValues = { Int32.MinValue, 0, Int32.MaxValue };
String[] expectedValues = { "20000000000", "0", "17777777777" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8));
}
}
[Fact]
public static void FromInt32Base10()
{
Int32[] testValues = { Int32.MinValue, 0, Int32.MaxValue };
String[] expectedValues = { "-2147483648", "0", "2147483647" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10));
}
}
[Fact]
public static void FromInt32Base16()
{
Int32[] testValues = { Int32.MinValue, 0, Int32.MaxValue };
String[] expectedValues = { "80000000", "0", "7fffffff" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16));
}
}
[Fact]
public static void FromInt32InvalidBase()
{
Assert.Throws<ArgumentException>(() => Convert.ToString(Int32.MaxValue, 9));
}
[Fact]
public static void FromInt64Base2()
{
Int64[] testValues = { Int64.MinValue, 0, Int64.MaxValue };
String[] expectedValues = { "1000000000000000000000000000000000000000000000000000000000000000", "0", "111111111111111111111111111111111111111111111111111111111111111" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2));
}
}
[Fact]
public static void FromInt64Base8()
{
Int64[] testValues = { Int64.MinValue, 0, Int64.MaxValue };
String[] expectedValues = { "1000000000000000000000", "0", "777777777777777777777" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8));
}
}
[Fact]
public static void FromInt64Base10()
{
Int64[] testValues = { Int64.MinValue, 0, Int64.MaxValue };
String[] expectedValues = { "-9223372036854775808", "0", "9223372036854775807" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10));
}
}
[Fact]
public static void FromInt64Base16()
{
Int64[] testValues = { Int64.MinValue, 0, Int64.MaxValue };
String[] expectedValues = { "8000000000000000", "0", "7fffffffffffffff" };
for (int i = 0; i < testValues.Length; i++)
{
Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16));
}
}
[Fact]
public static void FromInt64InvalidBase()
{
Assert.Throws<ArgumentException>(() => Convert.ToString(Int64.MaxValue, 1));
}
[Fact]
public static void FromBoolean()
{
Boolean[] testValues = new[] { true, false };
for (int i = 0; i < testValues.Length; i++)
{
string expected = testValues[i].ToString();
string actual = Convert.ToString(testValues[i]);
Assert.Equal(expected, actual);
actual = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(expected, actual);
}
}
[Fact]
public static void FromSByte()
{
SByte[] testValues = new SByte[] { SByte.MinValue, -1, 0, 1, SByte.MaxValue };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromByte()
{
Byte[] testValues = new Byte[] { Byte.MinValue, 0, 1, 100, Byte.MaxValue };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromInt16Array()
{
Int16[] testValues = new Int16[] { Int16.MinValue, -1000, -1, 0, 1, 1000, Int16.MaxValue };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromUInt16Array()
{
UInt16[] testValues = new UInt16[] { UInt16.MinValue, 0, 1, 1000, UInt16.MaxValue };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromInt32Array()
{
Int32[] testValues = new Int32[] { Int32.MinValue, -1000, -1, 0, 1, 1000, Int32.MaxValue };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromUInt32Array()
{
UInt32[] testValues = new UInt32[] { UInt32.MinValue, 0, 1, 1000, UInt32.MaxValue };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromInt64Array()
{
Int64[] testValues = new Int64[] { Int64.MinValue, -1000, -1, 0, 1, 1000, Int64.MaxValue };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromUInt64Array()
{
UInt64[] testValues = new UInt64[] { UInt64.MinValue, 0, 1, 1000, UInt64.MaxValue };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromSingleArray()
{
Single[] testValues = new Single[] { Single.MinValue, 0.0f, 1.0f, 1000.0f, Single.MaxValue, Single.NegativeInfinity, Single.PositiveInfinity, Single.Epsilon, Single.NaN };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromDoubleArray()
{
Double[] testValues = new Double[] { Double.MinValue, 0.0, 1.0, 1000.0, Double.MaxValue, Double.NegativeInfinity, Double.PositiveInfinity, Double.Epsilon, Double.NaN };
// Vanila Test Cases
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromDecimalArray()
{
Decimal[] testValues = new Decimal[] { Decimal.MinValue, Decimal.Parse("-1.234567890123456789012345678", NumberFormatInfo.InvariantInfo), (Decimal)0.0, (Decimal)1.0, (Decimal)1000.0, Decimal.MaxValue, Decimal.One, Decimal.Zero, Decimal.MinusOne };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result);
}
}
[Fact]
public static void FromDateTimeArray()
{
DateTime[] testValues = new DateTime[] {
DateTime.Parse("08/15/2000 16:59:59", DateTimeFormatInfo.InvariantInfo),
DateTime.Parse("01/01/0001 01:01:01", DateTimeFormatInfo.InvariantInfo) };
IFormatProvider formatProvider = DateTimeFormatInfo.GetInstance(new CultureInfo("en-US"));
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], formatProvider);
String expected = testValues[i].ToString(formatProvider);
Assert.Equal(expected, result);
}
}
[Fact]
public static void FromString()
{
String[] testValues = new String[] { "Hello", " ", "", "\0" };
for (int i = 0; i < testValues.Length; i++)
{
String result = Convert.ToString(testValues[i]);
Assert.Equal(testValues[i].ToString(), result);
result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo);
Assert.Equal(testValues[i].ToString(), result);
}
}
[Fact]
public static void FromIFormattable()
{
FooFormattable foo = new FooFormattable(3);
String result = Convert.ToString(foo);
Assert.Equal("FooFormattable: 3", result);
result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo);
Assert.Equal("System.Globalization.NumberFormatInfo: 3", result);
foo = null;
result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo);
Assert.Equal("", result);
}
[Fact]
public static void FromNonIConvertible()
{
Foo foo = new Foo(3);
String result = Convert.ToString(foo);
Assert.Equal("ConvertToStringTests+Foo", result);
result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo);
Assert.Equal("ConvertToStringTests+Foo", result);
foo = null;
result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo);
Assert.Equal("", result);
}
private class FooFormattable : IFormattable
{
private int _value;
public FooFormattable(int value) { _value = value; }
public String ToString(String format, IFormatProvider formatProvider)
{
if (formatProvider != null)
{
return String.Format("{0}: {1}", formatProvider, _value);
}
else
{
return String.Format("FooFormattable: {0}", (_value));
}
}
}
private class Foo
{
private int _value;
public Foo(int value) { _value = value; }
public String ToString(IFormatProvider provider)
{
if (provider != null)
{
return String.Format("{0}: {1}", provider, _value);
}
else
{
return String.Format("Foo: {0}", _value);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.Runtime.Augments;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
namespace System.Threading
{
//
// Implementation of ThreadPoolBoundHandle that sits on top of the Win32 ThreadPool
//
public sealed class ThreadPoolBoundHandle : IDisposable, IDeferredDisposable
{
private readonly SafeHandle _handle;
private readonly SafeThreadPoolIOHandle _threadPoolHandle;
private DeferredDisposableLifetime<ThreadPoolBoundHandle> _lifetime;
private ThreadPoolBoundHandle(SafeHandle handle, SafeThreadPoolIOHandle threadPoolHandle)
{
_threadPoolHandle = threadPoolHandle;
_handle = handle;
}
public SafeHandle Handle
{
get { return _handle; }
}
public static ThreadPoolBoundHandle BindHandle(SafeHandle handle)
{
if (handle == null)
throw new ArgumentNullException(nameof(handle));
if (handle.IsClosed || handle.IsInvalid)
throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
IntPtr callback = AddrofIntrinsics.AddrOf<Interop.NativeIoCompletionCallback>(OnNativeIOCompleted);
SafeThreadPoolIOHandle threadPoolHandle = Interop.mincore.CreateThreadpoolIo(handle, callback, IntPtr.Zero, IntPtr.Zero);
if (threadPoolHandle.IsInvalid)
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE) // Bad handle
throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER) // Handle already bound or sync handle
throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, nameof(handle));
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
return new ThreadPoolBoundHandle(handle, threadPoolHandle);
}
[CLSCompliant(false)]
public unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object state, object pinData)
{
if (callback == null)
throw new ArgumentNullException(nameof(callback));
AddRef();
try
{
Win32ThreadPoolNativeOverlapped* overlapped = Win32ThreadPoolNativeOverlapped.Allocate(callback, state, pinData, preAllocated: null);
overlapped->Data._boundHandle = this;
Interop.mincore.StartThreadpoolIo(_threadPoolHandle);
return Win32ThreadPoolNativeOverlapped.ToNativeOverlapped(overlapped);
}
catch
{
Release();
throw;
}
}
[CLSCompliant(false)]
public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated)
{
if (preAllocated == null)
throw new ArgumentNullException(nameof(preAllocated));
bool addedRefToThis = false;
bool addedRefToPreAllocated = false;
try
{
addedRefToThis = AddRef();
addedRefToPreAllocated = preAllocated.AddRef();
Win32ThreadPoolNativeOverlapped.OverlappedData data = preAllocated._overlapped->Data;
if (data._boundHandle != null)
throw new ArgumentException(SR.Argument_PreAllocatedAlreadyAllocated, nameof(preAllocated));
data._boundHandle = this;
Interop.mincore.StartThreadpoolIo(_threadPoolHandle);
return Win32ThreadPoolNativeOverlapped.ToNativeOverlapped(preAllocated._overlapped);
}
catch
{
if (addedRefToPreAllocated)
preAllocated.Release();
if (addedRefToThis)
Release();
throw;
}
}
[CLSCompliant(false)]
public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped)
{
if (overlapped == null)
throw new ArgumentNullException(nameof(overlapped));
Win32ThreadPoolNativeOverlapped* threadPoolOverlapped = Win32ThreadPoolNativeOverlapped.FromNativeOverlapped(overlapped);
Win32ThreadPoolNativeOverlapped.OverlappedData data = GetOverlappedData(threadPoolOverlapped, this);
if (!data._completed)
{
Interop.mincore.CancelThreadpoolIo(_threadPoolHandle);
Release();
}
data._boundHandle = null;
data._completed = false;
if (data._preAllocated != null)
data._preAllocated.Release();
else
Win32ThreadPoolNativeOverlapped.Free(threadPoolOverlapped);
}
[CLSCompliant(false)]
public static unsafe object GetNativeOverlappedState(NativeOverlapped* overlapped)
{
if (overlapped == null)
throw new ArgumentNullException(nameof(overlapped));
Win32ThreadPoolNativeOverlapped* threadPoolOverlapped = Win32ThreadPoolNativeOverlapped.FromNativeOverlapped(overlapped);
Win32ThreadPoolNativeOverlapped.OverlappedData data = GetOverlappedData(threadPoolOverlapped, null);
return threadPoolOverlapped->Data._state;
}
private static unsafe Win32ThreadPoolNativeOverlapped.OverlappedData GetOverlappedData(Win32ThreadPoolNativeOverlapped* overlapped, ThreadPoolBoundHandle expectedBoundHandle)
{
Win32ThreadPoolNativeOverlapped.OverlappedData data = overlapped->Data;
if (data._boundHandle == null)
throw new ArgumentException(SR.Argument_NativeOverlappedAlreadyFree, nameof(overlapped));
if (expectedBoundHandle != null && data._boundHandle != expectedBoundHandle)
throw new ArgumentException(SR.Argument_NativeOverlappedWrongBoundHandle, nameof(overlapped));
return data;
}
[NativeCallable(CallingConvention = CallingConvention.StdCall)]
private static unsafe void OnNativeIOCompleted(IntPtr instance, IntPtr context, IntPtr overlappedPtr, uint ioResult, UIntPtr numberOfBytesTransferred, IntPtr ioPtr)
{
RuntimeThread.InitializeThreadPoolThread();
Win32ThreadPoolNativeOverlapped* overlapped = (Win32ThreadPoolNativeOverlapped*)overlappedPtr;
ThreadPoolBoundHandle boundHandle = overlapped->Data._boundHandle;
if (boundHandle == null)
throw new InvalidOperationException(SR.Argument_NativeOverlappedAlreadyFree);
boundHandle.Release();
Win32ThreadPoolNativeOverlapped.CompleteWithCallback(ioResult, (uint)numberOfBytesTransferred, overlapped);
}
private bool AddRef()
{
return _lifetime.AddRef(this);
}
private void Release()
{
_lifetime.Release(this);
}
public void Dispose()
{
_lifetime.Dispose(this);
GC.SuppressFinalize(this);
}
~ThreadPoolBoundHandle()
{
//
// During shutdown, don't automatically clean up, because this instance may still be
// reachable/usable by other code.
//
if (!Environment.HasShutdownStarted)
Dispose();
}
void IDeferredDisposable.OnFinalRelease(bool disposed)
{
if (disposed)
_threadPoolHandle.Dispose();
}
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections;
using System.Collections.Generic;
using UMA;
using UMAAssetBundleManager;
public class DynamicRaceLibrary : RaceLibrary
{
//extra fields for Dynamic Version
public bool dynamicallyAddFromResources;
[Tooltip("Limit the Resources search to the following folders (no starting slash and seperate multiple entries with a comma)")]
public string resourcesFolderPath = "";
public bool dynamicallyAddFromAssetBundles;
[Tooltip("Limit the AssetBundles search to the following bundles (no starting slash and seperate multiple entries with a comma)")]
public string assetBundleNamesToSearch = "";
//This is a ditionary of asset bundles that were loaded into the library at runtime.
//CharacterAvatar can query this this to find out what asset bundles were required to create itself
//or other scripts can use it to find out which asset bundles are being used by the Libraries at any given point.
public Dictionary<string, List<string>> assetBundlesUsedDict = new Dictionary<string, List<string>>();
#if UNITY_EDITOR
//if we have already added everything in the editor dont do it again
bool allAssetsAddedInEditor = false;
[HideInInspector]
List<RaceData> editorAddedAssets = new List<RaceData>();
#endif
[System.NonSerialized]
bool allStartingAssetsAdded = false;
[System.NonSerialized]
[HideInInspector]
public bool downloadAssetsEnabled = true;
#if UNITY_EDITOR
void Reset()
{
allStartingAssetsAdded = false;//make this false to that loading new scenes makes the library update
allAssetsAddedInEditor = false;
}
#endif
public void Awake()
{
#if UNITY_EDITOR
allStartingAssetsAdded = false;//make this false to that loading new scenes makes the library update
allAssetsAddedInEditor = false;
#endif
}
public void Start()
{
if (Application.isPlaying)
{
assetBundlesUsedDict.Clear();
}
#if UNITY_EDITOR
if (Application.isPlaying)
{
ClearEditorAddedAssets();
}
allStartingAssetsAdded = false;//make this false to that loading new scenes makes the library update
allAssetsAddedInEditor = false;
#endif
}
/// <summary>
/// Clears any editor added assets when the Scene is closed
/// </summary>
void OnDestroy()
{
#if UNITY_EDITOR
ClearEditorAddedAssets();
#endif
}
public void ClearEditorAddedAssets()
{
#if UNITY_EDITOR
if (editorAddedAssets.Count > 0)
{
editorAddedAssets.Clear();
allAssetsAddedInEditor = false;
}
#endif
}
#if UNITY_EDITOR
RaceData GetEditorAddedAsset(int? raceHash = null, string raceName = "")
{
RaceData foundRaceData = null;
if (editorAddedAssets.Count > 0)
{
foreach (RaceData edRace in editorAddedAssets)
{
if (edRace != null)
{
if (raceHash != null)
{
if (UMAUtils.StringToHash(edRace.raceName) == raceHash)
foundRaceData = edRace;
}
else if (raceName != null)
{
if (raceName != "")
if (edRace.raceName == raceName)
foundRaceData = edRace;
}
}
}
}
return foundRaceData;
}
#endif
public void UpdateDynamicRaceLibrary(bool downloadAssets, int? raceHash = null)
{
if (allStartingAssetsAdded && raceHash == null)
return;
//Making the race library scan everything (by sending raceHash = null) only needs to happen once- at all other times a specific race will have been requested (and been added by dynamic asset loader) so it will already be here if it needs to be.
if (raceHash == null && Application.isPlaying && allStartingAssetsAdded == false && UMAResourcesIndex.Instance != null && UMAResourcesIndex.Instance.enableDynamicIndexing == false)
allStartingAssetsAdded = true;
#if UNITY_EDITOR
if (allAssetsAddedInEditor && raceHash == null)
return;
#endif
if (DynamicAssetLoader.Instance != null)
DynamicAssetLoader.Instance.AddAssets<RaceData>(ref assetBundlesUsedDict, dynamicallyAddFromResources, dynamicallyAddFromAssetBundles, downloadAssets, assetBundleNamesToSearch, resourcesFolderPath, raceHash, "", AddRaces);
#if UNITY_EDITOR
if (raceHash == null && !Application.isPlaying)
allAssetsAddedInEditor = true;
#endif
}
public void UpdateDynamicRaceLibrary(string raceName)
{
DynamicAssetLoader.Instance.AddAssets<RaceData>(ref assetBundlesUsedDict, dynamicallyAddFromResources, dynamicallyAddFromAssetBundles, downloadAssetsEnabled, assetBundleNamesToSearch, resourcesFolderPath, null, raceName, AddRaces);
}
#pragma warning disable 618
private void AddRaces(RaceData[] races)
{
int currentNumRaces = raceElementList.Length;
foreach (RaceData race in races)
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
if (!editorAddedAssets.Contains(race))
{
editorAddedAssets.Add(race);
if (UMAContext.Instance == null)
UMAContext.FindInstance();
if (UMAContext.Instance.dynamicCharacterSystem != null)
{
(UMAContext.Instance.dynamicCharacterSystem as UMACharacterSystem.DynamicCharacterSystem).Refresh(false);
}
}
}
else
#endif
AddRace(race);
}
//Ensure the new races have keys in the DCS dictionary
if (currentNumRaces != raceElementList.Length && Application.isPlaying)
{
if (UMAContext.Instance == null)
UMAContext.FindInstance();
if (UMAContext.Instance != null && UMAContext.Instance.dynamicCharacterSystem != null)
{
(UMAContext.Instance.dynamicCharacterSystem as UMACharacterSystem.DynamicCharacterSystem).RefreshRaceKeys();
}
}
//This doesn't actually seem to do anything apart from slow things down
//StartCoroutine(CleanRacesFromResourcesAndBundles());
}
#pragma warning restore 618
/*IEnumerator CleanRacesFromResourcesAndBundles()
{
yield return null;
Resources.UnloadUnusedAssets();
yield break;
}*/
#pragma warning disable 618
//We need to override AddRace Too because if the element is not in the list anymore it causes an error...
override public void AddRace(RaceData race)
{
if (race == null)
return;
race.UpdateDictionary();
try
{
base.AddRace(race);
}
catch
{
//if there is an error it will be because RaceElementList contained an empty refrence
List<RaceData> newRaceElementList = new List<RaceData>();
for (int i = 0; i < raceElementList.Length; i++)
{
if (raceElementList[i] != null)
{
raceElementList[i].UpdateDictionary();
newRaceElementList.Add(raceElementList[i]);
}
}
raceElementList = newRaceElementList.ToArray();
base.AddRace(race);
}
}
#pragma warning restore 618
//TODO if this works it should maybe be the other way round for backwards compatability- i.e. so unless you do something different this does what it always did do...
public override RaceData GetRace(string raceName)
{
return GetRace(raceName, true);
}
public RaceData GetRace(string raceName, bool allowUpdate = true)
{
if ((raceName == null) || (raceName.Length == 0))
return null;
RaceData res;
res = base.GetRace(raceName);
#if UNITY_EDITOR
if (!Application.isPlaying && res == null)
{
res = GetEditorAddedAsset(null, raceName);
}
#endif
if (res == null && allowUpdate)
{
//we try to load the race dynamically
UpdateDynamicRaceLibrary(raceName);
res = base.GetRace(raceName);
if (res == null)
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
res = GetEditorAddedAsset(null, raceName);
if (res != null)
{
return res;
}
}
#endif
return null;
}
}
return res;
}
public override RaceData GetRace(int nameHash)
{
return GetRace(nameHash, true);
}
public RaceData GetRace(int nameHash, bool allowUpdate = true)
{
if (nameHash == 0)
return null;
RaceData res;
res = base.GetRace(nameHash);
#if UNITY_EDITOR
if (!Application.isPlaying && res == null)
{
res = GetEditorAddedAsset(nameHash);
}
#endif
if (res == null && allowUpdate)
{
UpdateDynamicRaceLibrary(true, nameHash);
res = base.GetRace(nameHash);
if (res == null)
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
res = GetEditorAddedAsset(nameHash);
if (res != null)
{
return res;
}
}
#endif
return null;
}
}
return res;
}
/// <summary>
/// Returns the current list of races without adding from assetBundles or Resources
/// </summary>
/// <returns></returns>
public RaceData[] GetAllRacesBase()
{
return base.GetAllRaces();
}
/// <summary>
/// Gets all the races that are available including in Resources (but does not cause downloads for races that are in assetbundles)
/// </summary>
/// <returns></returns>
public override RaceData[] GetAllRaces()
{
UpdateDynamicRaceLibrary(false);
#if UNITY_EDITOR
if (!Application.isPlaying)
{
//we need a combined array of the editor added assets and the baseGetAllRaces Array
List<RaceData> combinedRaceDatas = new List<RaceData>(base.GetAllRaces());
if (editorAddedAssets.Count > 0)
{
combinedRaceDatas.AddRange(editorAddedAssets);
}
return combinedRaceDatas.ToArray();
}
else
#endif
return base.GetAllRaces();
}
/// <summary>
/// Gets the originating asset bundle.
/// </summary>
/// <returns>The originating asset bundle.</returns>
/// <param name="raceName">Race name.</param>
public string GetOriginatingAssetBundle(string raceName)
{
string originatingAssetBundle = "";
if (assetBundlesUsedDict.Count > 0)
{
foreach (KeyValuePair<string, List<string>> kp in assetBundlesUsedDict)
{
if (kp.Value.Contains(raceName))
{
originatingAssetBundle = kp.Key;
break;
}
}
}
if (originatingAssetBundle == "")
{
Debug.Log(raceName + " was not found in any loaded AssetBundle");
}
else
{
Debug.Log("originatingAssetBundle for " + raceName + " was " + originatingAssetBundle);
}
return originatingAssetBundle;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.