context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Runtime.ExceptionServices;
using Microsoft.DebugEngineHost;
using MICore;
using Logger = MICore.Logger;
namespace Microsoft.MIDebugEngine
{
public delegate void Operation();
public delegate Task AsyncOperation();
public delegate Task AsyncProgressOperation(HostWaitLoop waitLoop);
/// <summary>
/// Worker thread used to process MI Debugger output and used to process AD7 commands
/// </summary>
internal class WorkerThread : IDisposable
{
private readonly AutoResetEvent _opSet;
private readonly ManualResetEvent _runningOpCompleteEvent; // fired when either m_syncOp finishes, or the kick off of m_async
private readonly Object _eventLock = new object(); // Locking on an event directly can cause Mono to stop responding.
private readonly Queue<Operation> _postedOperations; // queue of fire-and-forget operations
public event EventHandler<Exception> PostedOperationErrorEvent;
private class OperationDescriptor
{
/// <summary>
/// Delegate that was added via 'RunOperation'. Is of type 'Operation' or 'AsyncOperation'
/// </summary>
public readonly Delegate Target;
public ExceptionDispatchInfo ExceptionDispatchInfo;
public Task Task;
private bool _isStarted;
private bool _isComplete;
public OperationDescriptor(Delegate target)
{
this.Target = target;
}
public bool IsComplete
{
get { return _isComplete; }
}
public void MarkComplete()
{
Debug.Assert(_isStarted == true, "MarkComplete called before MarkStarted?");
Debug.Assert(_isComplete == false, "MarkComplete called more than once??");
_isComplete = true;
}
public bool IsStarted
{
get { return _isStarted; }
}
public void MarkStarted()
{
Debug.Assert(_isStarted == false, "MarkStarted called more than once??");
_isStarted = true;
}
}
private OperationDescriptor _runningOp;
private Thread _thread;
private volatile bool _isClosed;
public Logger Logger { get; private set; }
public WorkerThread(Logger logger)
{
Logger = logger;
_opSet = new AutoResetEvent(false);
_runningOpCompleteEvent = new ManualResetEvent(true);
_postedOperations = new Queue<Operation>();
_thread = new Thread(new ThreadStart(ThreadFunc));
_thread.Name = "MIDebugger.PollThread";
_thread.Start();
}
/// <summary>
/// Send an operation to the worker thread, and block for it to finish. This is used for implementing
/// most AD7 interfaces. This will wait for other 'RunOperation' calls to finish before starting.
/// </summary>
/// <param name="op">Delegate for the code to run on the worker thread</param>
public void RunOperation(Operation op)
{
if (op == null)
throw new ArgumentNullException();
SetOperationInternal(op);
}
/// <summary>
/// Send an operation to the worker thread, and block for it to finish (task returns complete). This is used for implementing
/// most AD7 interfaces. This will wait for other 'RunOperation' calls to finish before starting.
/// </summary>
/// <param name="op">Delegate for the code to run on the worker thread. This returns a Task that we wait on.</param>
public void RunOperation(AsyncOperation op)
{
if (op == null)
throw new ArgumentNullException();
SetOperationInternal(op);
}
public void RunOperation(string text, CancellationTokenSource canTokenSource, AsyncProgressOperation op)
{
if (op == null)
throw new ArgumentNullException();
SetOperationInternalWithProgress(op, text, canTokenSource);
}
public void Close()
{
if (_isClosed)
return;
// block out posting any more operations
lock (_postedOperations)
{
if (_isClosed)
return;
_isClosed = true;
// Wait for any pending running operations to finish
while (true)
{
_runningOpCompleteEvent.WaitOne();
lock (_eventLock)
{
if (_runningOp == null)
{
_opSet.Set();
break;
}
}
}
}
}
internal void SetOperationInternal(Delegate op)
{
// If this is called on the Worker thread it will deadlock
Debug.Assert(!IsPollThread());
while (true)
{
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
_runningOpCompleteEvent.WaitOne();
if (TrySetOperationInternal(op))
{
return;
}
}
}
internal void SetOperationInternalWithProgress(AsyncProgressOperation op, string text, CancellationTokenSource canTokenSource)
{
// If this is called on the Worker thread it will deadlock
Debug.Assert(!IsPollThread());
while (true)
{
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
_runningOpCompleteEvent.WaitOne();
if (TrySetOperationInternalWithProgress(op, text, canTokenSource))
{
return;
}
}
}
public void PostOperation(Operation op)
{
if (op == null)
throw new ArgumentNullException();
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
lock (_postedOperations)
{
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
_postedOperations.Enqueue(op);
if (_postedOperations.Count == 1)
{
_opSet.Set();
}
}
}
private bool TrySetOperationInternal(Delegate op)
{
lock (_eventLock)
{
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
if (_runningOp == null)
{
_runningOpCompleteEvent.Reset();
OperationDescriptor runningOp = new OperationDescriptor(op);
_runningOp = runningOp;
_opSet.Set();
_runningOpCompleteEvent.WaitOne();
Debug.Assert(runningOp.IsComplete, "Why isn't the running op complete?");
if (runningOp.ExceptionDispatchInfo != null)
{
runningOp.ExceptionDispatchInfo.Throw();
}
return true;
}
}
return false;
}
private bool TrySetOperationInternalWithProgress(AsyncProgressOperation op, string text, CancellationTokenSource canTokenSource)
{
var waitLoop = new HostWaitLoop(text);
lock (_eventLock)
{
if (_isClosed)
throw new ObjectDisposedException("WorkerThread");
if (_runningOp == null)
{
_runningOpCompleteEvent.Reset();
OperationDescriptor runningOp = new OperationDescriptor(new AsyncOperation(() => { return op(waitLoop); }));
_runningOp = runningOp;
_opSet.Set();
waitLoop.Wait(_runningOpCompleteEvent, canTokenSource);
Debug.Assert(runningOp.IsComplete, "Why isn't the running op complete?");
if (runningOp.ExceptionDispatchInfo != null)
{
runningOp.ExceptionDispatchInfo.Throw();
}
return true;
}
}
return false;
}
// Thread routine for the poll loop. It handles calls coming in from the debug engine as well as polling for debug events.
private void ThreadFunc()
{
while (!_isClosed)
{
// Wait for an operation to be set
_opSet.WaitOne();
// Run until we go through a loop where there was nothing to do
bool ranOperation;
do
{
ranOperation = false;
OperationDescriptor runningOp = _runningOp;
if (runningOp != null && !runningOp.IsStarted)
{
runningOp.MarkStarted();
ranOperation = true;
bool completeAsync = false;
Operation syncOp = runningOp.Target as Operation;
if (syncOp != null)
{
try
{
syncOp();
}
catch (Exception opException) when (ExceptionHelper.BeforeCatch(opException, Logger, reportOnlyCorrupting: true))
{
runningOp.ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(opException);
}
}
else
{
AsyncOperation asyncOp = (AsyncOperation)runningOp.Target;
try
{
runningOp.Task = asyncOp();
}
catch (Exception opException) when (ExceptionHelper.BeforeCatch(opException, Logger, reportOnlyCorrupting: true))
{
runningOp.ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(opException);
}
if (runningOp.Task != null)
{
runningOp.Task.ContinueWith(OnAsyncRunningOpComplete, TaskContinuationOptions.ExecuteSynchronously);
completeAsync = true;
}
}
if (!completeAsync)
{
runningOp.MarkComplete();
Debug.Assert(_runningOp == runningOp, "How did m_runningOp change?");
_runningOp = null;
_runningOpCompleteEvent.Set();
}
}
Operation postedOperation = null;
lock (_postedOperations)
{
if (_postedOperations.Count > 0)
{
postedOperation = _postedOperations.Dequeue();
}
}
if (postedOperation != null)
{
ranOperation = true;
try
{
postedOperation();
}
catch (Exception e) when (ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: false))
{
if (PostedOperationErrorEvent != null)
{
PostedOperationErrorEvent(this, e);
}
}
}
}
while (ranOperation);
}
}
internal void OnAsyncRunningOpComplete(Task t)
{
Debug.Assert(_runningOp != null, "How did m_runningOp get cleared?");
Debug.Assert(t == _runningOp.Task, "Why is a different task completing?");
if (t.Exception != null)
{
if (t.Exception.InnerException != null)
{
_runningOp.ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(t.Exception.InnerException);
}
else
{
_runningOp.ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(t.Exception);
}
}
_runningOp.MarkComplete();
_runningOp = null;
_runningOpCompleteEvent.Set();
}
internal bool IsPollThread()
{
return Thread.CurrentThread == _thread;
}
void IDisposable.Dispose()
{
Close();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using OrchardCore.Modules;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OrchardCore.Data.Migration.Records;
using OrchardCore.Environment.Extensions;
using YesSql;
using YesSql.Sql;
namespace OrchardCore.Data.Migration
{
public class DataMigrationManager : IDataMigrationManager
{
private readonly IEnumerable<IDataMigration> _dataMigrations;
private readonly ISession _session;
private readonly IStore _store;
private readonly IExtensionManager _extensionManager;
private readonly ILogger _logger;
private readonly ITypeFeatureProvider _typeFeatureProvider;
private readonly List<string> _processedFeatures;
private DataMigrationRecord _dataMigrationRecord;
public DataMigrationManager(
ITypeFeatureProvider typeFeatureProvider,
IEnumerable<IDataMigration> dataMigrations,
ISession session,
IStore store,
IExtensionManager extensionManager,
ILogger<DataMigrationManager> logger,
IStringLocalizer<DataMigrationManager> localizer)
{
_typeFeatureProvider = typeFeatureProvider;
_dataMigrations = dataMigrations;
_session = session;
_store = store;
_extensionManager = extensionManager;
_logger = logger;
_processedFeatures = new List<string>();
T = localizer;
}
public IStringLocalizer T { get; set; }
public async Task<DataMigrationRecord> GetDataMigrationRecordAsync()
{
if (_dataMigrationRecord == null)
{
_dataMigrationRecord = await _session.Query<DataMigrationRecord>().FirstOrDefaultAsync();
if (_dataMigrationRecord == null)
{
_dataMigrationRecord = new DataMigrationRecord();
_session.Save(_dataMigrationRecord);
}
}
return _dataMigrationRecord;
}
public async Task<IEnumerable<string>> GetFeaturesThatNeedUpdateAsync()
{
var currentVersions = (await GetDataMigrationRecordAsync()).DataMigrations
.ToDictionary(r => r.DataMigrationClass);
var outOfDateMigrations = _dataMigrations.Where(dataMigration =>
{
Records.DataMigration record;
if (currentVersions.TryGetValue(dataMigration.GetType().FullName, out record) && record.Version.HasValue)
{
return CreateUpgradeLookupTable(dataMigration).ContainsKey(record.Version.Value);
}
return (GetCreateMethod(dataMigration) != null);
});
return outOfDateMigrations.Select(m => _typeFeatureProvider.GetFeatureForDependency(m.GetType()).Id).ToList();
}
public async Task Uninstall(string feature)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Uninstalling feature: {0}.", feature);
}
var migrations = GetDataMigrations(feature);
// apply update methods to each migration class for the module
foreach (var migration in migrations)
{
// copy the object for the Linq query
var tempMigration = migration;
// get current version for this migration
var dataMigrationRecord = await GetDataMigrationRecordAsync(tempMigration);
var uninstallMethod = GetUninstallMethod(migration);
if (uninstallMethod != null)
{
uninstallMethod.Invoke(migration, new object[0]);
}
if (dataMigrationRecord == null)
{
continue;
}
(await GetDataMigrationRecordAsync()).DataMigrations.Remove(dataMigrationRecord);
}
}
public async Task UpdateAsync(IEnumerable<string> featureIds)
{
foreach (var featureId in featureIds)
{
if (!_processedFeatures.Contains(featureId))
{
await UpdateAsync(featureId);
}
}
}
public async Task UpdateAsync(string featureId)
{
if (_processedFeatures.Contains(featureId))
{
return;
}
_processedFeatures.Add(featureId);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Updating feature: {0}", featureId);
}
// proceed with dependent features first, whatever the module it's in
var dependencies = _extensionManager
.GetDependentFeatures(
featureId)
.Where(x => x.Id != featureId)
.Select(x => x.Id);
await UpdateAsync(dependencies);
var migrations = GetDataMigrations(featureId);
// apply update methods to each migration class for the module
foreach (var migration in migrations)
{
var schemaBuilder = new SchemaBuilder(_session);
migration.SchemaBuilder = schemaBuilder;
// copy the object for the Linq query
var tempMigration = migration;
// get current version for this migration
var dataMigrationRecord = GetDataMigrationRecordAsync(tempMigration).Result;
var current = 0;
if (dataMigrationRecord != null)
{
current = dataMigrationRecord.Version.Value;
}
else
{
dataMigrationRecord = new Records.DataMigration { DataMigrationClass = migration.GetType().FullName };
_dataMigrationRecord.DataMigrations.Add(dataMigrationRecord);
}
try
{
// do we need to call Create() ?
if (current == 0)
{
// try to resolve a Create method
var createMethod = GetCreateMethod(migration);
if (createMethod != null)
{
current = (int)createMethod.Invoke(migration, new object[0]);
}
}
var lookupTable = CreateUpgradeLookupTable(migration);
while (lookupTable.ContainsKey(current))
{
try
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Applying migration for {0} from version {1}.", featureId, current);
}
current = (int)lookupTable[current].Invoke(migration, new object[0]);
}
catch (Exception ex)
{
if (ex.IsFatal())
{
throw;
}
_logger.LogError(0, "An unexpected error occurred while applying migration on {0} from version {1}.", featureId, current);
throw;
}
}
// if current is 0, it means no upgrade/create method was found or succeeded
if (current == 0)
{
return;
}
dataMigrationRecord.Version = current;
}
catch (Exception ex)
{
if (ex.IsFatal())
{
throw;
}
_logger.LogError(0, "Error while running migration version {0} for {1}.", current, featureId);
_session.Cancel();
throw new Exception(T["Error while running migration version {0} for {1}.", current, featureId], ex);
}
finally
{
// Persist data migrations
_session.Save(_dataMigrationRecord);
}
}
}
private async Task<Records.DataMigration> GetDataMigrationRecordAsync(IDataMigration tempMigration)
{
var dataMigrationRecord = await GetDataMigrationRecordAsync();
return dataMigrationRecord
.DataMigrations
.FirstOrDefault(dm => dm.DataMigrationClass == tempMigration.GetType().FullName);
}
/// <summary>
/// Returns all the available IDataMigration instances for a specific module, and inject necessary builders
/// </summary>
private IEnumerable<IDataMigration> GetDataMigrations(string featureId)
{
var migrations = _dataMigrations
.Where(dm => _typeFeatureProvider.GetFeatureForDependency(dm.GetType()).Id == featureId)
.ToList();
//foreach (var migration in migrations.OfType<DataMigrationImpl>()) {
// migration.SchemaBuilder = new SchemaBuilder(_interpreter, migration.Feature.Descriptor.Extension.Id, s => s.Replace(".", "_") + "_");
// migration.ContentDefinitionManager = _contentDefinitionManager;
//}
return migrations;
}
/// <summary>
/// Create a list of all available Update methods from a data migration class, indexed by the version number
/// </summary>
private static Dictionary<int, MethodInfo> CreateUpgradeLookupTable(IDataMigration dataMigration)
{
return dataMigration
.GetType()
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Select(GetUpdateMethod)
.Where(tuple => tuple != null)
.ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2);
}
private static Tuple<int, MethodInfo> GetUpdateMethod(MethodInfo mi)
{
const string updatefromPrefix = "UpdateFrom";
if (mi.Name.StartsWith(updatefromPrefix))
{
var version = mi.Name.Substring(updatefromPrefix.Length);
int versionValue;
if (int.TryParse(version, out versionValue))
{
return new Tuple<int, MethodInfo>(versionValue, mi);
}
}
return null;
}
/// <summary>
/// Returns the Create method from a data migration class if it's found
/// </summary>
private static MethodInfo GetCreateMethod(IDataMigration dataMigration)
{
var methodInfo = dataMigration.GetType().GetMethod("Create", BindingFlags.Public | BindingFlags.Instance);
if (methodInfo != null && methodInfo.ReturnType == typeof(int))
{
return methodInfo;
}
return null;
}
/// <summary>
/// Returns the Uninstall method from a data migration class if it's found
/// </summary>
private static MethodInfo GetUninstallMethod(IDataMigration dataMigration)
{
var methodInfo = dataMigration.GetType().GetMethod("Uninstall", BindingFlags.Public | BindingFlags.Instance);
if (methodInfo != null && methodInfo.ReturnType == typeof(void))
{
return methodInfo;
}
return null;
}
public async Task UpdateAllFeaturesAsync()
{
var featuresThatNeedUpdate = await GetFeaturesThatNeedUpdateAsync();
foreach (var featureId in featuresThatNeedUpdate)
{
try
{
await UpdateAsync(featureId);
}
catch (Exception ex)
{
if (ex.IsFatal())
{
throw;
}
_logger.LogError("Could not run migrations automatically on " + featureId, ex);
}
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ASC.Blogs.Core.Data;
using ASC.Blogs.Core.Domain;
using ASC.Blogs.Core.Security;
using ASC.Blogs.Core.Service;
using ASC.Common.Caching;
using ASC.Common.Web;
using ASC.Core;
using ASC.Core.Common.Notify;
using ASC.ElasticSearch;
using ASC.Notify;
using ASC.Notify.Patterns;
using ASC.Notify.Recipients;
using ASC.Web.Community.Product;
using ASC.Web.Community.Search;
using ASC.Web.Core.Users;
using ASC.Web.Studio.Utility;
namespace ASC.Blogs.Core
{
public class BlogsEngine
{
private const string DbRegistryKey = "community";
#region fabric
public static BlogsEngine GetEngine(int tenant)
{
if (HttpContext.Current != null)
{
var bs = DisposableHttpContext.Current["blogs"] as BlogsStorage;
if (bs == null)
{
bs = GetStorage(tenant);
DisposableHttpContext.Current["blogs"] = bs;
}
return new BlogsEngine(tenant, bs);
}
return new BlogsEngine(tenant, GetStorage(tenant));
}
public static BlogsStorage GetStorage(int tenant)
{
return new BlogsStorage(DbRegistryKey, tenant);
}
#endregion
private readonly BlogsStorage _storage;
private static INotifyClient _notifyClient;
private static BlogNotifySource _notifySource;
public BlogsEngine(int tenant, BlogsStorage storage)
{
_storage = storage;
InitNotify();
}
#region database
#region posts
private List<int> SearchPostsInternal(string searchText)
{
List<int> blogs;
if (FactoryIndexer<BlogsWrapper>.TrySelectIds(r => r.MatchAll(searchText), out blogs))
{
return blogs;
}
var keyWords = new List<string>(searchText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
keyWords.RemoveAll(kw => kw.Length < 3);
var wordResults = new Dictionary<string, int>(keyWords.Count);
var counts = new Dictionary<int, int>();
var wordsCount = 0;
foreach (var word in keyWords.Where(word => !wordResults.ContainsKey(word)))
{
wordsCount++;
var wordResult = _storage.GetPostDao().SearchPostsByWord(word);
wordResults.Add(word, wordResult.Count);
wordResult.ForEach(
pid =>
{
if (counts.ContainsKey(pid))
counts[pid] = counts[pid] + 1;
else
counts.Add(pid, 1);
});
}
return (from kw in counts where kw.Value == wordsCount select kw.Key).ToList();
}
public int SearchPostsCount(string searchText)
{
if (String.IsNullOrEmpty(searchText))
throw new ArgumentNullException("searchText");
var ids = SearchPostsInternal(searchText);
var forSelectPosts = _storage.GetPostDao().GetPosts(ids, false, false);
return forSelectPosts.Count;
}
public List<Post> SearchPosts(string searchText, PagingQuery paging)
{
if (String.IsNullOrEmpty(searchText)) throw new ArgumentNullException("searchText");
var ids = SearchPostsInternal(searchText);
var forSelectPosts = _storage.GetPostDao().GetPosts(ids, false, false);
forSelectPosts.Sort((p1, p2) => DateTime.Compare(p2.Datetime, p1.Datetime));
var offset = paging.Offset.GetValueOrDefault(0);
var count = paging.Count.GetValueOrDefault(forSelectPosts.Count);
if (offset > forSelectPosts.Count) return new List<Post>();
if (count > forSelectPosts.Count - offset) count = forSelectPosts.Count - offset;
var result = _storage.GetPostDao().GetPosts(forSelectPosts.GetRange(offset, count).ConvertAll(p => p.ID), true, true);
result.Sort((p1, p2) => DateTime.Compare(p2.Datetime, p1.Datetime));
return result;
}
public int GetPostsCount(PostsQuery query)
{
if (query.SearchText != null)
return SearchPostsCount(query.SearchText);
return
_storage.GetPostDao()
.GetCount(
null,
null,
query.UserId,
query.Tag);
}
public List<Post> SelectPosts(PostsQuery query)
{
if (query.SearchText != null)
return SearchPosts(query.SearchText, new PagingQuery(query));
return
_storage.GetPostDao()
.Select(
null,
null,
query.UserId,
query.Tag,
query.WithContent,
false,
query.Offset,
query.Count,
query.WithTags,
false);
}
public List<Post> SelectPostsInfo(List<Guid> ids)
{
return _storage.GetPostDao().GetPosts(ids, false, false);
}
public Post GetPostById(Guid postId)
{
return _storage.GetPostDao().Select(postId, null, null, true, true, false).FirstOrDefault();
}
public List<Tuple<Post, int>> GetPostsCommentsCount(List<Post> posts)
{
var result = new List<Tuple<Post, int>>();
if (posts.Count == 0) return result;
var postIds = posts.ConvertAll(p => p.ID);
var counts = _storage.GetPostDao().GetCommentsCount(postIds);
result.AddRange(counts.Select((t, i) => Tuple.Create(posts[i], t)));
return result;
}
public void SavePostReview(Post post, Guid userID)
{
_storage.GetPostDao()
.SavePostReview(userID, post.ID, ASC.Core.Tenants.TenantUtil.DateTimeNow());
}
public void SavePost(Post post, bool isNew, bool notifyComments)
{
CommunitySecurity.DemandPermissions(
new PersonalBlogSecObject(CoreContext.UserManager.GetUsers(post.UserID)),
isNew ? Constants.Action_AddPost : Constants.Action_EditRemovePost);
_storage.GetPostDao().SavePost(post);
FactoryIndexer<BlogsWrapper>.IndexAsync(post);
if (isNew)
{
var initiatorInterceptor = new InitiatorInterceptor(new DirectRecipient(post.UserID.ToString(), ""));
try
{
NotifyClient.BeginSingleRecipientEvent("asc_blog");
NotifyClient.AddInterceptor(initiatorInterceptor);
var tags = new List<ITagValue>
{
new TagValue(Constants.TagPostSubject, post.Title),
new TagValue(Constants.TagPostPreview,
post.GetPreviewText(500)),
new TagValue(Constants.TagUserName,
DisplayUserSettings.GetFullUserName(post.UserID)),
new TagValue(Constants.TagUserURL,
CommonLinkUtility.GetFullAbsolutePath(
CommonLinkUtility.GetUserProfile(post.UserID))),
new TagValue(Constants.TagDate,
string.Format("{0:d} {0:t}", post.Datetime)),
new TagValue(Constants.TagURL,
CommonLinkUtility.GetFullAbsolutePath(
Constants.ViewBlogPageUrl +
"?blogid=" + post.ID.ToString())),
GetReplyToTag(Guid.Empty, post)
};
NotifyClient.SendNoticeAsync(
Constants.NewPost,
null,
null,
tags.ToArray());
NotifyClient.SendNoticeAsync(
Constants.NewPostByAuthor,
post.UserID.ToString(),
null,
tags.ToArray());
NotifyClient.EndSingleRecipientEvent("asc_blog");
}
finally
{
NotifyClient.RemoveInterceptor(initiatorInterceptor.Name);
}
}
if (!notifyComments) return;
var subscriptionProvider = NotifySource.GetSubscriptionProvider();
subscriptionProvider.Subscribe(
Constants.NewComment,
post.ID.ToString(),
NotifySource.GetRecipientsProvider().
GetRecipient(post.UserID.ToString())
);
}
public void DeletePost(Post post)
{
CommunitySecurity.CheckPermissions(post, Constants.Action_EditRemovePost);
_storage.GetPostDao().DeletePost(post.ID);
NotifySource.GetSubscriptionProvider().UnSubscribe(
Constants.NewComment,
post.ID.ToString()
);
FactoryIndexer<BlogsWrapper>.DeleteAsync(post);
AscCache.Default.Remove("communityScreen" + TenantProvider.CurrentTenantID);
}
#endregion
#region misc
public List<TagStat> GetTopTagsList(int count)
{
return _storage.GetPostDao().GetTagStat(count);
}
public List<string> GetTags(string like, int limit)
{
return _storage.GetPostDao().GetTags(like, limit);
}
#endregion
#region comments
public List<Comment> GetPostComments(Guid postId)
{
return _storage.GetPostDao().GetComments(postId);
}
public Comment GetCommentById(Guid commentId)
{
return _storage.GetPostDao().GetCommentById(commentId);
}
public void SaveComment(Comment comment, Post post)
{
CommunitySecurity.DemandPermissions(post, Constants.Action_AddComment);
SaveComment(comment);
var initiatorInterceptor = new InitiatorInterceptor(new DirectRecipient(comment.UserID.ToString(), ""));
try
{
NotifyClient.BeginSingleRecipientEvent("asc_blog_c");
NotifyClient.AddInterceptor(initiatorInterceptor);
var tags = new List<ITagValue>
{
new TagValue(Constants.TagPostSubject, post.Title),
new TagValue(Constants.TagPostPreview, post.GetPreviewText(500)),
new TagValue(Constants.TagUserName, DisplayUserSettings.GetFullUserName(comment.UserID)),
new TagValue(Constants.TagUserURL, CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetUserProfile(comment.UserID))),
new TagValue(Constants.TagDate, string.Format("{0:d} {0:t}", comment.Datetime)),
new TagValue(Constants.TagCommentBody, comment.Content),
new TagValue(Constants.TagURL, CommonLinkUtility.GetFullAbsolutePath(Constants.ViewBlogPageUrl + "?blogid=" + post.ID.ToString())),
new TagValue(Constants.TagCommentURL, CommonLinkUtility.GetFullAbsolutePath(Constants.ViewBlogPageUrl + "?blogid=" + post.ID.ToString() + "#container_" + comment.ID.ToString())),
GetReplyToTag(comment.ID, post)
};
NotifyClient.SendNoticeAsync(
Constants.NewComment,
post.ID.ToString(),
null,
tags.ToArray());
NotifyClient.EndSingleRecipientEvent("asc_blog_c");
}
finally
{
NotifyClient.RemoveInterceptor(initiatorInterceptor.Name);
}
var subscriptionProvider = NotifySource.GetSubscriptionProvider();
if (!subscriptionProvider.IsUnsubscribe((IDirectRecipient)NotifySource.GetRecipientsProvider().
GetRecipient(SecurityContext.CurrentAccount.ID.ToString()), Constants.NewComment, post.ID.ToString()))
{
subscriptionProvider.Subscribe(
Constants.NewComment,
post.ID.ToString(),
NotifySource.GetRecipientsProvider().
GetRecipient(SecurityContext.CurrentAccount.ID.ToString())
);
}
}
private static TagValue GetReplyToTag(Guid commentId, Post post)
{
return ReplyToTagProvider.Comment("blog", post.ID.ToString(), commentId.ToString());
}
private void SaveComment(Comment comment)
{
CommunitySecurity.DemandPermissions(comment, Constants.Action_EditRemoveComment);
if (String.IsNullOrEmpty(comment.Content))
throw new ArgumentException("comment");
if (comment.PostId == Guid.Empty)
throw new ArgumentException("comment");
_storage.GetPostDao().SaveComment(comment);
}
#endregion
#endregion
#region notify
private void InitNotify()
{
if (_notifySource == null)
_notifySource = new BlogNotifySource();
if (_notifyClient == null)
_notifyClient = WorkContext.NotifyContext.NotifyService.RegisterClient(_notifySource);
}
public BlogNotifySource NotifySource
{
get { return _notifySource; }
}
public INotifyClient NotifyClient
{
get { return _notifyClient; }
}
#endregion
public void UpdateComment(Comment comment, Post post)
{
SaveComment(comment);
}
public void RemoveComment(Comment comment, Post post)
{
SaveComment(comment);
}
}
public class PostsQuery : PagingQuery<PostsQuery>
{
internal bool WithTags = true;
internal bool WithContent = true;
internal string Tag;
internal Guid? UserId;
internal string SearchText;
public PostsQuery NoTags()
{
WithTags = false;
return this;
}
public PostsQuery NoContent()
{
WithContent = false;
return this;
}
public PostsQuery SetTag(string tag)
{
if (String.IsNullOrEmpty(tag))
throw new ArgumentException("tag");
Tag = tag;
return this;
}
public PostsQuery SetUser(Guid userId)
{
UserId = userId;
return this;
}
public PostsQuery SetSearch(string searchText)
{
SearchText = searchText;
return this;
}
}
public class PagingQuery : PagingQuery<PagingQuery>
{
public PagingQuery()
{
}
public PagingQuery(PostsQuery q)
{
Count = q.Count;
Offset = q.Offset;
}
}
public class PagingQuery<T> where T : class
{
internal int? Count;
internal int? Offset;
public T SetCount(int count)
{
Count = count;
return this as T;
}
public T SetOffset(int offset)
{
Offset = offset;
return this as T;
}
}
}
| |
#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.IO;
#if HAVE_ASYNC
using System.Threading;
using System.Threading.Tasks;
#endif
using System.Collections.Generic;
using System.Diagnostics;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Utilities
{
internal static class BufferUtils
{
public static char[] RentBuffer(IArrayPool<char> bufferPool, int minSize)
{
if (bufferPool == null)
{
return new char[minSize];
}
char[] buffer = bufferPool.Rent(minSize);
return buffer;
}
public static void ReturnBuffer(IArrayPool<char> bufferPool, char[] buffer)
{
bufferPool?.Return(buffer);
}
public static char[] EnsureBufferSize(IArrayPool<char> bufferPool, int size, char[] buffer)
{
if (bufferPool == null)
{
return new char[size];
}
if (buffer != null)
{
bufferPool.Return(buffer);
}
return bufferPool.Rent(size);
}
}
internal static class JavaScriptUtils
{
internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128];
internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128];
internal static readonly bool[] HtmlCharEscapeFlags = new bool[128];
private const int UnicodeTextLength = 6;
static JavaScriptUtils()
{
IList<char> escapeChars = new List<char>
{
'\n', '\r', '\t', '\\', '\f', '\b',
};
for (int i = 0; i < ' '; i++)
{
escapeChars.Add((char)i);
}
foreach (char escapeChar in escapeChars.Union(new[] { '\'' }))
{
SingleQuoteCharEscapeFlags[escapeChar] = true;
}
foreach (char escapeChar in escapeChars.Union(new[] { '"' }))
{
DoubleQuoteCharEscapeFlags[escapeChar] = true;
}
foreach (char escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' }))
{
HtmlCharEscapeFlags[escapeChar] = true;
}
}
private const string EscapedUnicodeText = "!";
public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar)
{
if (stringEscapeHandling == StringEscapeHandling.EscapeHtml)
{
return HtmlCharEscapeFlags;
}
if (quoteChar == '"')
{
return DoubleQuoteCharEscapeFlags;
}
return SingleQuoteCharEscapeFlags;
}
public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags)
{
if (s == null)
{
return false;
}
foreach (char c in s)
{
if (c >= charEscapeFlags.Length || charEscapeFlags[c])
{
return true;
}
}
return false;
}
public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters,
bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool<char> bufferPool, ref char[] writeBuffer)
{
// leading delimiter
if (appendDelimiters)
{
writer.Write(delimiter);
}
if (!string.IsNullOrEmpty(s))
{
int lastWritePosition = FirstCharToEscape(s, charEscapeFlags, stringEscapeHandling);
if (lastWritePosition == -1)
{
writer.Write(s);
}
else
{
if (lastWritePosition != 0)
{
if (writeBuffer == null || writeBuffer.Length < lastWritePosition)
{
writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, lastWritePosition, writeBuffer);
}
// write unchanged chars at start of text.
s.CopyTo(0, writeBuffer, 0, lastWritePosition);
writer.Write(writeBuffer, 0, lastWritePosition);
}
int length;
for (int i = lastWritePosition; i < s.Length; i++)
{
char c = s[i];
if (c < charEscapeFlags.Length && !charEscapeFlags[c])
{
continue;
}
string escapedValue;
switch (c)
{
case '\t':
escapedValue = @"\t";
break;
case '\n':
escapedValue = @"\n";
break;
case '\r':
escapedValue = @"\r";
break;
case '\f':
escapedValue = @"\f";
break;
case '\b':
escapedValue = @"\b";
break;
case '\\':
escapedValue = @"\\";
break;
case '\u0085': // Next Line
escapedValue = @"\u0085";
break;
case '\u2028': // Line Separator
escapedValue = @"\u2028";
break;
case '\u2029': // Paragraph Separator
escapedValue = @"\u2029";
break;
default:
if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii)
{
if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
{
escapedValue = @"\'";
}
else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
{
escapedValue = @"\""";
}
else
{
if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength)
{
writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer);
}
StringUtils.ToCharAsUnicode(c, writeBuffer);
// slightly hacky but it saves multiple conditions in if test
escapedValue = EscapedUnicodeText;
}
}
else
{
escapedValue = null;
}
break;
}
if (escapedValue == null)
{
continue;
}
bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText, StringComparison.Ordinal);
if (i > lastWritePosition)
{
length = i - lastWritePosition + ((isEscapedUnicodeText) ? UnicodeTextLength : 0);
int start = (isEscapedUnicodeText) ? UnicodeTextLength : 0;
if (writeBuffer == null || writeBuffer.Length < length)
{
char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length);
// the unicode text is already in the buffer
// copy it over when creating new buffer
if (isEscapedUnicodeText)
{
Debug.Assert(writeBuffer != null, "Write buffer should never be null because it is set when the escaped unicode text is encountered.");
Array.Copy(writeBuffer, newBuffer, UnicodeTextLength);
}
BufferUtils.ReturnBuffer(bufferPool, writeBuffer);
writeBuffer = newBuffer;
}
s.CopyTo(lastWritePosition, writeBuffer, start, length - start);
// write unchanged chars before writing escaped text
writer.Write(writeBuffer, start, length - start);
}
lastWritePosition = i + 1;
if (!isEscapedUnicodeText)
{
writer.Write(escapedValue);
}
else
{
writer.Write(writeBuffer, 0, UnicodeTextLength);
}
}
Debug.Assert(lastWritePosition != 0);
length = s.Length - lastWritePosition;
if (length > 0)
{
if (writeBuffer == null || writeBuffer.Length < length)
{
writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, length, writeBuffer);
}
s.CopyTo(lastWritePosition, writeBuffer, 0, length);
// write remaining text
writer.Write(writeBuffer, 0, length);
}
}
}
// trailing delimiter
if (appendDelimiters)
{
writer.Write(delimiter);
}
}
public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling)
{
bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter);
using (StringWriter w = StringUtils.CreateStringWriter(value?.Length ?? 16))
{
char[] buffer = null;
WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer);
return w.ToString();
}
}
private static int FirstCharToEscape(string s, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling)
{
for (int i = 0; i != s.Length; i++)
{
char c = s[i];
if (c < charEscapeFlags.Length)
{
if (charEscapeFlags[c])
{
return i;
}
}
else if (stringEscapeHandling == StringEscapeHandling.EscapeNonAscii)
{
return i;
}
else
{
switch (c)
{
case '\u0085':
case '\u2028':
case '\u2029':
return i;
}
}
}
return -1;
}
#if HAVE_ASYNC
public static Task WriteEscapedJavaScriptStringAsync(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return cancellationToken.FromCanceled();
}
if (appendDelimiters)
{
return WriteEscapedJavaScriptStringWithDelimitersAsync(writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken);
}
if (string.IsNullOrEmpty(s))
{
return cancellationToken.CancelIfRequestedAsync() ?? AsyncUtils.CompletedTask;
}
return WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken);
}
private static Task WriteEscapedJavaScriptStringWithDelimitersAsync(TextWriter writer, string s, char delimiter,
bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken)
{
Task task = writer.WriteAsync(delimiter, cancellationToken);
if (!task.IsCompletedSucessfully())
{
return WriteEscapedJavaScriptStringWithDelimitersAsync(task, writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken);
}
if (!string.IsNullOrEmpty(s))
{
task = WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken);
if (task.IsCompletedSucessfully())
{
return writer.WriteAsync(delimiter, cancellationToken);
}
}
return WriteCharAsync(task, writer, delimiter, cancellationToken);
}
private static async Task WriteEscapedJavaScriptStringWithDelimitersAsync(Task task, TextWriter writer, string s, char delimiter,
bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken)
{
await task.ConfigureAwait(false);
if (!string.IsNullOrEmpty(s))
{
await WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken).ConfigureAwait(false);
}
await writer.WriteAsync(delimiter).ConfigureAwait(false);
}
public static async Task WriteCharAsync(Task task, TextWriter writer, char c, CancellationToken cancellationToken)
{
await task.ConfigureAwait(false);
await writer.WriteAsync(c, cancellationToken).ConfigureAwait(false);
}
private static Task WriteEscapedJavaScriptStringWithoutDelimitersAsync(
TextWriter writer, string s, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling,
JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken)
{
int i = FirstCharToEscape(s, charEscapeFlags, stringEscapeHandling);
return i == -1
? writer.WriteAsync(s, cancellationToken)
: WriteDefinitelyEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, i, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken);
}
private static async Task WriteDefinitelyEscapedJavaScriptStringWithoutDelimitersAsync(
TextWriter writer, string s, int lastWritePosition, bool[] charEscapeFlags,
StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer,
CancellationToken cancellationToken)
{
if (writeBuffer == null || writeBuffer.Length < lastWritePosition)
{
writeBuffer = client.EnsureWriteBuffer(lastWritePosition, UnicodeTextLength);
}
if (lastWritePosition != 0)
{
s.CopyTo(0, writeBuffer, 0, lastWritePosition);
// write unchanged chars at start of text.
await writer.WriteAsync(writeBuffer, 0, lastWritePosition, cancellationToken).ConfigureAwait(false);
}
int length;
bool isEscapedUnicodeText = false;
string escapedValue = null;
for (int i = lastWritePosition; i < s.Length; i++)
{
char c = s[i];
if (c < charEscapeFlags.Length && !charEscapeFlags[c])
{
continue;
}
switch (c)
{
case '\t':
escapedValue = @"\t";
break;
case '\n':
escapedValue = @"\n";
break;
case '\r':
escapedValue = @"\r";
break;
case '\f':
escapedValue = @"\f";
break;
case '\b':
escapedValue = @"\b";
break;
case '\\':
escapedValue = @"\\";
break;
case '\u0085': // Next Line
escapedValue = @"\u0085";
break;
case '\u2028': // Line Separator
escapedValue = @"\u2028";
break;
case '\u2029': // Paragraph Separator
escapedValue = @"\u2029";
break;
default:
if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii)
{
if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
{
escapedValue = @"\'";
}
else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
{
escapedValue = @"\""";
}
else
{
if (writeBuffer.Length < UnicodeTextLength)
{
writeBuffer = client.EnsureWriteBuffer(UnicodeTextLength, 0);
}
StringUtils.ToCharAsUnicode(c, writeBuffer);
isEscapedUnicodeText = true;
}
}
else
{
continue;
}
break;
}
if (i > lastWritePosition)
{
length = i - lastWritePosition + (isEscapedUnicodeText ? UnicodeTextLength : 0);
int start = isEscapedUnicodeText ? UnicodeTextLength : 0;
if (writeBuffer.Length < length)
{
writeBuffer = client.EnsureWriteBuffer(length, UnicodeTextLength);
}
s.CopyTo(lastWritePosition, writeBuffer, start, length - start);
// write unchanged chars before writing escaped text
await writer.WriteAsync(writeBuffer, start, length - start, cancellationToken).ConfigureAwait(false);
}
lastWritePosition = i + 1;
if (!isEscapedUnicodeText)
{
await writer.WriteAsync(escapedValue, cancellationToken).ConfigureAwait(false);
}
else
{
await writer.WriteAsync(writeBuffer, 0, UnicodeTextLength, cancellationToken).ConfigureAwait(false);
isEscapedUnicodeText = false;
}
}
length = s.Length - lastWritePosition;
if (length != 0)
{
if (writeBuffer.Length < length)
{
writeBuffer = client.EnsureWriteBuffer(length, 0);
}
s.CopyTo(lastWritePosition, writeBuffer, 0, length);
// write remaining text
await writer.WriteAsync(writeBuffer, 0, length, cancellationToken).ConfigureAwait(false);
}
}
#endif
public static bool TryGetDateFromConstructorJson(JsonReader reader, out DateTime dateTime, out string errorMessage)
{
dateTime = default;
errorMessage = null;
if (!TryGetDateConstructorValue(reader, out long? t1, out errorMessage) || t1 == null)
{
errorMessage = errorMessage ?? "Date constructor has no arguments.";
return false;
}
if (!TryGetDateConstructorValue(reader, out long? t2, out errorMessage))
{
return false;
}
else if (t2 != null)
{
// Only create a list when there is more than one argument
List<long> dateArgs = new List<long>
{
t1.Value,
t2.Value
};
while (true)
{
if (!TryGetDateConstructorValue(reader, out long? integer, out errorMessage))
{
return false;
}
else if (integer != null)
{
dateArgs.Add(integer.Value);
}
else
{
break;
}
}
if (dateArgs.Count > 7)
{
errorMessage = "Unexpected number of arguments when reading date constructor.";
return false;
}
// Pad args out to the number used by the ctor
while (dateArgs.Count < 7)
{
dateArgs.Add(0);
}
dateTime = new DateTime((int)dateArgs[0], (int)dateArgs[1] + 1, dateArgs[2] == 0 ? 1 : (int)dateArgs[2],
(int)dateArgs[3], (int)dateArgs[4], (int)dateArgs[5], (int)dateArgs[6]);
}
else
{
dateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(t1.Value);
}
return true;
}
private static bool TryGetDateConstructorValue(JsonReader reader, out long? integer, out string errorMessage)
{
integer = null;
errorMessage = null;
if (!reader.Read())
{
errorMessage = "Unexpected end when reading date constructor.";
return false;
}
if (reader.TokenType == JsonToken.EndConstructor)
{
return true;
}
if (reader.TokenType != JsonToken.Integer)
{
errorMessage = "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType;
return false;
}
integer = (long)reader.Value;
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Models;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.cache;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.web;
using umbraco.cms.helpers;
using umbraco.DataLayer;
using umbraco.interfaces;
using DataTypeDefinition = umbraco.cms.businesslogic.datatype.DataTypeDefinition;
using Language = umbraco.cms.businesslogic.language.Language;
namespace umbraco.cms.businesslogic.propertytype
{
/// <summary>
/// Summary description for propertytype.
/// </summary>
[Obsolete("Use the ContentTypeService instead")]
public class PropertyType
{
#region Declarations
private readonly int _contenttypeid;
private readonly int _id;
private int _DataTypeId;
private string _alias;
private string _description = "";
private bool _mandatory;
private string _name;
private int _sortOrder;
private int _tabId;
private int _propertyTypeGroup;
private string _validationRegExp = "";
#endregion
/// <summary>
/// Unused, please do not use
/// </summary>
[Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)]
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
#region Constructors
public PropertyType(int id)
{
using (var sqlHelper = Application.SqlHelper)
using (IRecordsReader dr = sqlHelper.ExecuteReader(
"Select mandatory, DataTypeId, propertyTypeGroupId, ContentTypeId, sortOrder, alias, name, validationRegExp, description from cmsPropertyType where id=@id",
sqlHelper.CreateParameter("@id", id)))
{
if (!dr.Read())
throw new ArgumentException("Propertytype with id: " + id + " doesnt exist!");
_mandatory = dr.GetBoolean("mandatory");
_id = id;
if (!dr.IsNull("propertyTypeGroupId"))
{
_propertyTypeGroup = dr.GetInt("propertyTypeGroupId");
//TODO: Remove after refactoring!
_tabId = _propertyTypeGroup;
}
_sortOrder = dr.GetInt("sortOrder");
_alias = dr.GetString("alias");
_name = dr.GetString("Name");
_validationRegExp = dr.GetString("validationRegExp");
_DataTypeId = dr.GetInt("DataTypeId");
_contenttypeid = dr.GetInt("contentTypeId");
_description = dr.GetString("description");
}
}
#endregion
#region Properties
public DataTypeDefinition DataTypeDefinition
{
get { return DataTypeDefinition.GetDataTypeDefinition(_DataTypeId); }
set
{
_DataTypeId = value.Id;
InvalidateCache();
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set DataTypeId = " + value.Id + " where id=" + Id);
}
}
public int Id
{
get { return _id; }
}
/// <summary>
/// Setting the tab id is not meant to be used directly in code. Use the ContentType SetTabOnPropertyType method instead
/// as that will handle all of the caching properly, this will not.
/// </summary>
/// <remarks>
/// Setting the tab id to a negative value will actually set the value to NULL in the database
/// </remarks>
[Obsolete("Use the new PropertyTypeGroup parameter", false)]
public int TabId
{
get { return _tabId; }
set
{
_tabId = value;
PropertyTypeGroup = value;
InvalidateCache();
}
}
public int PropertyTypeGroup
{
get { return _propertyTypeGroup; }
set
{
_propertyTypeGroup = value;
object dbPropertyTypeGroup = value;
if (value < 1)
{
dbPropertyTypeGroup = DBNull.Value;
}
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery("Update cmsPropertyType set propertyTypeGroupId = @propertyTypeGroupId where id = @id",
sqlHelper.CreateParameter("@propertyTypeGroupId", dbPropertyTypeGroup),
sqlHelper.CreateParameter("@id", Id));
}
}
public bool Mandatory
{
get { return _mandatory; }
set
{
_mandatory = value;
InvalidateCache();
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery("Update cmsPropertyType set mandatory = @mandatory where id = @id",
sqlHelper.CreateParameter("@mandatory", value),
sqlHelper.CreateParameter("@id", Id));
}
}
public string ValidationRegExp
{
get { return _validationRegExp; }
set
{
_validationRegExp = value;
InvalidateCache();
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery("Update cmsPropertyType set validationRegExp = @validationRegExp where id = @id",
sqlHelper.CreateParameter("@validationRegExp", value), sqlHelper.CreateParameter("@id", Id));
}
}
public string Description
{
get
{
if (_description != null)
{
if (!_description.StartsWith("#"))
return _description;
else
{
Language lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name);
if (lang != null)
{
if (Dictionary.DictionaryItem.hasKey(_description.Substring(1, _description.Length - 1)))
{
var di =
new Dictionary.DictionaryItem(_description.Substring(1, _description.Length - 1));
return di.Value(lang.id);
}
}
}
return "[" + _description + "]";
}
return _description;
}
set
{
_description = value;
InvalidateCache();
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery("Update cmsPropertyType set description = @description where id = @id",
sqlHelper.CreateParameter("@description", value),
sqlHelper.CreateParameter("@id", Id));
}
}
public int SortOrder
{
get { return _sortOrder; }
set
{
_sortOrder = value;
InvalidateCache();
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery("Update cmsPropertyType set sortOrder = @sortOrder where id = @id",
sqlHelper.CreateParameter("@sortOrder", value),
sqlHelper.CreateParameter("@id", Id));
}
}
public string Alias
{
get { return _alias; }
set
{
_alias = value;
InvalidateCache();
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery("Update cmsPropertyType set alias = @alias where id= @id",
sqlHelper.CreateParameter("@alias", Casing.SafeAliasWithForcingCheck(_alias)),
sqlHelper.CreateParameter("@id", Id));
}
}
public int ContentTypeId
{
get { return _contenttypeid; }
}
public string Name
{
get
{
if (!_name.StartsWith("#"))
return _name;
else
{
Language lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name);
if (lang != null)
{
if (Dictionary.DictionaryItem.hasKey(_name.Substring(1, _name.Length - 1)))
{
var di = new Dictionary.DictionaryItem(_name.Substring(1, _name.Length - 1));
return di.Value(lang.id);
}
}
return "[" + _name + "]";
}
}
set
{
_name = value;
InvalidateCache();
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery(
"UPDATE cmsPropertyType SET name=@name WHERE id=@id",
sqlHelper.CreateParameter("@name", _name),
sqlHelper.CreateParameter("@id", Id));
}
}
#endregion
#region Methods
public string GetRawName()
{
return _name;
}
public string GetRawDescription()
{
return _description;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static PropertyType MakeNew(DataTypeDefinition dt, ContentType ct, string name, string alias)
{
//make sure that the alias starts with a letter
if (string.IsNullOrEmpty(alias))
throw new ArgumentNullException("alias");
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (!Char.IsLetter(alias[0]))
throw new ArgumentException("alias must start with a letter", "alias");
PropertyType pt;
try
{
// The method is synchronized, but we'll still look it up with an additional parameter (alias)
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery(
"INSERT INTO cmsPropertyType (DataTypeId, ContentTypeId, alias, name) VALUES (@DataTypeId, @ContentTypeId, @alias, @name)",
sqlHelper.CreateParameter("@DataTypeId", dt.Id),
sqlHelper.CreateParameter("@ContentTypeId", ct.Id),
sqlHelper.CreateParameter("@alias", alias),
sqlHelper.CreateParameter("@name", name));
using (var sqlHelper = Application.SqlHelper)
pt = new PropertyType(sqlHelper.ExecuteScalar<int>("SELECT MAX(id) FROM cmsPropertyType WHERE alias=@alias",
sqlHelper.CreateParameter("@alias", alias)));
}
finally
{
// Clear cached items
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(CacheKeys.PropertyTypeCacheKey);
}
return pt;
}
public static PropertyType[] GetAll()
{
var result = GetPropertyTypes();
return result.ToArray();
}
public static IEnumerable<PropertyType> GetPropertyTypes()
{
var result = new List<PropertyType>();
using (var sqlHelper = Application.SqlHelper)
using (IRecordsReader dr =
sqlHelper.ExecuteReader("select id from cmsPropertyType order by Name"))
{
while (dr.Read())
{
PropertyType pt = GetPropertyType(dr.GetInt("id"));
if (pt != null)
result.Add(pt);
}
}
return result;
}
public static IEnumerable<PropertyType> GetPropertyTypesByGroup(int groupId, List<int> contentTypeIds)
{
return GetPropertyTypesByGroup(groupId).Where(x => contentTypeIds.Contains(x.ContentTypeId));
}
public static IEnumerable<PropertyType> GetPropertyTypesByGroup(int groupId)
{
var result = new List<PropertyType>();
using (var sqlHelper = Application.SqlHelper)
using (IRecordsReader dr =
sqlHelper.ExecuteReader("SELECT id FROM cmsPropertyType WHERE propertyTypeGroupId = @groupId order by SortOrder",
sqlHelper.CreateParameter("@groupId", groupId)))
{
while (dr.Read())
{
PropertyType pt = GetPropertyType(dr.GetInt("id"));
if (pt != null)
result.Add(pt);
}
}
return result;
}
/// <summary>
/// Returns all property types based on the data type definition
/// </summary>
/// <param name="dataTypeDefId"></param>
/// <returns></returns>
public static IEnumerable<PropertyType> GetByDataTypeDefinition(int dataTypeDefId)
{
var result = new List<PropertyType>();
using (var sqlHelper = Application.SqlHelper)
using (IRecordsReader dr =
sqlHelper.ExecuteReader(
"select id, Name from cmsPropertyType where dataTypeId=@dataTypeId order by Name",
sqlHelper.CreateParameter("@dataTypeId", dataTypeDefId)))
{
while (dr.Read())
{
PropertyType pt = GetPropertyType(dr.GetInt("id"));
if (pt != null)
result.Add(pt);
}
}
return result.ToList();
}
public void delete()
{
// flush cache
FlushCache();
// Delete all properties of propertytype
CleanPropertiesOnDeletion(_contenttypeid);
//delete tag refs
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery("Delete from cmsTagRelationship where propertyTypeId = " + Id);
// Delete PropertyType ..
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery("Delete from cmsPropertyType where id = " + Id);
// delete cache from either master (via tabid) or current contentype
FlushCacheBasedOnTab();
InvalidateCache();
}
public void FlushCacheBasedOnTab()
{
if (TabId != 0)
{
ContentType.FlushFromCache(ContentType.Tab.GetTab(TabId).ContentType);
}
else
{
ContentType.FlushFromCache(ContentTypeId);
}
}
private void CleanPropertiesOnDeletion(int contentTypeId)
{
// first delete from all master document types
//TODO: Verify no endless loops with mixins
DocumentType.GetAllAsList().FindAll(dt => dt.MasterContentTypes.Contains(contentTypeId)).ForEach(
dt => CleanPropertiesOnDeletion(dt.Id));
//Initially Content.getContentOfContentType() was called, but because this doesn't include members we resort to sql lookups and deletes
var tmp = new List<int>();
using (var sqlHelper = Application.SqlHelper)
using (IRecordsReader dr = sqlHelper.ExecuteReader("SELECT nodeId FROM cmsContent INNER JOIN umbracoNode ON cmsContent.nodeId = umbracoNode.id WHERE ContentType = @contentTypeId ORDER BY umbracoNode.text", sqlHelper.CreateParameter("contentTypeId", contentTypeId)))
{
while (dr.Read()) tmp.Add(dr.GetInt("nodeId"));
foreach (var contentId in tmp)
{
sqlHelper.ExecuteNonQuery("DELETE FROM cmsPropertyData WHERE PropertyTypeId =" + this.Id + " AND contentNodeId = " + contentId);
}
// invalidate content type cache
ContentType.FlushFromCache(contentTypeId);
}
}
public IDataType GetEditControl(object value, bool isPostBack)
{
IDataType dt = DataTypeDefinition.DataType;
dt.DataEditor.Editor.ID = Alias;
IData df = DataTypeDefinition.DataType.Data;
(dt.DataEditor.Editor).ID = Alias;
if (!isPostBack)
{
if (value != null)
dt.Data.Value = value;
else
dt.Data.Value = "";
}
return dt;
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public virtual void Save()
{
FlushCache();
}
protected virtual void FlushCache()
{
// clear local cache
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(GetCacheKey(Id));
// clear cache in contentype
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(CacheKeys.ContentTypePropertiesCacheKey + _contenttypeid);
//Ensure that DocumentTypes are reloaded from db by clearing cache - this similar to the Save method on DocumentType.
//NOTE Would be nice if we could clear cache by type instead of emptying the entire cache.
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IContent>();
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IContentType>();
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IMedia>();
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IMediaType>();
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IMember>();
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IMemberType>();
}
public static PropertyType GetPropertyType(int id)
{
return ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem<PropertyType>(
GetCacheKey(id),
timeout: TimeSpan.FromMinutes(30),
getCacheItem: () =>
{
try
{
return new PropertyType(id);
}
catch
{
return null;
}
});
}
private void InvalidateCache()
{
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(GetCacheKey(Id));
}
private static string GetCacheKey(int id)
{
return CacheKeys.PropertyTypeCacheKey + id;
}
#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.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Security;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace HttpStress
{
public class StressClient : IDisposable
{
private const string UNENCRYPTED_HTTP2_ENV_VAR = "DOTNET_SYSTEM_NET_HTTP_SOCKETSHTTPHANDLER_HTTP2UNENCRYPTEDSUPPORT";
private readonly (string name, Func<RequestContext, Task> operation)[] _clientOperations;
private readonly Configuration _config;
private readonly StressResultAggregator _aggregator;
private readonly Stopwatch _stopwatch = new Stopwatch();
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
private Task? _clientTask;
public long TotalErrorCount => _aggregator.TotalErrorCount;
public StressClient((string name, Func<RequestContext, Task> operation)[] clientOperations, Configuration configuration)
{
_clientOperations = clientOperations;
_config = configuration;
_aggregator = new StressResultAggregator(clientOperations);
}
public void Start()
{
lock (_cts)
{
if (_cts.IsCancellationRequested)
{
throw new ObjectDisposedException(nameof(StressClient));
}
if (_clientTask != null)
{
throw new InvalidOperationException("Stress client already running");
}
_stopwatch.Start();
_clientTask = StartCore();
}
}
public void Stop()
{
_cts.Cancel();
_clientTask?.Wait();
_stopwatch.Stop();
_cts.Dispose();
}
public void PrintFinalReport()
{
lock(Console.Out)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("HttpStress Run Final Report");
Console.WriteLine();
_aggregator.PrintCurrentResults(_stopwatch.Elapsed);
_aggregator.PrintLatencies();
_aggregator.PrintFailureTypes();
}
}
public void Dispose() => Stop();
private async Task StartCore()
{
if (_config.ServerUri.Scheme == "http")
{
Environment.SetEnvironmentVariable(UNENCRYPTED_HTTP2_ENV_VAR, "1");
}
HttpMessageHandler CreateHttpHandler()
{
if (_config.UseWinHttpHandler)
{
return new System.Net.Http.WinHttpHandler()
{
ServerCertificateValidationCallback = delegate { return true; }
};
}
else
{
return new SocketsHttpHandler()
{
PooledConnectionLifetime = _config.ConnectionLifetime.GetValueOrDefault(Timeout.InfiniteTimeSpan),
SslOptions = new SslClientAuthenticationOptions
{
RemoteCertificateValidationCallback = delegate { return true; }
}
};
}
}
using var client = new HttpClient(CreateHttpHandler()) { BaseAddress = _config.ServerUri, Timeout = _config.DefaultTimeout };
async Task RunWorker(int taskNum)
{
// create random instance specific to the current worker
var random = new Random(Combine(taskNum, _config.RandomSeed));
var stopwatch = new Stopwatch();
for (long i = taskNum; ; i++)
{
if (_cts.IsCancellationRequested)
break;
int opIndex = (int)(i % _clientOperations.Length);
(string operation, Func<RequestContext, Task> func) = _clientOperations[opIndex];
var requestContext = new RequestContext(_config, client, random, _cts.Token, taskNum);
stopwatch.Restart();
try
{
await func(requestContext);
_aggregator.RecordSuccess(opIndex, stopwatch.Elapsed);
}
catch (OperationCanceledException) when (requestContext.IsCancellationRequested || _cts.IsCancellationRequested)
{
_aggregator.RecordCancellation(opIndex, stopwatch.Elapsed);
}
catch (Exception e)
{
_aggregator.RecordFailure(e, opIndex, stopwatch.Elapsed, taskNum: taskNum, iteration: i);
}
}
// deterministic hashing copied from System.Runtime.Hashing
int Combine(int h1, int h2)
{
uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
return ((int)rol5 + h1) ^ h2;
}
}
// Spin up a thread dedicated to outputting stats for each defined interval
new Thread(() =>
{
while (!_cts.IsCancellationRequested)
{
Thread.Sleep(_config.DisplayInterval);
lock (Console.Out) { _aggregator.PrintCurrentResults(_stopwatch.Elapsed); }
}
})
{ IsBackground = true }.Start();
// Start N workers, each of which sits in a loop making requests.
Task[] tasks = Enumerable.Range(0, _config.ConcurrentRequests).Select(RunWorker).ToArray();
await Task.WhenAll(tasks);
}
/// <summary>Aggregate view of a particular stress failure type</summary>
private sealed class StressFailureType
{
// Representative error text of stress failure
public string ErrorText { get; }
// Operation id => failure timestamps
public Dictionary<int, List<DateTime>> Failures { get; }
public StressFailureType(string errorText)
{
ErrorText = errorText;
Failures = new Dictionary<int, List<DateTime>>();
}
public int FailureCount => Failures.Values.Select(x => x.Count).Sum();
}
private sealed class StressResultAggregator
{
private readonly string[] _operationNames;
private long _totalRequests = 0;
private readonly long[] _successes, _cancellations, _failures;
private long _reuseAddressFailures = 0;
private long _lastTotal = -1;
private readonly ConcurrentDictionary<(Type exception, string message, string callSite)[], StressFailureType> _failureTypes;
private readonly ConcurrentBag<double> _latencies = new ConcurrentBag<double>();
public long TotalErrorCount => _failures.Sum();
public StressResultAggregator((string name, Func<RequestContext, Task>)[] operations)
{
_operationNames = operations.Select(x => x.name).ToArray();
_successes = new long[operations.Length];
_cancellations = new long[operations.Length];
_failures = new long[operations.Length];
_failureTypes = new ConcurrentDictionary<(Type, string, string)[], StressFailureType>(new StructuralEqualityComparer<(Type, string, string)[]>());
}
public void RecordSuccess(int operationIndex, TimeSpan elapsed)
{
Interlocked.Increment(ref _totalRequests);
Interlocked.Increment(ref _successes[operationIndex]);
_latencies.Add(elapsed.TotalMilliseconds);
}
public void RecordCancellation(int operationIndex, TimeSpan elapsed)
{
Interlocked.Increment(ref _totalRequests);
Interlocked.Increment(ref _cancellations[operationIndex]);
_latencies.Add(elapsed.TotalMilliseconds);
}
public void RecordFailure(Exception exn, int operationIndex, TimeSpan elapsed, int taskNum, long iteration)
{
DateTime timestamp = DateTime.Now;
Interlocked.Increment(ref _totalRequests);
Interlocked.Increment(ref _failures[operationIndex]);
_latencies.Add(elapsed.TotalMilliseconds);
RecordFailureType();
PrintToConsole();
// record exception according to failure type classification
void RecordFailureType()
{
(Type, string, string)[] key = ClassifyFailure(exn);
StressFailureType failureType = _failureTypes.GetOrAdd(key, _ => new StressFailureType(exn.ToString()));
lock (failureType)
{
if(!failureType.Failures.TryGetValue(operationIndex, out List<DateTime>? timestamps))
{
timestamps = new List<DateTime>();
failureType.Failures.Add(operationIndex, timestamps);
}
timestamps.Add(timestamp);
}
(Type exception, string message, string callSite)[] ClassifyFailure(Exception exn)
{
var acc = new List<(Type exception, string message, string callSite)>();
for (Exception? e = exn; e != null; )
{
acc.Add((e.GetType(), e.Message ?? "", new StackTrace(e, true).GetFrame(0)?.ToString() ?? ""));
e = e.InnerException;
}
return acc.ToArray();
}
}
void PrintToConsole()
{
if (exn is HttpRequestException hre && hre.InnerException is SocketException se && se.SocketErrorCode == SocketError.AddressAlreadyInUse)
{
Interlocked.Increment(ref _reuseAddressFailures);
}
else
{
lock (Console.Out)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"Error from iteration {iteration} ({_operationNames[operationIndex]}) in task {taskNum} with {_successes.Sum()} successes / {_failures.Sum()} fails:");
Console.ResetColor();
Console.WriteLine(exn);
Console.WriteLine();
}
}
}
}
public void PrintCurrentResults(TimeSpan runtime)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("[" + DateTime.Now + "]");
Console.ResetColor();
if (_lastTotal == _totalRequests)
{
Console.ForegroundColor = ConsoleColor.Red;
}
_lastTotal = _totalRequests;
Console.Write(" Total: " + _totalRequests.ToString("N0"));
Console.ResetColor();
Console.WriteLine($" Runtime: " + runtime.ToString(@"hh\:mm\:ss"));
if (_reuseAddressFailures > 0)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("~~ Reuse address failures: " + _reuseAddressFailures.ToString("N0") + "~~");
Console.ResetColor();
}
for (int i = 0; i < _operationNames.Length; i++)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write($"\t{_operationNames[i].PadRight(30)}");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("Success: ");
Console.Write(_successes[i].ToString("N0"));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("\tCanceled: ");
Console.Write(_cancellations[i].ToString("N0"));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.Write("\tFail: ");
Console.ResetColor();
Console.WriteLine(_failures[i].ToString("N0"));
}
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("\t TOTAL".PadRight(31));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("Success: ");
Console.Write(_successes.Sum().ToString("N0"));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("\tCanceled: ");
Console.Write(_cancellations.Sum().ToString("N0"));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.Write("\tFail: ");
Console.ResetColor();
Console.WriteLine(_failures.Sum().ToString("N0"));
Console.WriteLine();
}
public void PrintLatencies()
{
var latencies = _latencies.ToArray();
Array.Sort(latencies);
Console.WriteLine($"Latency(ms) : n={latencies.Length}, p50={Pc(0.5)}, p75={Pc(0.75)}, p99={Pc(0.99)}, p999={Pc(0.999)}, max={Pc(1)}");
Console.WriteLine();
double Pc(double percentile)
{
int N = latencies.Length;
double n = (N - 1) * percentile + 1;
if (n == 1) return Rnd(latencies[0]);
else if (n == N) return Rnd(latencies[N - 1]);
else
{
int k = (int)n;
double d = n - k;
return Rnd(latencies[k - 1] + d * (latencies[k] - latencies[k - 1]));
}
double Rnd(double value) => Math.Round(value, 2);
}
}
public void PrintFailureTypes()
{
if (_failureTypes.Count == 0)
return;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"There were a total of {_failures.Sum()} failures classified into {_failureTypes.Count} different types:");
Console.WriteLine();
Console.ResetColor();
int i = 0;
foreach (StressFailureType failure in _failureTypes.Values.OrderByDescending(x => x.FailureCount))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"Failure Type {++i}/{_failureTypes.Count}:");
Console.ResetColor();
Console.WriteLine(failure.ErrorText);
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Yellow;
foreach (KeyValuePair<int, List<DateTime>> operation in failure.Failures)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write($"\t{_operationNames[operation.Key].PadRight(30)}");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Fail: ");
Console.ResetColor();
Console.Write(operation.Value.Count);
Console.WriteLine($"\tTimestamps: {string.Join(", ", operation.Value.Select(x => x.ToString("HH:mm:ss")))}");
}
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("\t TOTAL".PadRight(31));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.Write($"Fail: ");
Console.ResetColor();
Console.WriteLine(failure.FailureCount);
Console.WriteLine();
}
}
}
private class StructuralEqualityComparer<T> : IEqualityComparer<T> where T : IStructuralEquatable
{
public bool Equals(T left, T right) => left.Equals(right, StructuralComparisons.StructuralEqualityComparer);
public int GetHashCode(T value) => value.GetHashCode(StructuralComparisons.StructuralEqualityComparer);
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR
{
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.Zelig.MetaData;
using Microsoft.Zelig.MetaData.Normalized;
using Microsoft.Zelig.Runtime.TypeSystem;
public partial class TypeSystemForCodeTransformation
{
[Runtime.ConfigurationOption( "ExcludeDebuggerHooks" )] public bool ExcludeDebuggerHooks;
//--//
[CompilationSteps.NewEntityNotification]
private void Notify_NewBoxedType( TypeRepresentation td )
{
//
// Make sure that there's a boxed representation for each value type.
//
if(td is ValueTypeRepresentation)
{
CreateBoxedValueType( td );
}
}
[CompilationSteps.NewEntityNotification]
private void Notify_CheckArrays( TypeRepresentation td )
{
if(td is SzArrayReferenceTypeRepresentation)
{
var elementType = td.ContainedType;
//
// For a non-generic array, we need to instantiate also the helper class.
// It will provide the implementation for the runtime methods.
//
if(elementType.IsOpenType == false)
{
CreateInstantiationOfGenericTemplate( this.WellKnownTypes.Microsoft_Zelig_Runtime_SZArrayHelper, elementType );
}
}
}
[CompilationSteps.NewEntityNotification]
private void Notify_CheckForComparerInstantiation( MethodRepresentation md )
{
if(md.Name == "CreateComparer")
{
var td = md.OwnerType;
if(td.IsGenericInstantiation)
{
if(td.GenericTemplate == this.WellKnownTypes.System_Collections_Generic_Comparer_of_T)
{
var tdParam = td.GenericParameters[0];
//// private static Comparer<T> CreateComparer()
//// {
//// Type t = typeof( T );
////
//// // If T implements IComparable<T> return a GenericComparer<T>
//// if(typeof( IComparable<T> ).IsAssignableFrom( t ))
//// {
//// //return (Comparer<T>)Activator.CreateInstance(typeof(GenericComparer<>).MakeGenericType(t));
//// return (Comparer<T>)(typeof( GenericComparer<int> ).TypeHandle.CreateInstanceForAnotherGenericParameter( t ));
//// }
////
//// // If T is a Nullable<U> where U implements IComparable<U> return a NullableComparer<U>
//// if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof( Nullable<> ))
//// {
//// Type u = t.GetGenericArguments()[0];
//// if(typeof( IComparable<> ).MakeGenericType( u ).IsAssignableFrom( u ))
//// {
//// //return (Comparer<T>)Activator.CreateInstance(typeof(NullableComparer<>).MakeGenericType(u));
//// return (Comparer<T>)(typeof( NullableComparer<int> ).TypeHandle.CreateInstanceForAnotherGenericParameter( u ));
//// }
//// }
////
//// // Otherwise return an ObjectComparer<T>
//// return new ObjectComparer<T>();
//// }
if(tdParam.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IComparable_of_T, tdParam ) != null)
{
var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_GenericComparer_of_T, tdParam );
CreateComparerHelper( md, newTd );
}
if(tdParam.GenericTemplate == this.WellKnownTypes.System_Nullable_of_T)
{
var tdParam2 = tdParam.GenericParameters[0];
if(td.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IComparable_of_T, tdParam2 ) != null)
{
var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_NullableComparer_of_T, tdParam2 );
CreateComparerHelper( md, newTd );
return;
}
}
{
var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_ObjectComparer_of_T, tdParam );
CreateComparerHelper( md, newTd );
return;
}
}
}
}
}
[CompilationSteps.NewEntityNotification]
private void Notify_CheckForEqualityComparerInstantiation( MethodRepresentation md )
{
if(md.Name == "CreateComparer")
{
var td = md.OwnerType;
if(td.IsGenericInstantiation)
{
if(td.GenericTemplate == this.WellKnownTypes.System_Collections_Generic_EqualityComparer_of_T)
{
var tdParam = td.GenericParameters[0];
//// private static EqualityComparer<T> CreateComparer()
//// {
//// Type t = typeof( T );
////
//// // Specialize type byte for performance reasons
//// if(t == typeof( byte ))
//// {
//// return (EqualityComparer<T>)(object)(new ByteEqualityComparer());
//// }
////
//// // If T implements IEquatable<T> return a GenericEqualityComparer<T>
//// if(typeof( IEquatable<T> ).IsAssignableFrom( t ))
//// {
//// //return (EqualityComparer<T>)Activator.CreateInstance(typeof(GenericEqualityComparer<>).MakeGenericType(t));
//// return (EqualityComparer<T>)(typeof( GenericEqualityComparer<int> ).TypeHandle.CreateInstanceForAnotherGenericParameter( t ));
//// }
////
//// // If T is a Nullable<U> where U implements IEquatable<U> return a NullableEqualityComparer<U>
//// if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof( Nullable<> ))
//// {
//// Type u = t.GetGenericArguments()[0];
//// if(typeof( IEquatable<> ).MakeGenericType( u ).IsAssignableFrom( u ))
//// {
//// //return (EqualityComparer<T>)Activator.CreateInstance(typeof(NullableEqualityComparer<>).MakeGenericType(u));
//// return (EqualityComparer<T>)(typeof( NullableEqualityComparer<int> ).TypeHandle.CreateInstanceForAnotherGenericParameter( u ));
//// }
//// }
////
//// // Otherwise return an ObjectEqualityComparer<T>
//// return new ObjectEqualityComparer<T>();
//// }
if(tdParam.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IEquatable_of_T, tdParam ) != null)
{
var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_GenericEqualityComparer_of_T, tdParam );
CreateComparerHelper( md, newTd );
return;
}
if(tdParam.GenericTemplate == this.WellKnownTypes.System_Nullable_of_T)
{
var tdParam2 = tdParam.GenericParameters[0];
if(td.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IEquatable_of_T, tdParam2 ) != null)
{
var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_NullableEqualityComparer_of_T, tdParam2 );
CreateComparerHelper( md, newTd );
return;
}
}
{
var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_ObjectEqualityComparer_of_T, tdParam );
CreateComparerHelper( md, newTd );
return;
}
}
}
}
}
private void CreateComparerHelper( MethodRepresentation md ,
TypeRepresentation newTd )
{
var cfg = (ControlFlowGraphStateForCodeTransformation)this.CreateControlFlowGraphState( md );
var bb = cfg.CreateFirstNormalBasicBlock();
//
// Allocate helper.
//
bb.AddOperator( ObjectAllocationOperator.New( null, newTd, cfg.ReturnValue ) );
cfg.AddReturnOperator();
}
//--//--//
//// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Internals_TypeDependencyAttribute" )]
//// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_TypeDependencyAttribute" )]
//// private void Notify_TypeDependencyAttribute( ref bool fKeep ,
//// CustomAttributeRepresentation ca ,
//// TypeRepresentation owner )
//// {
//// }
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Internals_WellKnownFieldAttribute" )]
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_WellKnownFieldAttribute" )]
private void Notify_WellKnownFieldAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
FieldRepresentation owner )
{
fKeep = false;
//
// Filter methods that belong to types that do not belong to the platform compiled
//
CustomAttributeRepresentation sfpf = owner.OwnerType.FindCustomAttribute( this.WellKnownTypes.Microsoft_Zelig_Runtime_ExtendClassAttribute );
if(sfpf != null)
{
object obj = sfpf.GetNamedArg( "PlatformVersionFilter" );
if(obj != null)
{
uint filter = (uint)obj;
if((filter & this.PlatformAbstraction.PlatformVersion) != this.PlatformAbstraction.PlatformVersion)
{
// This type is not an allowed extension for the current platform
return;
}
}
}
string fieldName = (string)ca.FixedArgsValues[0];
FieldRepresentation fdOld = this.GetWellKnownFieldNoThrow( fieldName );
if(fdOld != null && fdOld != owner)
{
throw TypeConsistencyErrorException.Create( "Found the well-known field '{0}' defined more than once: {1} and {2}", fieldName, fdOld, owner );
}
this.SetWellKnownField( fieldName, owner );
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Internals_WellKnownMethodAttribute" )]
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_WellKnownMethodAttribute" )]
private void Notify_WellKnownMethodAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
if(owner.IsGenericInstantiation)
{
owner = owner.GenericTemplate;
}
//
// Filter methods that belong to types that do not belong to the platform compiled
//
CustomAttributeRepresentation sfpf = owner.OwnerType.FindCustomAttribute( this.WellKnownTypes.Microsoft_Zelig_Runtime_ExtendClassAttribute );
if(sfpf != null)
{
object obj = sfpf.GetNamedArg( "PlatformVersionFilter" );
if(obj != null)
{
uint filter = (uint)obj;
if((filter & this.PlatformAbstraction.PlatformVersion) != this.PlatformAbstraction.PlatformVersion)
{
// This type is not an allowed extension for the current platform
return;
}
}
}
string methodName = (string)ca.FixedArgsValues[0];
MethodRepresentation mdOld = this.GetWellKnownMethodNoThrow( methodName );
if(mdOld != null && mdOld != owner)
{
throw TypeConsistencyErrorException.Create( "Found the well-known method '{0}' defined more than once: {1} and {2}", methodName, mdOld, owner );
}
this.SetWellKnownMethod( methodName, owner );
}
//--//
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ForceDevirtualizationAttribute" )]
private void Notify_ForceDevirtualizationAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
TypeRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.ForceDevirtualization;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ImplicitInstanceAttribute" )]
private void Notify_ImplicitInstanceAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
TypeRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.ImplicitInstance;
}
[CompilationSteps.CustomAttributeNotification( "System_FlagsAttribute" )]
private void Notify_FlagsAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
TypeRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.FlagsAttribute;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_InlineAttribute" )]
private void Notify_InlineAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Inline;
owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.NoInline;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_NoInlineAttribute" )]
private void Notify_NoInlineAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline;
owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BottomOfCallStackAttribute" )]
private void Notify_BottomOfCallStackAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.BottomOfCallStack;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_SaveFullProcessorContextAttribute" )]
private void Notify_SaveFullProcessorContextAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_NoReturnAttribute" )]
private void Notify_NoReturnAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoReturn;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_CannotAllocateAttribute" )]
private void Notify_CannotAllocateAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.CannotAllocate;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_CanAllocateOnReturnAttribute" )]
private void Notify_CanAllocateOnReturnAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.CanAllocateOnReturn;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_StackNotAvailableAttribute" )]
private void Notify_StackNotAvailableAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.StackNotAvailable;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_StackAvailableOnReturnAttribute" )]
private void Notify_StackAvailableOnReturnAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.StackAvailableOnReturn;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_DisableBoundsChecksAttribute" )]
private void Notify_DisableBoundsChecksAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
if(ca.GetNamedArg( "ApplyRecursively" ) != null)
{
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableDeepBoundsChecks;
}
else
{
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableBoundsChecks;
}
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_DisableNullChecksAttribute" )]
private void Notify_DisableNullChecksAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
if(ca.GetNamedArg( "ApplyRecursively" ) != null)
{
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableDeepNullChecks;
}
else
{
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableNullChecks;
}
}
//LON: 2/16/09
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ImportedMethodReferenceAttribute" )]
private void Notify_ImportedMethodReferenceAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = true;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Imported;
// for now disable inlining of these methods
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline;
owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline;
}
//LON: 2/16/09
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ExportedMethodAttribute" )]
private void Notify_ExportedMethodAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
fKeep = false;
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Exported;
// for now disable inlining of these methods
owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline;
owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline;
if(this.PlatformAbstraction.PlatformVersion == TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv7M ||
this.PlatformAbstraction.PlatformVersion == TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv6M ||
this.PlatformAbstraction.PlatformVersion == TargetModel.Win32.InstructionSetVersion.Platform_Version__x86 )
{
CustomAttributeRepresentation cf = owner.FindCustomAttribute( this.WellKnownTypes.Microsoft_Zelig_Runtime_CapabilitiesFilterAttribute );
if(cf != null)
{
object obj = cf.GetNamedArg( "RequiredCapabilities" );
if(obj != null)
{
uint capabilities = (uint)obj;
uint reqFamily = capabilities & TargetModel.ArmProcessor.InstructionSetVersion.Platform_Family__Mask;
uint reqVFP = capabilities & TargetModel.ArmProcessor.InstructionSetVersion.Platform_VFP__Mask;
uint reqPlatformVersion = capabilities & TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__Mask;
if(reqFamily != 0 && reqFamily != this.PlatformAbstraction.PlatformFamily)
{
// This method does not conform to the capabilities of the platform we are compiling
return;
}
else if(reqVFP != 0 && reqVFP != this.PlatformAbstraction.PlatformVFP)
{
// This method does not conform to the capabilities of the platform we are compiling
return;
}
else if(reqPlatformVersion != 0 && reqPlatformVersion != this.PlatformAbstraction.PlatformVersion)
{
// This method does not conform to the capabilities of the platform we are compiling
return;
}
}
}
ExportedMethods.Add(owner);
}
}
//--//
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_GarbageCollectionExtensionAttribute" )]
private void Notify_GarbageCollectionExtensionAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
TypeRepresentation owner )
{
var td = (TypeRepresentation)ca.FixedArgsValues[0];
m_garbageCollectionExtensions.Add( td, owner );
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_SkipDuringGarbageCollectionAttribute" )]
private void Notify_SkipDuringGarbageCollectionAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
FieldRepresentation owner )
{
m_garbageCollectionExclusions.Insert( owner );
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_DisableReferenceCountingAttribute" )]
private void Notify_EnableReferenceCountingAttribute( ref bool fKeep,
CustomAttributeRepresentation ca,
TypeRepresentation owner )
{
m_referenceCountingExcludedTypes.Insert( owner );
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_DisableAutomaticReferenceCountingAttribute" )]
private void Notify_DisableAutomaticReferenceCountingAttribute( ref bool fKeep,
CustomAttributeRepresentation ca,
BaseRepresentation owner )
{
if(owner is MethodRepresentation)
{
AddAutomaticReferenceCountingExclusion( (MethodRepresentation)owner );
}
else if(owner is TypeRepresentation)
{
var tr = (TypeRepresentation)owner;
foreach(var mr in tr.Methods)
{
AddAutomaticReferenceCountingExclusion( mr );
}
}
}
private void AddAutomaticReferenceCountingExclusion( MethodRepresentation md )
{
if(md.IsGenericInstantiation)
{
md = md.GenericTemplate;
}
var methodsList = m_automaticReferenceCountingExclusions.GetValue( md.Name );
if(methodsList == null)
{
methodsList = new List<MethodRepresentation>( );
m_automaticReferenceCountingExclusions.Add( md.Name, methodsList );
}
if(!methodsList.Contains( md ))
{
methodsList.Add( md );
}
}
//--//
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_AlignmentRequirementsAttribute" )]
private void Notify_AlignmentRequirementsAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
BaseRepresentation owner )
{
Abstractions.PlacementRequirements pr = CreatePlacementRequirements( owner );
pr.Alignment = (uint)ca.FixedArgsValues[0];
pr.AlignmentOffset = (int )ca.FixedArgsValues[1];
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_MemoryRequirementsAttribute" )]
private void Notify_MemoryRequirementsAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
BaseRepresentation owner )
{
Abstractions.PlacementRequirements pr = CreatePlacementRequirements( owner );
pr.AddConstraint( (Runtime.MemoryAttributes)ca.FixedArgsValues[0] );
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_MemoryUsageAttribute" )]
private void Notify_MemoryUsageAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
BaseRepresentation owner )
{
Abstractions.PlacementRequirements pr = CreatePlacementRequirements( owner );
pr.AddConstraint( (Runtime.MemoryUsage)ca.FixedArgsValues[0] );
pr.AddConstraint( ca.GetNamedArg<string>( "SectionName", null ) );
pr.ContentsUninitialized = ca.GetNamedArg( "ContentsUninitialized" , false );
pr.AllocateFromHighAddress = ca.GetNamedArg( "AllocateFromHighAddress", false );
}
//--//
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_HardwareExceptionHandlerAttribute" )]
private void Notify_HardwareExceptionHandlerAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
m_hardwareExceptionHandlers[ owner ] = ca;
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_DebuggerHookHandlerAttribute" )]
private void Notify_DebuggerHookHandlerAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
if(this.ExcludeDebuggerHooks == false)
{
m_debuggerHookHandlers[owner] = ca;
}
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_SingletonFactoryAttribute" )]
private void Notify_SingletonFactoryAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
MethodRepresentation owner )
{
m_singletonFactories[ owner ] = ca;
var tdFallback = ca.GetNamedArg( "Fallback" ) as TypeRepresentation;
if(tdFallback != null)
{
m_singletonFactoriesFallback[owner.OwnerType] = tdFallback;
}
}
//--//
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_NoVTableAttribute" )]
private void Notify_NoVTableAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
TypeRepresentation owner )
{
owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.NoVTable;
}
//--//--//
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_MemoryMappedPeripheralAttribute" )]
private void Notify_MemoryMappedPeripheralAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
TypeRepresentation owner )
{
m_memoryMappedPeripherals[ owner ] = ca;
RegisterAsMemoryMappedPeripheral( owner );
if(owner is ConcreteReferenceTypeRepresentation)
{
CheckRequiredFieldForMemoryMappedPeripheralAttribute( owner, "Base" );
CheckRequiredFieldForMemoryMappedPeripheralAttribute( owner, "Length" );
}
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_RegisterAttribute" )]
private void Notify_RegisterAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
FieldRepresentation owner )
{
CheckRequiredField( ca, owner, "Offset" );
m_registerAttributes[ owner ] = ca;
RegisterAsMemoryMappedPeripheral( owner.OwnerType );
}
private void RegisterAsMemoryMappedPeripheral( TypeRepresentation td )
{
for(var td2 = td; td2 != null && td2 != this.WellKnownTypes.System_Object; td2 = td2.Extends)
{
if(m_memoryMappedPeripherals.ContainsKey( td2 ) == false)
{
if(td == td2)
{
throw TypeConsistencyErrorException.Create( "'{0}' is not marked as a memory-mapped class", td.FullName );
}
else
{
throw TypeConsistencyErrorException.Create( "Cannot have memory-mapped class derive from a non-memory-mapped one: '{0}' => '{1}'", td.FullName, td2.FullName );
}
}
}
td.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.NoVTable;
RegisterForTypeLayoutDelegation( td, Notify_LayoutMemoryMappedPeripheral );
}
//--//
private bool Notify_LayoutMemoryMappedPeripheral( TypeRepresentation td ,
GrowOnlySet< TypeRepresentation > history )
{
uint maxSize = 0;
{
TypeRepresentation tdSize = td;
while(tdSize != null)
{
CustomAttributeRepresentation ca;
if(m_memoryMappedPeripherals.TryGetValue( tdSize, out ca ))
{
object sizeObj = ca.GetNamedArg( "Length" );
if(sizeObj != null)
{
maxSize = (uint)sizeObj;
break;
}
}
tdSize = tdSize.Extends;
}
}
foreach(FieldRepresentation fd in td.Fields)
{
if(fd is InstanceFieldRepresentation)
{
CustomAttributeRepresentation caFd;
if(m_registerAttributes.TryGetValue( fd, out caFd ) == false)
{
throw TypeConsistencyErrorException.Create( "Cannot have non-register field '{0}' in memory-mapped class '{1}'", fd.Name, td.FullNameWithAbbreviation );
}
var tdField = fd.FieldType;
EnsureTypeLayout( tdField, history, this.PlatformAbstraction.MemoryAlignment );
fd.Offset = (int)(uint)caFd.GetNamedArg( "Offset" );
maxSize = Math.Max( (uint)(fd.Offset + tdField.SizeOfHoldingVariable), maxSize );
}
}
td.Size = maxSize;
return true;
}
//--//--//
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BitFieldPeripheralAttribute" )]
private void Notify_BitFieldPeripheralAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
TypeRepresentation owner )
{
CheckRequiredField( ca, owner, "PhysicalType" );
owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.NoVTable;
m_memoryMappedBitFieldPeripherals[ owner ] = ca;
RegisterForTypeLayoutDelegation( owner, Layout_LayoutMemoryMappedBitFieldPeripheral );
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BitFieldRegisterAttribute" )]
private void Notify_BitFieldRegisterAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
FieldRepresentation owner )
{
var sec = CreateSectionOfBitFieldDefinition( ca, owner );
HandleBitFieldRegisterAttributeCommon( ref fKeep, ca, owner, sec );
}
[CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BitFieldSplitRegisterAttribute" )]
private void Notify_BitFieldSplitRegisterAttribute( ref bool fKeep ,
CustomAttributeRepresentation ca ,
FieldRepresentation owner )
{
var sec = CreateSectionOfBitFieldDefinition( ca, owner );
if(ca.TryToGetNamedArg( "Offset", out sec.Offset ) == false)
{
FailedRequiredField( ca, owner, "Offset" );
}
HandleBitFieldRegisterAttributeCommon( ref fKeep, ca, owner, sec );
}
private BitFieldDefinition.Section CreateSectionOfBitFieldDefinition( CustomAttributeRepresentation ca ,
FieldRepresentation owner )
{
BitFieldDefinition.Section sec = new BitFieldDefinition.Section();
if(ca.TryToGetNamedArg( "Position", out sec.Position ) == false)
{
FailedRequiredField( ca, owner, "Position" );
}
if(ca.TryToGetNamedArg( "Size", out sec.Size ) == false)
{
if(owner.FieldType != this.WellKnownTypes.System_Boolean)
{
FailedRequiredField( ca, owner, "Size" );
}
sec.Size = 1;
}
ca.TryToGetNamedArg( "Modifiers", out sec.Modifiers );
ca.TryToGetNamedArg( "ReadAs" , out sec.ReadsAs );
ca.TryToGetNamedArg( "WriteAs" , out sec.WritesAs );
return sec;
}
private void HandleBitFieldRegisterAttributeCommon( ref bool fKeep ,
CustomAttributeRepresentation ca ,
FieldRepresentation owner ,
BitFieldDefinition.Section sec )
{
fKeep = false;
if(m_memoryMappedBitFieldPeripherals.ContainsKey( owner.OwnerType ) == false)
{
throw TypeConsistencyErrorException.Create( "Containing type '{0}' of bitfield register '{1}' must be a bitfield peripheral", owner.OwnerType.FullName, owner );
}
BitFieldDefinition bfDef;
if(m_bitFieldRegisterAttributes.TryGetValue( owner, out bfDef ) == false)
{
bfDef = new BitFieldDefinition();
m_bitFieldRegisterAttributes[ owner ] = bfDef;
}
bfDef.AddSection( sec );
}
//--//
private bool Layout_LayoutMemoryMappedBitFieldPeripheral( TypeRepresentation td ,
GrowOnlySet< TypeRepresentation > history )
{
CustomAttributeRepresentation ca = m_memoryMappedBitFieldPeripherals[td];
TypeRepresentation tdPhysical = ca.GetNamedArg< TypeRepresentation >( "PhysicalType" );
EnsureTypeLayout( tdPhysical, history, this.PlatformAbstraction.MemoryAlignment );
td.Size = tdPhysical.Size;
foreach(FieldRepresentation fd in td.Fields)
{
if(fd is StaticFieldRepresentation)
{
throw TypeConsistencyErrorException.Create( "Cannot have static field '{0}' in memory-mapped bitfield class '{1}'", fd.Name, td.FullNameWithAbbreviation );
}
if(m_bitFieldRegisterAttributes.ContainsKey( fd ) == false)
{
throw TypeConsistencyErrorException.Create( "Cannot have non-bitfield register field '{0}' in memory-mapped bitfield class '{1}'", fd.Name, td.FullNameWithAbbreviation );
}
fd.Offset = 0;
}
return true;
}
//--//--//
private void CheckRequiredFieldForMemoryMappedPeripheralAttribute( TypeRepresentation target ,
string name )
{
for(TypeRepresentation td = target; td != null; td = td.Extends)
{
CustomAttributeRepresentation ca;
if(m_memoryMappedPeripherals.TryGetValue( td, out ca ))
{
if(ca.HasNamedArg( name ))
{
return;
}
}
}
throw TypeConsistencyErrorException.Create( "Cannot find required '{0}' field for attribute MemoryMappedPeripheralAttribute on the hierarchy for {2}", name, target );
}
private static void CheckRequiredField( CustomAttributeRepresentation ca ,
object owner ,
string name )
{
if(ca.HasNamedArg( name ) == false)
{
FailedRequiredField( ca, owner, name );
}
}
private static void FailedRequiredField( CustomAttributeRepresentation ca ,
object owner ,
string name )
{
throw TypeConsistencyErrorException.Create( "Missing required '{0}' field for attribute '{1}' on '{2}'", name, ca.Constructor.OwnerType.FullName, owner );
}
}
}
| |
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 BGB.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using PlayFab.Internal;
using PlayFab.Json;
namespace PlayFab.UUnit
{
public enum Region
{
USCentral,
USEast,
EUWest,
Singapore,
Japan,
Brazil,
Australia
}
internal class JsonPropertyAttrTestClass
{
[JsonProperty(PropertyName = "GoodField")]
public string InvalidField;
[JsonProperty(PropertyName = "GoodProperty")]
public string InvalidProperty { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public object HideNull = null;
public object ShowNull = null;
}
internal class NullableTestClass
{
public bool? BoolField = null;
public bool? BoolProperty { get; set; }
public int? IntField = null;
public int? IntProperty { get; set; }
public DateTime? TimeField = null;
public DateTime? TimeProperty { get; set; }
public Region? EnumField = null;
public Region? EnumProperty { get; set; }
}
internal class ObjNumFieldTest
{
public sbyte SbyteValue; public byte ByteValue;
public short ShortValue; public ushort UshortValue;
public int IntValue; public uint UintValue;
public long LongValue; public ulong UlongValue;
public float FloatValue; public double DoubleValue;
public static ObjNumFieldTest Max = new ObjNumFieldTest { SbyteValue = sbyte.MaxValue, ByteValue = byte.MaxValue, ShortValue = short.MaxValue, UshortValue = ushort.MaxValue, IntValue = int.MaxValue, UintValue = uint.MaxValue, LongValue = long.MaxValue, UlongValue = ulong.MaxValue, FloatValue = float.MaxValue, DoubleValue = double.MaxValue };
public static ObjNumFieldTest Min = new ObjNumFieldTest { SbyteValue = sbyte.MinValue, ByteValue = byte.MinValue, ShortValue = short.MinValue, UshortValue = ushort.MinValue, IntValue = int.MinValue, UintValue = uint.MinValue, LongValue = long.MinValue, UlongValue = ulong.MinValue, FloatValue = float.MinValue, DoubleValue = double.MinValue };
public static ObjNumFieldTest Zero = new ObjNumFieldTest();
}
internal class ObjNumPropTest
{
public sbyte SbyteValue { get; set; }
public byte ByteValue { get; set; }
public short ShortValue { get; set; }
public ushort UshortValue { get; set; }
public int IntValue { get; set; }
public uint UintValue { get; set; }
public long LongValue { get; set; }
public ulong UlongValue { get; set; }
public float FloatValue { get; set; }
public double DoubleValue { get; set; }
public static ObjNumPropTest Max = new ObjNumPropTest { SbyteValue = sbyte.MaxValue, ByteValue = byte.MaxValue, ShortValue = short.MaxValue, UshortValue = ushort.MaxValue, IntValue = int.MaxValue, UintValue = uint.MaxValue, LongValue = long.MaxValue, UlongValue = ulong.MaxValue, FloatValue = float.MaxValue, DoubleValue = double.MaxValue };
public static ObjNumPropTest Min = new ObjNumPropTest { SbyteValue = sbyte.MinValue, ByteValue = byte.MinValue, ShortValue = short.MinValue, UshortValue = ushort.MinValue, IntValue = int.MinValue, UintValue = uint.MinValue, LongValue = long.MinValue, UlongValue = ulong.MinValue, FloatValue = float.MinValue, DoubleValue = double.MinValue };
public static ObjNumPropTest Zero = new ObjNumPropTest();
}
internal struct StructNumFieldTest
{
public sbyte SbyteValue; public byte ByteValue;
public short ShortValue; public ushort UshortValue;
public int IntValue; public uint UintValue;
public long LongValue; public ulong UlongValue;
public float FloatValue; public double DoubleValue;
public static StructNumFieldTest Max = new StructNumFieldTest { SbyteValue = sbyte.MaxValue, ByteValue = byte.MaxValue, ShortValue = short.MaxValue, UshortValue = ushort.MaxValue, IntValue = int.MaxValue, UintValue = uint.MaxValue, LongValue = long.MaxValue, UlongValue = ulong.MaxValue, FloatValue = float.MaxValue, DoubleValue = double.MaxValue };
public static StructNumFieldTest Min = new StructNumFieldTest { SbyteValue = sbyte.MinValue, ByteValue = byte.MinValue, ShortValue = short.MinValue, UshortValue = ushort.MinValue, IntValue = int.MinValue, UintValue = uint.MinValue, LongValue = long.MinValue, UlongValue = ulong.MinValue, FloatValue = float.MinValue, DoubleValue = double.MinValue };
public static StructNumFieldTest Zero = new StructNumFieldTest();
}
internal class ObjOptNumFieldTest
{
public sbyte? SbyteValue { get; set; }
public byte? ByteValue { get; set; }
public short? ShortValue { get; set; }
public ushort? UshortValue { get; set; }
public int? IntValue { get; set; }
public uint? UintValue { get; set; }
public long? LongValue { get; set; }
public ulong? UlongValue { get; set; }
public float? FloatValue { get; set; }
public double? DoubleValue { get; set; }
public static ObjOptNumFieldTest Max = new ObjOptNumFieldTest { SbyteValue = sbyte.MaxValue, ByteValue = byte.MaxValue, ShortValue = short.MaxValue, UshortValue = ushort.MaxValue, IntValue = int.MaxValue, UintValue = uint.MaxValue, LongValue = long.MaxValue, UlongValue = ulong.MaxValue, FloatValue = float.MaxValue, DoubleValue = double.MaxValue };
public static ObjOptNumFieldTest Min = new ObjOptNumFieldTest { SbyteValue = sbyte.MinValue, ByteValue = byte.MinValue, ShortValue = short.MinValue, UshortValue = ushort.MinValue, IntValue = int.MinValue, UintValue = uint.MinValue, LongValue = long.MinValue, UlongValue = ulong.MinValue, FloatValue = float.MinValue, DoubleValue = double.MinValue };
public static ObjOptNumFieldTest Zero = new ObjOptNumFieldTest { SbyteValue = 0, ByteValue = 0, ShortValue = 0, UshortValue = 0, IntValue = 0, UintValue = 0, LongValue = 0, UlongValue = 0, FloatValue = 0, DoubleValue = 0 };
public static ObjOptNumFieldTest Null = new ObjOptNumFieldTest { SbyteValue = null, ByteValue = null, ShortValue = null, UshortValue = null, IntValue = null, UintValue = null, LongValue = null, UlongValue = null, FloatValue = null, DoubleValue = null };
}
internal class OtherSpecificDatatypes
{
public Dictionary<string, string> StringDict { get; set; }
public Dictionary<string, int> IntDict { get; set; }
public Dictionary<string, uint> UintDict { get; set; }
public Dictionary<string, Region> EnumDict { get; set; }
public string TestString { get; set; }
}
public class JsonFeatureTests : UUnitTestCase
{
[UUnitTest]
public void JsonPropertyTest(UUnitTestContext testContext)
{
var expectedObject = new JsonPropertyAttrTestClass { InvalidField = "asdf", InvalidProperty = "fdsa" };
var json = JsonWrapper.SerializeObject(expectedObject);
// Verify that the field names have been transformed by the JsonProperty attribute
testContext.False(json.ToLower().Contains("invalid"), json);
testContext.False(json.ToLower().Contains("hidenull"), json);
testContext.True(json.ToLower().Contains("shownull"), json);
// Verify that the fields are re-serialized into the proper locations by the JsonProperty attribute
var actualObject = JsonWrapper.DeserializeObject<JsonPropertyAttrTestClass>(json);
testContext.StringEquals(expectedObject.InvalidField, actualObject.InvalidField, actualObject.InvalidField);
testContext.StringEquals(expectedObject.InvalidProperty, actualObject.InvalidProperty, actualObject.InvalidProperty);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
[UUnitTest]
public void TestObjNumField(UUnitTestContext testContext)
{
var expectedObjects = new[] { ObjNumFieldTest.Max, ObjNumFieldTest.Min, ObjNumFieldTest.Zero };
for (var i = 0; i < expectedObjects.Length; i++)
{
// Convert the object to json and back, and verify that everything is the same
var actualJson = JsonWrapper.SerializeObject(expectedObjects[i]).Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
var actualObject = JsonWrapper.DeserializeObject<ObjNumFieldTest>(actualJson);
testContext.SbyteEquals(expectedObjects[i].SbyteValue, actualObject.SbyteValue);
testContext.ByteEquals(expectedObjects[i].ByteValue, actualObject.ByteValue);
testContext.ShortEquals(expectedObjects[i].ShortValue, actualObject.ShortValue);
testContext.UshortEquals(expectedObjects[i].UshortValue, actualObject.UshortValue);
testContext.IntEquals(expectedObjects[i].IntValue, actualObject.IntValue);
testContext.UintEquals(expectedObjects[i].UintValue, actualObject.UintValue);
testContext.LongEquals(expectedObjects[i].LongValue, actualObject.LongValue);
testContext.ULongEquals(expectedObjects[i].UlongValue, actualObject.UlongValue);
testContext.FloatEquals(expectedObjects[i].FloatValue, actualObject.FloatValue, 0.001f);
testContext.DoubleEquals(expectedObjects[i].DoubleValue, actualObject.DoubleValue, 0.001);
}
testContext.EndTest(UUnitFinishState.PASSED, null);
}
[UUnitTest]
public void TestObjNumProp(UUnitTestContext testContext)
{
var expectedObjects = new[] { ObjNumPropTest.Max, ObjNumPropTest.Min, ObjNumPropTest.Zero };
for (var i = 0; i < expectedObjects.Length; i++)
{
// Convert the object to json and back, and verify that everything is the same
var actualJson = JsonWrapper.SerializeObject(expectedObjects[i]).Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
var actualObject = JsonWrapper.DeserializeObject<ObjNumPropTest>(actualJson);
testContext.SbyteEquals(expectedObjects[i].SbyteValue, actualObject.SbyteValue);
testContext.ByteEquals(expectedObjects[i].ByteValue, actualObject.ByteValue);
testContext.ShortEquals(expectedObjects[i].ShortValue, actualObject.ShortValue);
testContext.UshortEquals(expectedObjects[i].UshortValue, actualObject.UshortValue);
testContext.IntEquals(expectedObjects[i].IntValue, actualObject.IntValue);
testContext.UintEquals(expectedObjects[i].UintValue, actualObject.UintValue);
testContext.LongEquals(expectedObjects[i].LongValue, actualObject.LongValue);
testContext.ULongEquals(expectedObjects[i].UlongValue, actualObject.UlongValue);
testContext.FloatEquals(expectedObjects[i].FloatValue, actualObject.FloatValue, float.MaxValue * 0.000000001f);
testContext.DoubleEquals(expectedObjects[i].DoubleValue, actualObject.DoubleValue, double.MaxValue * 0.000000001f);
}
testContext.EndTest(UUnitFinishState.PASSED, null);
}
[UUnitTest]
public void TestStructNumField(UUnitTestContext testContext)
{
var expectedObjects = new[] { StructNumFieldTest.Max, StructNumFieldTest.Min, StructNumFieldTest.Zero };
for (var i = 0; i < expectedObjects.Length; i++)
{
// Convert the object to json and back, and verify that everything is the same
var actualJson = JsonWrapper.SerializeObject(expectedObjects[i]).Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
var actualObject = JsonWrapper.DeserializeObject<ObjNumPropTest>(actualJson);
testContext.SbyteEquals(expectedObjects[i].SbyteValue, actualObject.SbyteValue);
testContext.ByteEquals(expectedObjects[i].ByteValue, actualObject.ByteValue);
testContext.ShortEquals(expectedObjects[i].ShortValue, actualObject.ShortValue);
testContext.UshortEquals(expectedObjects[i].UshortValue, actualObject.UshortValue);
testContext.IntEquals(expectedObjects[i].IntValue, actualObject.IntValue);
testContext.UintEquals(expectedObjects[i].UintValue, actualObject.UintValue);
testContext.LongEquals(expectedObjects[i].LongValue, actualObject.LongValue);
testContext.ULongEquals(expectedObjects[i].UlongValue, actualObject.UlongValue);
testContext.FloatEquals(expectedObjects[i].FloatValue, actualObject.FloatValue, float.MaxValue * 0.000000001f);
testContext.DoubleEquals(expectedObjects[i].DoubleValue, actualObject.DoubleValue, double.MaxValue * 0.000000001f);
}
testContext.EndTest(UUnitFinishState.PASSED, null);
}
[UUnitTest]
public void TestObjOptNumField(UUnitTestContext testContext)
{
var expectedObjects = new[] { ObjOptNumFieldTest.Max, ObjOptNumFieldTest.Min, ObjOptNumFieldTest.Zero, ObjOptNumFieldTest.Null };
for (var i = 0; i < expectedObjects.Length; i++)
{
// Convert the object to json and back, and verify that everything is the same
var actualJson = JsonWrapper.SerializeObject(expectedObjects[i]).Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
var actualObject = JsonWrapper.DeserializeObject<ObjOptNumFieldTest>(actualJson);
testContext.SbyteEquals(expectedObjects[i].SbyteValue, actualObject.SbyteValue);
testContext.ByteEquals(expectedObjects[i].ByteValue, actualObject.ByteValue);
testContext.ShortEquals(expectedObjects[i].ShortValue, actualObject.ShortValue);
testContext.UshortEquals(expectedObjects[i].UshortValue, actualObject.UshortValue);
testContext.IntEquals(expectedObjects[i].IntValue, actualObject.IntValue);
testContext.UintEquals(expectedObjects[i].UintValue, actualObject.UintValue);
testContext.LongEquals(expectedObjects[i].LongValue, actualObject.LongValue);
testContext.ULongEquals(expectedObjects[i].UlongValue, actualObject.UlongValue);
testContext.FloatEquals(expectedObjects[i].FloatValue, actualObject.FloatValue, float.MaxValue * 0.000000001f);
testContext.DoubleEquals(expectedObjects[i].DoubleValue, actualObject.DoubleValue, double.MaxValue * 0.000000001f);
}
testContext.EndTest(UUnitFinishState.PASSED, null);
}
[UUnitTest]
public void OtherSpecificDatatypes(UUnitTestContext testContext)
{
var expectedObj = new OtherSpecificDatatypes
{
StringDict = new Dictionary<string, string> { { "stringKey", "stringValue" } },
EnumDict = new Dictionary<string, Region> { { "enumKey", Region.Japan } },
IntDict = new Dictionary<string, int> { { "intKey", int.MinValue } },
UintDict = new Dictionary<string, uint> { { "uintKey", uint.MaxValue } },
TestString = "yup",
};
// Convert the object to json and back, and verify that everything is the same
var actualJson = JsonWrapper.SerializeObject(expectedObj).Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
var actualObject = JsonWrapper.DeserializeObject<OtherSpecificDatatypes>(actualJson);
testContext.ObjEquals(expectedObj.TestString, actualObject.TestString);
testContext.SequenceEquals(expectedObj.IntDict, actualObject.IntDict);
testContext.SequenceEquals(expectedObj.UintDict, actualObject.UintDict);
testContext.SequenceEquals(expectedObj.StringDict, actualObject.StringDict);
testContext.SequenceEquals(expectedObj.EnumDict, actualObject.EnumDict);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
[UUnitTest]
public void ArrayAsObject(UUnitTestContext testContext)
{
var json = "{\"Version\": \"2016-06-21_23-57-16\", \"ObjectArray\": [{\"Id\": 2, \"Name\": \"Stunned\", \"Type\": \"Condition\", \"ShowNumber\": true, \"EN_text\": \"Stunned\", \"EN_reminder\": \"Can\'t attack, block, or activate\"}, {\"Id\": 3, \"Name\": \"Poisoned\", \"Type\": \"Condition\", \"ShowNumber\": true, \"EN_text\": \"Poisoned\", \"EN_reminder\": \"Takes {N} damage at the start of each turn. Wears off over time.\" }], \"StringArray\": [\"NoSubtype\", \"Aircraft\"]}";
var result = JsonWrapper.DeserializeObject<Dictionary<string, object>>(json);
var version = result["Version"] as string;
var objArray = result["ObjectArray"] as List<object>;
var strArray = result["StringArray"] as List<object>;
testContext.NotNull(result);
testContext.True(!string.IsNullOrEmpty(version));
testContext.True(objArray != null && objArray.Count > 0);
testContext.True(strArray != null && strArray.Count > 0);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
[UUnitTest]
public void TimeSpanJson(UUnitTestContext testContext)
{
var span = TimeSpan.FromSeconds(5);
var actualJson = JsonWrapper.SerializeObject(span);
var expectedJson = "5";
testContext.StringEquals(expectedJson, actualJson, actualJson);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
[UUnitTest]
public void ArrayOfObjects(UUnitTestContext testContext)
{
var actualJson = "[{\"a\":\"aValue\"}, {\"b\":\"bValue\"}]";
var actualObjectList = JsonWrapper.DeserializeObject<List<object>>(actualJson);
var actualObjectArray = JsonWrapper.DeserializeObject<object[]>(actualJson);
testContext.IntEquals(actualObjectList.Count, 2);
testContext.IntEquals(actualObjectArray.Length, 2);
testContext.StringEquals(((JsonObject)actualObjectList[0])["a"] as string, "aValue");
testContext.StringEquals(((JsonObject)actualObjectList[1])["b"] as string, "bValue");
testContext.EndTest(UUnitFinishState.PASSED, null);
}
[UUnitTest]
public void NullableJson(UUnitTestContext testContext)
{
var testObjNull = new NullableTestClass();
var testObjInt = new NullableTestClass { IntField = 42, IntProperty = 42 };
var testObjTime = new NullableTestClass { TimeField = DateTime.UtcNow, TimeProperty = DateTime.UtcNow };
var testObjEnum = new NullableTestClass { EnumField = Region.Japan, EnumProperty = Region.Japan };
var testObjBool = new NullableTestClass { BoolField = true, BoolProperty = true };
var testObjs = new[] { testObjNull, testObjEnum, testObjBool, testObjInt, testObjTime };
List<string> failures = new List<string>();
foreach (var testObj in testObjs)
{
NullableTestClass actualObj = null;
var actualJson = JsonWrapper.SerializeObject(testObj);
try
{
actualObj = JsonWrapper.DeserializeObject<NullableTestClass>(actualJson);
}
catch (Exception)
{
failures.Add(actualJson + " Cannot be deserialized as NullableTestClass");
continue;
}
if (testObj.BoolField != actualObj.BoolField) failures.Add("Nullable bool field does not serialize properly: " + testObj.BoolField + ", from " + actualJson);
if (testObj.BoolProperty != actualObj.BoolProperty) failures.Add("Nullable bool property does not serialize properly: " + testObj.BoolProperty + ", from " + actualJson);
if (testObj.IntField != actualObj.IntField) failures.Add("Nullable integer field does not serialize properly: " + testObj.IntField + ", from " + actualJson);
if (testObj.IntProperty != actualObj.IntProperty) failures.Add("Nullable integer property does not serialize properly: " + testObj.IntProperty + ", from " + actualJson);
if (testObj.EnumField != actualObj.EnumField) failures.Add("Nullable enum field does not serialize properly: " + testObj.EnumField + ", from " + actualJson);
if (testObj.EnumProperty != actualObj.EnumProperty) failures.Add("Nullable enum property does not serialize properly: " + testObj.EnumProperty + ", from " + actualJson);
if (testObj.TimeField.HasValue != actualObj.TimeField.HasValue)
failures.Add("Nullable struct field does not serialize properly: " + testObj.TimeField + ", from " + actualJson);
if (testObj.TimeField.HasValue && Math.Abs((testObj.TimeField - actualObj.TimeField).Value.TotalSeconds) > 1)
failures.Add("Nullable struct field does not serialize properly: " + testObj.TimeField + ", from " + actualJson);
if (testObj.TimeProperty.HasValue != actualObj.TimeProperty.HasValue)
failures.Add("Nullable struct field does not serialize properly: " + testObj.TimeProperty + ", from " + actualJson);
if (testObj.TimeProperty.HasValue && Math.Abs((testObj.TimeProperty - actualObj.TimeProperty).Value.TotalSeconds) > 1)
failures.Add("Nullable struct property does not serialize properly: " + testObj.TimeProperty + ", from " + actualJson);
}
if (failures.Count == 0)
testContext.EndTest(UUnitFinishState.PASSED, null);
else
testContext.EndTest(UUnitFinishState.FAILED, string.Join("\n", failures.ToArray()));
}
[UUnitTest]
public void TestDeserializeToObject(UUnitTestContext testContext)
{
var testInt = PlayFabSimpleJson.DeserializeObject<object>("1");
var testString = PlayFabSimpleJson.DeserializeObject<object>("\"a string\"");
testContext.IntEquals((int)(ulong)testInt, 1);
testContext.StringEquals((string)testString, "a string");
testContext.EndTest(UUnitFinishState.PASSED, null);
}
}
}
| |
// <copyright file="TFQMRTest.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>
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex32;
using MathNet.Numerics.LinearAlgebra.Complex32.Solvers;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32.Solvers.Iterative
{
using Numerics;
/// <summary>
/// Tests of Transpose Free Quasi-Minimal Residual iterative matrix solver.
/// </summary>
[TestFixture, Category("LASolver")]
public class TFQMRTest
{
/// <summary>
/// Convergence boundary.
/// </summary>
const float ConvergenceBoundary = 1e-5f;
/// <summary>
/// Maximum iterations.
/// </summary>
const int MaximumIterations = 1000;
/// <summary>
/// Solve wide matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveWideMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(2, 3);
var input = new DenseVector(2);
var solver = new TFQMR();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve long matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveLongMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(3, 2);
var input = new DenseVector(3);
var solver = new TFQMR();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve unit matrix and back multiply.
/// </summary>
[Test]
public void SolveUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = SparseMatrix.CreateIdentity(100);
// Create the y vector
var y = Vector<Complex32>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex32>(
new IterationCountStopCriterion<Complex32>(MaximumIterations),
new ResidualStopCriterion<Complex32>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex32>(),
new FailureStopCriterion<Complex32>());
var solver = new TFQMR();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
Assert.LessOrEqual(Distance.Chebyshev(y, z), 2*ConvergenceBoundary);
}
/// <summary>
/// Solve scaled unit matrix and back multiply.
/// </summary>
[Test]
public void SolveScaledUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = SparseMatrix.CreateIdentity(100);
// Scale it with a funny number
matrix.Multiply((float)Math.PI, matrix);
// Create the y vector
var y = Vector<Complex32>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex32>(
new IterationCountStopCriterion<Complex32>(MaximumIterations),
new ResidualStopCriterion<Complex32>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex32>(),
new FailureStopCriterion<Complex32>());
var solver = new TFQMR();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
Assert.LessOrEqual(Distance.Chebyshev(y, z), 2*ConvergenceBoundary);
}
/// <summary>
/// Solve poisson matrix and back multiply.
/// </summary>
[Test]
public void SolvePoissonMatrixAndBackMultiply()
{
// Create the matrix
var matrix = new SparseMatrix(25);
// Assemble the matrix. We assume we're solving the Poisson equation
// on a rectangular 5 x 5 grid
const int GridSize = 5;
// The pattern is:
// 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
for (var i = 0; i < matrix.RowCount; i++)
{
// Insert the first set of -1's
if (i > (GridSize - 1))
{
matrix[i, i - GridSize] = -1;
}
// Insert the second set of -1's
if (i > 0)
{
matrix[i, i - 1] = -1;
}
// Insert the centerline values
matrix[i, i] = 4;
// Insert the first trailing set of -1's
if (i < matrix.RowCount - 1)
{
matrix[i, i + 1] = -1;
}
// Insert the second trailing set of -1's
if (i < matrix.RowCount - GridSize)
{
matrix[i, i + GridSize] = -1;
}
}
// Create the y vector
var y = Vector<Complex32>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex32>(
new IterationCountStopCriterion<Complex32>(MaximumIterations),
new ResidualStopCriterion<Complex32>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex32>(),
new FailureStopCriterion<Complex32>());
var solver = new TFQMR();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
Assert.LessOrEqual(Distance.Chebyshev(y, z), 2*ConvergenceBoundary);
}
/// <summary>
/// Can solve for a random vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
public void CanSolveForRandomVector(int order)
{
for (var iteration = 5; iteration > 3; iteration--)
{
var matrixA = Matrix<Complex32>.Build.Random(order, order, 1);
var vectorb = Vector<Complex32>.Build.Random(order, 1);
var monitor = new Iterator<Complex32>(
new IterationCountStopCriterion<Complex32>(1000),
new ResidualStopCriterion<Complex32>(Math.Pow(1.0/10.0, iteration)));
var solver = new TFQMR();
var resultx = matrixA.SolveIterative(vectorb, solver, monitor);
if (monitor.Status != IterationStatus.Converged)
{
// Solution was not found, try again downgrading convergence boundary
continue;
}
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, (float)Math.Pow(1.0/10.0, iteration - 3));
Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, (float)Math.Pow(1.0/10.0, iteration - 3));
}
return;
}
Assert.Fail("Solution was not found in 3 tries");
}
/// <summary>
/// Can solve for random matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
public void CanSolveForRandomMatrix(int order)
{
for (var iteration = 5; iteration > 3; iteration--)
{
var matrixA = Matrix<Complex32>.Build.Random(order, order, 1);
var matrixB = Matrix<Complex32>.Build.Random(order, order, 1);
var monitor = new Iterator<Complex32>(
new IterationCountStopCriterion<Complex32>(1000),
new ResidualStopCriterion<Complex32>(Math.Pow(1.0/10.0, iteration)));
var solver = new TFQMR();
var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);
if (monitor.Status != IterationStatus.Converged)
{
// Solution was not found, try again downgrading convergence boundary
continue;
}
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, (float)Math.Pow(1.0/10.0, iteration - 3));
Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, (float)Math.Pow(1.0/10.0, iteration - 3));
}
}
return;
}
Assert.Fail("Solution was not found in 3 tries");
}
}
}
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("2D Toolkit/Deprecated/GUI/tk2dButton")]
public class tk2dButton : MonoBehaviour
{
/// <summary>
/// The camera this button is meant to be viewed from.
/// Set this explicitly for best performance.\n
/// The system will automatically traverse up the hierarchy to find a camera if this is not set.\n
/// If nothing is found, it will fall back to the active <see cref="tk2dCamera"/>.\n
/// Failing that, it will use Camera.main.
/// </summary>
public Camera viewCamera;
// Button Up = normal state
// Button Down = held down
// Button Pressed = after it is pressed and activated
/// <summary>
/// The button down sprite. This is resolved by name from the sprite collection of the sprite component.
/// </summary>
public string buttonDownSprite = "button_down";
/// <summary>
/// The button up sprite. This is resolved by name from the sprite collection of the sprite component.
/// </summary>
public string buttonUpSprite = "button_up";
/// <summary>
/// The button pressed sprite. This is resolved by name from the sprite collection of the sprite component.
/// </summary>
public string buttonPressedSprite = "button_up";
int buttonDownSpriteId = -1, buttonUpSpriteId = -1, buttonPressedSpriteId = -1;
/// <summary>
/// Audio clip to play when the button transitions from up to down state. Requires an AudioSource component to be attached to work.
/// </summary>
public AudioClip buttonDownSound = null;
/// <summary>
/// Audio clip to play when the button transitions from down to up state. Requires an AudioSource component to be attached to work.
/// </summary>
public AudioClip buttonUpSound = null;
/// <summary>
/// Audio clip to play when the button is pressed. Requires an AudioSource component to be attached to work.
/// </summary>
public AudioClip buttonPressedSound = null;
// Delegates
/// <summary>
/// Button event handler delegate.
/// </summary>
public delegate void ButtonHandlerDelegate(tk2dButton source);
// Messaging
/// <summary>
/// Target object to send the message to. The event methods below are significantly more efficient.
/// </summary>
public GameObject targetObject = null;
/// <summary>
/// The message to send to the object. This should be the name of the method which needs to be called.
/// </summary>
public string messageName = "";
/// <summary>
/// Occurs when button is pressed (tapped, and finger lifted while inside the button)
/// </summary>
public event ButtonHandlerDelegate ButtonPressedEvent;
/// <summary>
/// Occurs every frame for as long as the button is held down.
/// </summary>
public event ButtonHandlerDelegate ButtonAutoFireEvent;
/// <summary>
/// Occurs when button transition from up to down state
/// </summary>
public event ButtonHandlerDelegate ButtonDownEvent;
/// <summary>
/// Occurs when button transitions from down to up state
/// </summary>
public event ButtonHandlerDelegate ButtonUpEvent;
tk2dBaseSprite sprite;
bool buttonDown = false;
/// <summary>
/// How much to scale the sprite when the button is in the down state
/// </summary>
public float targetScale = 1.1f;
/// <summary>
/// The length of time the scale operation takes
/// </summary>
public float scaleTime = 0.05f;
/// <summary>
/// How long to wait before allowing the button to be pressed again, in seconds.
/// </summary>
public float pressedWaitTime = 0.3f;
void OnEnable()
{
buttonDown = false;
}
// Use this for initialization
void Start ()
{
if (viewCamera == null)
{
// Find a camera parent
Transform node = transform;
while (node && node.GetComponent<Camera>() == null)
{
node = node.parent;
}
if (node && node.GetComponent<Camera>() != null)
{
viewCamera = node.GetComponent<Camera>();
}
// See if a tk2dCamera exists
if (viewCamera == null && tk2dCamera.Instance)
{
viewCamera = tk2dCamera.Instance.GetComponent<Camera>();
}
// ...otherwise, use the main camera
if (viewCamera == null)
{
viewCamera = Camera.main;
}
}
sprite = GetComponent<tk2dBaseSprite>();
// Further tests for sprite not being null aren't necessary, as the IDs will default to -1 in that case. Testing them will be sufficient
if (sprite)
{
// Change this to use animated sprites if necessary
// Same concept here, lookup Ids and call Play(xxx) instead of .spriteId = xxx
UpdateSpriteIds();
}
if (GetComponent<Collider>() == null)
{
BoxCollider newCollider = gameObject.AddComponent<BoxCollider>();
Vector3 colliderSize = newCollider.size;
colliderSize.z = 0.2f;
newCollider.size = colliderSize;
}
if ((buttonDownSound != null || buttonPressedSound != null || buttonUpSound != null) &&
GetComponent<AudioSource>() == null)
{
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.playOnAwake = false;
}
}
/// <summary>
/// Call this when the sprite names have changed
/// </summary>
public void UpdateSpriteIds()
{
buttonDownSpriteId = (buttonDownSprite.Length > 0)?sprite.GetSpriteIdByName(buttonDownSprite):-1;
buttonUpSpriteId = (buttonUpSprite.Length > 0)?sprite.GetSpriteIdByName(buttonUpSprite):-1;
buttonPressedSpriteId = (buttonPressedSprite.Length > 0)?sprite.GetSpriteIdByName(buttonPressedSprite):-1;
}
// Modify this to suit your audio solution
// In our case, we have a global audio manager to play one shot sounds and pool them
void PlaySound(AudioClip source)
{
if (GetComponent<AudioSource>() && source)
{
GetComponent<AudioSource>().PlayOneShot(source);
}
}
IEnumerator coScale(Vector3 defaultScale, float startScale, float endScale)
{
float t0 = Time.realtimeSinceStartup;
Vector3 scale = defaultScale;
float s = 0.0f;
while (s < scaleTime)
{
float t = Mathf.Clamp01(s / scaleTime);
float scl = Mathf.Lerp(startScale, endScale, t);
scale = defaultScale * scl;
transform.localScale = scale;
yield return 0;
s = (Time.realtimeSinceStartup - t0);
}
transform.localScale = defaultScale * endScale;
}
IEnumerator LocalWaitForSeconds(float seconds)
{
float t0 = Time.realtimeSinceStartup;
float s = 0.0f;
while (s < seconds)
{
yield return 0;
s = (Time.realtimeSinceStartup - t0);
}
}
IEnumerator coHandleButtonPress(int fingerId)
{
buttonDown = true; // inhibit processing in Update()
bool buttonPressed = true; // the button is currently being pressed
Vector3 defaultScale = transform.localScale;
// Button has been pressed for the first time, cursor/finger is still on it
if (targetScale != 1.0f)
{
// Only do this when the scale is actually enabled, to save one frame of latency when not needed
yield return StartCoroutine( coScale(defaultScale, 1.0f, targetScale) );
}
PlaySound(buttonDownSound);
if (buttonDownSpriteId != -1)
sprite.spriteId = buttonDownSpriteId;
if (ButtonDownEvent != null)
ButtonDownEvent(this);
while (true)
{
Vector3 cursorPosition = Vector3.zero;
bool cursorActive = true;
// slightly akward arrangement to keep exact backwards compatibility
#if !UNITY_FLASH
if (fingerId != -1)
{
bool found = false;
for (int i = 0; i < Input.touchCount; ++i)
{
Touch touch = Input.GetTouch(i);
if (touch.fingerId == fingerId)
{
if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
break; // treat as not found
cursorPosition = touch.position;
found = true;
}
}
if (!found) cursorActive = false;
}
else
#endif
{
if (!Input.GetMouseButton(0))
cursorActive = false;
cursorPosition = Input.mousePosition;
}
// user is no longer pressing mouse or no longer touching button
if (!cursorActive)
break;
Ray ray = viewCamera.ScreenPointToRay(cursorPosition);
RaycastHit hitInfo;
bool colliderHit = GetComponent<Collider>().Raycast(ray, out hitInfo, Mathf.Infinity);
if (buttonPressed && !colliderHit)
{
if (targetScale != 1.0f)
{
// Finger is still on screen / button is still down, but the cursor has left the bounds of the button
yield return StartCoroutine( coScale(defaultScale, targetScale, 1.0f) );
}
PlaySound(buttonUpSound);
if (buttonUpSpriteId != -1)
sprite.spriteId = buttonUpSpriteId;
if (ButtonUpEvent != null)
ButtonUpEvent(this);
buttonPressed = false;
}
else if (!buttonPressed & colliderHit)
{
if (targetScale != 1.0f)
{
// Cursor had left the bounds before, but now has come back in
yield return StartCoroutine( coScale(defaultScale, 1.0f, targetScale) );
}
PlaySound(buttonDownSound);
if (buttonDownSpriteId != -1)
sprite.spriteId = buttonDownSpriteId;
if (ButtonDownEvent != null)
ButtonDownEvent(this);
buttonPressed = true;
}
if (buttonPressed && ButtonAutoFireEvent != null)
{
ButtonAutoFireEvent(this);
}
yield return 0;
}
if (buttonPressed)
{
if (targetScale != 1.0f)
{
// Handle case when cursor was in bounds when the button was released / finger lifted
yield return StartCoroutine( coScale(defaultScale, targetScale, 1.0f) );
}
PlaySound(buttonPressedSound);
if (buttonPressedSpriteId != -1)
sprite.spriteId = buttonPressedSpriteId;
if (targetObject)
{
targetObject.SendMessage(messageName);
}
if (ButtonUpEvent != null)
ButtonUpEvent(this);
if (ButtonPressedEvent != null)
ButtonPressedEvent(this);
// Button may have been deactivated in ButtonPressed / Up event
// Don't wait in that case
#if UNITY_3_5
if (gameObject.active)
#else
if (gameObject.activeInHierarchy)
#endif
{
yield return StartCoroutine(LocalWaitForSeconds(pressedWaitTime));
}
if (buttonUpSpriteId != -1)
sprite.spriteId = buttonUpSpriteId;
}
buttonDown = false;
}
// Update is called once per frame
void Update ()
{
if (buttonDown) // only need to process if button isn't down
return;
#if !UNITY_FLASH
bool detected = false;
if (Input.multiTouchEnabled)
{
for (int i = 0; i < Input.touchCount; ++i)
{
Touch touch = Input.GetTouch(i);
if (touch.phase != TouchPhase.Began) continue;
Ray ray = viewCamera.ScreenPointToRay(touch.position);
RaycastHit hitInfo;
if (GetComponent<Collider>().Raycast(ray, out hitInfo, 1.0e8f))
{
if (!Physics.Raycast(ray, hitInfo.distance - 0.01f))
{
StartCoroutine(coHandleButtonPress(touch.fingerId));
detected = true;
break; // only one finger on a buton, please.
}
}
}
}
if (!detected)
#endif
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (GetComponent<Collider>().Raycast(ray, out hitInfo, 1.0e8f))
{
if (!Physics.Raycast(ray, hitInfo.distance - 0.01f))
StartCoroutine(coHandleButtonPress(-1));
}
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Win32;
namespace Microsoft.PythonTools.Profiling {
using Infrastructure;
using IServiceProvider = System.IServiceProvider;
/// <summary>
/// Represents an individual profiling session. We have nodes:
/// 0 - the configuration for what to profile
/// 1 - a folder, sessions that have been run
/// 2+ - the sessions themselves.
///
/// This looks like:
/// Root
/// Target
/// Sessions
/// Session #1
/// Session #2
/// </summary>
class SessionNode : BaseHierarchyNode, IVsHierarchyDeleteHandler, IVsPersistHierarchyItem {
private readonly string _filename;
private readonly uint _docCookie;
internal bool _isDirty, _neverSaved;
private bool _isReportsExpanded;
private readonly SessionsNode _parent;
internal readonly IServiceProvider _serviceProvider;
private ProfilingTarget _target;
private AutomationSession _automationSession;
internal readonly uint ItemId;
//private const int ConfigItemId = 0;
private const int ReportsItemId = 1;
internal const uint StartingReportId = 2;
public SessionNode(IServiceProvider serviceProvider, SessionsNode parent, ProfilingTarget target, string filename) {
_serviceProvider = serviceProvider;
_parent = parent;
_target = target;
_filename = filename;
// Register this with the running document table. This will prompt
// for save when the file is dirty and by responding to GetProperty
// for VSHPROPID_ItemDocCookie we will support Ctrl-S when one of
// our files is dirty.
// http://msdn.microsoft.com/en-us/library/bb164600(VS.80).aspx
var rdt = (IVsRunningDocumentTable)_serviceProvider.GetService(typeof(SVsRunningDocumentTable));
Debug.Assert(rdt != null, "_serviceProvider has no RDT service");
uint cookie;
IntPtr punkDocData = Marshal.GetIUnknownForObject(this);
try {
ErrorHandler.ThrowOnFailure(rdt.RegisterAndLockDocument(
(uint)(_VSRDTFLAGS.RDT_VirtualDocument | _VSRDTFLAGS.RDT_EditLock | _VSRDTFLAGS.RDT_CanBuildFromMemory),
filename,
this,
VSConstants.VSITEMID_ROOT,
punkDocData,
out cookie
));
} finally {
if (punkDocData != IntPtr.Zero) {
Marshal.Release(punkDocData);
}
}
_docCookie = cookie;
ItemId = parent._sessionsCollection.Add(this);
}
public IPythonProfileSession GetAutomationObject() {
if (_automationSession == null) {
_automationSession = new AutomationSession(this);
}
return _automationSession;
}
public SortedDictionary<uint, Report> Reports {
get {
if (_target.Reports == null) {
_target.Reports = new Reports();
}
if (_target.Reports.AllReports == null) {
_target.Reports.AllReports = new SortedDictionary<uint, Report>();
}
return _target.Reports.AllReports;
}
}
public string Caption {
get {
string name = Name;
if (_isDirty) {
return Strings.CaptionDirty.FormatUI(name);
}
return name;
}
}
public ProfilingTarget Target {
get {
return _target;
}
}
public override int SetProperty(uint itemid, int propid, object var) {
var prop = (__VSHPROPID)propid;
switch (prop) {
case __VSHPROPID.VSHPROPID_Expanded:
if (itemid == ReportsItemId) {
_isReportsExpanded = Convert.ToBoolean(var);
break;
}
break;
}
return base.SetProperty(itemid, propid, var);
}
public override int GetProperty(uint itemid, int propid, out object pvar) {
// GetProperty is called many many times for this particular property
pvar = null;
var prop = (__VSHPROPID)propid;
switch (prop) {
case __VSHPROPID.VSHPROPID_Parent:
if (itemid == ReportsItemId) {
pvar = VSConstants.VSITEMID_ROOT;
} else if (IsReportItem(itemid)) {
pvar = ReportsItemId;
}
break;
case __VSHPROPID.VSHPROPID_FirstChild:
if (itemid == VSConstants.VSITEMID_ROOT) {
pvar = ReportsItemId;
} else if (itemid == ReportsItemId && Reports.Count > 0) {
pvar = Reports.First().Key;
} else {
pvar = VSConstants.VSITEMID_NIL;
}
break;
case __VSHPROPID.VSHPROPID_NextSibling:
pvar = VSConstants.VSITEMID_NIL;
if (IsReportItem(itemid)) {
var items = Reports.Keys.ToArray();
for (int i = 0; i < items.Length; i++) {
if (items[i] > (int)itemid) {
pvar = itemid + 1;
break;
}
}
}
break;
case __VSHPROPID.VSHPROPID_ItemDocCookie:
if (itemid == VSConstants.VSITEMID_ROOT) {
pvar = (int)_docCookie;
}
break;
case __VSHPROPID.VSHPROPID_Expandable:
if (itemid == VSConstants.VSITEMID_ROOT) {
pvar = true;
} else if (itemid == ReportsItemId && Reports.Count > 0) {
pvar = true;
} else {
pvar = false;
}
break;
case __VSHPROPID.VSHPROPID_ExpandByDefault:
pvar = true;
break;
case __VSHPROPID.VSHPROPID_IconImgList:
case __VSHPROPID.VSHPROPID_OpenFolderIconHandle:
pvar = (int)SessionsNode._imageList.Handle;
break;
case __VSHPROPID.VSHPROPID_IconIndex:
case __VSHPROPID.VSHPROPID_OpenFolderIconIndex:
if (itemid == ReportsItemId) {
if (_isReportsExpanded) {
pvar = (int)TreeViewIconIndex.OpenFolder;
} else {
pvar = (int)TreeViewIconIndex.CloseFolder;
}
} else if (IsReportItem(itemid)) {
pvar = (int)TreeViewIconIndex.GreenNotebook;
}
break;
case __VSHPROPID.VSHPROPID_Caption:
if (itemid == VSConstants.VSITEMID_ROOT) {
pvar = Caption;
} else if (itemid == ReportsItemId) {
pvar = "Reports";
} else if (IsReportItem(itemid)) {
pvar = Path.GetFileNameWithoutExtension(GetReport(itemid).Filename);
}
break;
case __VSHPROPID.VSHPROPID_ParentHierarchy:
if (itemid == VSConstants.VSITEMID_ROOT) {
pvar = _parent as IVsHierarchy;
}
break;
}
if (pvar != null)
return VSConstants.S_OK;
return VSConstants.DISP_E_MEMBERNOTFOUND;
}
public override int ExecCommand(uint itemid, ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (pguidCmdGroup == VsMenus.guidVsUIHierarchyWindowCmds) {
switch ((VSConstants.VsUIHierarchyWindowCmdIds)nCmdID) {
case VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_DoubleClick:
case VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_EnterKey:
if (itemid == VSConstants.VSITEMID_ROOT) {
OpenTargetProperties();
// S_FALSE: don't process the double click to expand the item
return VSConstants.S_FALSE;
} else if (IsReportItem(itemid)) {
OpenProfile(itemid);
}
return (int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED;
case VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_RightClick:
int? ctxMenu = null;
if (itemid == VSConstants.VSITEMID_ROOT) {
ctxMenu = (int)PkgCmdIDList.menuIdPerfContext;
} else if (itemid == ReportsItemId) {
ctxMenu = (int)PkgCmdIDList.menuIdPerfReportsContext;
} else if (IsReportItem(itemid)) {
ctxMenu = (int)PkgCmdIDList.menuIdPerfSingleReportContext;
}
if (ctxMenu != null) {
var uishell = (IVsUIShell)_serviceProvider.GetService(typeof(SVsUIShell));
if (uishell != null) {
var pt = System.Windows.Forms.Cursor.Position;
var pnts = new[] { new POINTS { x = (short)pt.X, y = (short)pt.Y } };
var guid = GuidList.guidPythonProfilingCmdSet;
int hr = uishell.ShowContextMenu(
0,
ref guid,
ctxMenu.Value,
pnts,
new ContextCommandTarget(this, itemid));
ErrorHandler.ThrowOnFailure(hr);
}
}
break;
}
}
return base.ExecCommand(itemid, ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
internal ProfilingTarget OpenTargetProperties() {
var targetView = new ProfilingTargetView(_serviceProvider, _target);
var dialog = new LaunchProfiling(_serviceProvider, targetView);
var res = dialog.ShowModal() ?? false;
if (res && targetView.IsValid) {
var target = targetView.GetTarget();
if (target != null && !ProfilingTarget.IsSame(target, _target)) {
_target = target;
MarkDirty();
return _target;
}
}
return null;
}
private void OpenProfile(uint itemid) {
var item = GetReport(itemid);
if (!File.Exists(item.Filename)) {
MessageBox.Show(Strings.PerformanceReportNotFound.FormatUI(item.Filename), Strings.ProductTitle);
} else {
var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));
dte.ItemOperations.OpenFile(item.Filename);
}
}
class ContextCommandTarget : IOleCommandTarget {
private readonly SessionNode _node;
private readonly uint _itemid;
public ContextCommandTarget(SessionNode node, uint itemid) {
_node = node;
_itemid = itemid;
}
#region IOleCommandTarget Members
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (pguidCmdGroup == GuidList.guidPythonProfilingCmdSet) {
switch (nCmdID) {
case PkgCmdIDList.cmdidOpenReport:
_node.OpenProfile(_itemid);
return VSConstants.S_OK;
case PkgCmdIDList.cmdidPerfCtxSetAsCurrent:
_node._parent.SetActiveSession(_node);
return VSConstants.S_OK;
case PkgCmdIDList.cmdidPerfCtxStartProfiling:
_node.StartProfiling();
return VSConstants.S_OK;
case PkgCmdIDList.cmdidReportsCompareReports: {
CompareReportsView compareView;
if (_node.IsReportItem(_itemid)) {
var report = _node.GetReport(_itemid);
compareView = new CompareReportsView(report.Filename);
} else {
compareView = new CompareReportsView();
}
var dialog = new CompareReportsWindow(compareView);
var res = dialog.ShowModal() ?? false;
if (res && compareView.IsValid) {
IVsUIShellOpenDocument sod = _node._serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
if (sod == null) {
return VSConstants.E_FAIL;
}
Microsoft.VisualStudio.Shell.Interop.IVsWindowFrame frame = null;
Guid guid = new Guid("{9C710F59-984F-4B83-B781-B6356C363B96}"); // performance diff guid
Guid guidNull = Guid.Empty;
sod.OpenSpecificEditor(
(uint)(_VSRDTFLAGS.RDT_CantSave | _VSRDTFLAGS.RDT_DontAddToMRU | _VSRDTFLAGS.RDT_NonCreatable | _VSRDTFLAGS.RDT_NoLock),
compareView.GetComparisonUri(),
ref guid,
null,
ref guidNull,
Strings.PerformanceComparisonTitle,
_node,
_itemid,
IntPtr.Zero,
null,
out frame
);
if (frame != null) {
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(frame.Show());
}
}
return VSConstants.S_OK;
}
case PkgCmdIDList.cmdidReportsAddReport: {
var dialog = new OpenFileDialog();
dialog.Filter = PythonProfilingPackage.PerformanceFileFilter;
dialog.CheckFileExists = true;
var res = dialog.ShowDialog() ?? false;
if (res) {
_node.AddProfile(dialog.FileName);
}
return VSConstants.S_OK;
}
}
} else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) {
switch((VSConstants.VSStd97CmdID)nCmdID) {
case VSConstants.VSStd97CmdID.PropSheetOrProperties:
_node.OpenTargetProperties();
return VSConstants.S_OK;
}
}
return (int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED;
}
public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) {
return (int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED;
}
#endregion
}
internal void MarkDirty() {
_isDirty = true;
OnPropertyChanged(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Caption, 0);
}
public override int QueryStatusCommand(uint itemid, ref Guid pguidCmdGroup, uint cCmds, VisualStudio.OLE.Interop.OLECMD[] prgCmds, IntPtr pCmdText) {
return base.QueryStatusCommand(itemid, ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
private bool IsReportItem(uint itemid) {
return itemid >= StartingReportId && Reports.ContainsKey(itemid);
}
private Report GetReport(uint itemid) {
return Reports[itemid];
}
public void AddProfile(string filename) {
if (_target.Reports == null) {
_target.Reports = new Reports(new[] { new Report(filename) });
} else {
if (_target.Reports.Report == null) {
_target.Reports.Report = new Report[0];
}
uint prevSibling, newId;
if (Reports.Count > 0) {
prevSibling = (uint)Reports.Last().Key;
newId = prevSibling + 1;
} else {
prevSibling = VSConstants.VSITEMID_NIL;
newId = StartingReportId;
}
Reports[newId] = new Report(filename);
OnItemAdded(
ReportsItemId,
prevSibling,
newId
);
}
MarkDirty();
}
public void Save(VSSAVEFLAGS flags, out int pfCanceled) {
pfCanceled = 0;
switch (flags) {
case VSSAVEFLAGS.VSSAVE_Save:
if (_neverSaved) {
goto case VSSAVEFLAGS.VSSAVE_SaveAs;
}
Save(_filename);
break;
case VSSAVEFLAGS.VSSAVE_SaveAs:
case VSSAVEFLAGS.VSSAVE_SaveCopyAs:
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.FileName = _filename;
if (saveDialog.ShowDialog() == true) {
Save(saveDialog.FileName);
_neverSaved = false;
} else {
pfCanceled = 1;
}
break;
}
}
internal void Removed() {
IVsRunningDocumentTable rdt = _serviceProvider.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)_VSRDTFLAGS.RDT_EditLock, _docCookie));
}
#region IVsHierarchyDeleteHandler Members
public int DeleteItem(uint dwDelItemOp, uint itemid) {
Debug.Assert(_target.Reports != null && _target.Reports.Report != null && _target.Reports.Report.Length > 0);
var report = GetReport(itemid);
Reports.Remove(itemid);
OnItemDeleted(itemid);
OnInvalidateItems(ReportsItemId);
if (File.Exists(report.Filename) && dwDelItemOp == (uint)__VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) {
// close the file if it's open before deleting it...
var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));
if (dte.ItemOperations.IsFileOpen(report.Filename)) {
var doc = dte.Documents.Item(report.Filename);
doc.Close();
}
File.Delete(report.Filename);
}
return VSConstants.S_OK;
}
public int QueryDeleteItem(uint dwDelItemOp, uint itemid, out int pfCanDelete) {
if (IsReportItem(itemid)) {
pfCanDelete = 1;
return VSConstants.S_OK;
}
pfCanDelete = 0;
return VSConstants.S_OK;
}
#endregion
internal void StartProfiling(bool openReport = true) {
PythonProfilingPackage.Instance.StartProfiling(_target, this, openReport);
}
public void Save(string filename = null) {
if (filename == null) {
filename = _filename;
}
using (var stream = new FileStream(filename, FileMode.Create)) {
ProfilingTarget.Serializer.Serialize(
stream,
_target
);
_isDirty = false;
stream.Close();
OnPropertyChanged(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Caption, 0);
}
}
public string Filename { get { return _filename; } }
public string Name {
get {
return Path.GetFileNameWithoutExtension(_filename);
}
}
public bool IsSaved {
get {
return !_isDirty && !_neverSaved;
}
}
#region IVsPersistHierarchyItem Members
public int IsItemDirty(uint itemid, IntPtr punkDocData, out int pfDirty) {
if (itemid == VSConstants.VSITEMID_ROOT) {
pfDirty = _isDirty ? 1 : 0;
return VSConstants.S_OK;
} else {
pfDirty = 0;
return VSConstants.E_FAIL;
}
}
public int SaveItem(VSSAVEFLAGS dwSave, string pszSilentSaveAsName, uint itemid, IntPtr punkDocData, out int pfCanceled) {
if (itemid == VSConstants.VSITEMID_ROOT) {
Save(dwSave, out pfCanceled);
return VSConstants.S_OK;
}
pfCanceled = 0;
return VSConstants.E_FAIL;
}
#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.Diagnostics;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using CURLcode = Interop.Http.CURLcode;
using CURLINFO = Interop.Http.CURLINFO;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private static class SslProvider
{
private static readonly Interop.Http.SslCtxCallback s_sslCtxCallback = SslCtxCallback;
private static readonly Interop.Ssl.AppVerifyCallback s_sslVerifyCallback = VerifyCertChain;
private static readonly Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1");
internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption)
{
EventSourceTrace("ClientCertificateOption: {0}", clientCertOption, easy:easy);
Debug.Assert(clientCertOption == ClientCertificateOption.Automatic || clientCertOption == ClientCertificateOption.Manual);
// Create a client certificate provider if client certs may be used.
X509Certificate2Collection clientCertificates = easy._handler._clientCertificates;
ClientCertificateProvider certProvider =
clientCertOption == ClientCertificateOption.Automatic ? new ClientCertificateProvider(null) : // automatic
clientCertificates?.Count > 0 ? new ClientCertificateProvider(clientCertificates) : // manual with certs
null; // manual without certs
IntPtr userPointer = IntPtr.Zero;
if (certProvider != null)
{
EventSourceTrace("Created certificate provider", easy:easy);
// The client cert provider needs to be passed through to the callback, and thus
// we create a GCHandle to keep it rooted. This handle needs to be cleaned up
// when the request has completed, and a simple and pay-for-play way to do that
// is by cleaning it up in a continuation off of the request.
userPointer = GCHandle.ToIntPtr(certProvider._gcHandle);
easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(), certProvider,
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
// Configure the options. Our best support is when targeting OpenSSL/1.0. For other backends,
// we fall back to a minimal amount of support, and may throw a PNSE based on the options requested.
if (CurlSslVersionDescription.IndexOf(Interop.Http.OpenSsl10Description, StringComparison.OrdinalIgnoreCase) != -1)
{
// Register the callback with libcurl. We need to register even if there's no user-provided
// server callback and even if there are no client certificates, because we support verifying
// server certificates against more than those known to OpenSSL.
SetSslOptionsForSupportedBackend(easy, certProvider, userPointer);
}
else
{
// Newer versions of OpenSSL, and other non-OpenSSL backends, do not currently support callbacks.
// That means we'll throw a PNSE if a callback is required.
SetSslOptionsForUnsupportedBackend(easy, certProvider);
}
}
private static void SetSslOptionsForSupportedBackend(EasyRequest easy, ClientCertificateProvider certProvider, IntPtr userPointer)
{
CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer);
EventSourceTrace("Callback registration result: {0}", answer, easy: easy);
switch (answer)
{
case CURLcode.CURLE_OK:
// We successfully registered. If we'll be invoking a user-provided callback to verify the server
// certificate as part of that, disable libcurl's verification of the host name; we need to get
// the callback from libcurl even if the host name doesn't match, so we take on the responsibility
// of doing the host name match in the callback prior to invoking the user's delegate.
if (easy._handler.ServerCertificateValidationCallback != null)
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0);
// But don't change the CURLOPT_SSL_VERIFYPEER setting, as setting it to 0 will
// cause SSL and libcurl to ignore the result of the server callback.
}
// The allowed SSL protocols will be set in the configuration callback.
break;
case CURLcode.CURLE_UNKNOWN_OPTION: // Curl 7.38 and prior
case CURLcode.CURLE_NOT_BUILT_IN: // Curl 7.39 and later
SetSslOptionsForUnsupportedBackend(easy, certProvider);
break;
default:
ThrowIfCURLEError(answer);
break;
}
}
private static void SetSslOptionsForUnsupportedBackend(EasyRequest easy, ClientCertificateProvider certProvider)
{
if (certProvider != null)
{
throw new PlatformNotSupportedException(SR.Format(SR.net_http_libcurl_clientcerts_notsupported, CurlVersionDescription, CurlSslVersionDescription));
}
if (easy._handler.CheckCertificateRevocationList)
{
throw new PlatformNotSupportedException(SR.Format(SR.net_http_libcurl_revocation_notsupported, CurlVersionDescription, CurlSslVersionDescription));
}
if (easy._handler.ServerCertificateValidationCallback != null)
{
if (easy.ServerCertificateValidationCallbackAcceptsAll)
{
EventSourceTrace("Warning: Disabling peer and host verification per {0}", nameof(HttpClientHandler.DangerousAcceptAnyServerCertificateValidator), easy: easy);
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYPEER, 0);
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0);
}
else
{
throw new PlatformNotSupportedException(SR.Format(SR.net_http_libcurl_callback_notsupported, CurlVersionDescription, CurlSslVersionDescription));
}
}
// In case of defaults configure the allowed SSL protocols.
SetSslVersion(easy);
}
private static void SetSslVersion(EasyRequest easy, IntPtr sslCtx = default(IntPtr))
{
// Get the requested protocols.
SslProtocols protocols = easy._handler.SslProtocols;
if (protocols == SslProtocols.None)
{
// Let libcurl use its defaults if None is set.
return;
}
// We explicitly disallow choosing SSL2/3. Make sure they were filtered out.
Debug.Assert((protocols & ~SecurityProtocol.AllowedSecurityProtocols) == 0,
"Disallowed protocols should have been filtered out.");
// libcurl supports options for either enabling all of the TLS1.* protocols or enabling
// just one of them; it doesn't currently support enabling two of the three, e.g. you can't
// pick TLS1.1 and TLS1.2 but not TLS1.0, but you can select just TLS1.2.
Interop.Http.CurlSslVersion curlSslVersion;
switch (protocols)
{
case SslProtocols.Tls:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_0;
break;
case SslProtocols.Tls11:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_1;
break;
case SslProtocols.Tls12:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_2;
break;
case SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1;
break;
default:
throw new NotSupportedException(SR.net_securityprotocolnotsupported);
}
try
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)curlSslVersion);
}
catch (CurlException e) when (e.HResult == (int)CURLcode.CURLE_UNKNOWN_OPTION)
{
throw new NotSupportedException(SR.net_securityprotocolnotsupported, e);
}
}
private static CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer)
{
EasyRequest easy;
if (!TryGetEasyRequest(curl, out easy))
{
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
EventSourceTrace(null, easy: easy);
// Configure the SSL protocols allowed.
SslProtocols protocols = easy._handler.SslProtocols;
if (protocols == SslProtocols.None)
{
// If None is selected, let OpenSSL use its defaults, but with SSL2/3 explicitly disabled.
// Since the shim/OpenSSL work on a disabling system, where any protocols for which bits aren't
// set are disabled, we set all of the bits other than those we want disabled.
#pragma warning disable 0618 // the enum values are obsolete
protocols = ~(SslProtocols.Ssl2 | SslProtocols.Ssl3);
#pragma warning restore 0618
}
Interop.Ssl.SetProtocolOptions(sslCtx, protocols);
// Configure the SSL server certificate verification callback.
Interop.Ssl.SslCtxSetCertVerifyCallback(sslCtx, s_sslVerifyCallback, curl);
// If a client certificate provider was provided, also configure the client certificate callback.
if (userPointer != IntPtr.Zero)
{
try
{
// Provider is passed in via a GCHandle. Get the provider, which contains
// the client certificate callback delegate.
GCHandle handle = GCHandle.FromIntPtr(userPointer);
ClientCertificateProvider provider = (ClientCertificateProvider)handle.Target;
if (provider == null)
{
Debug.Fail($"Expected non-null provider in {nameof(SslCtxCallback)}");
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
// Register the callback.
Interop.Ssl.SslCtxSetClientCertCallback(sslCtx, provider._callback);
EventSourceTrace("Registered client certificate callback.", easy: easy);
}
catch (Exception e)
{
Debug.Fail($"Exception in {nameof(SslCtxCallback)}", e.ToString());
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
}
return CURLcode.CURLE_OK;
}
private static bool TryGetEasyRequest(IntPtr curlPtr, out EasyRequest easy)
{
Debug.Assert(curlPtr != IntPtr.Zero, "curlPtr is not null");
IntPtr gcHandlePtr;
CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(curlPtr, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
if (getInfoResult == CURLcode.CURLE_OK)
{
return MultiAgent.TryGetEasyRequestFromGCHandle(gcHandlePtr, out easy);
}
Debug.Fail($"Failed to get info on a completing easy handle: {getInfoResult}");
easy = null;
return false;
}
private static int VerifyCertChain(IntPtr storeCtxPtr, IntPtr curlPtr)
{
EasyRequest easy;
if (!TryGetEasyRequest(curlPtr, out easy))
{
EventSourceTrace("Could not find associated easy request: {0}", curlPtr);
return 0;
}
using (var storeCtx = new SafeX509StoreCtxHandle(storeCtxPtr, ownsHandle: false))
{
IntPtr leafCertPtr = Interop.Crypto.X509StoreCtxGetTargetCert(storeCtx);
if (IntPtr.Zero == leafCertPtr)
{
EventSourceTrace("Invalid certificate pointer", easy: easy);
return 0;
}
using (X509Certificate2 leafCert = new X509Certificate2(leafCertPtr))
{
// We need to respect the user's server validation callback if there is one. If there isn't one,
// we can start by first trying to use OpenSSL's verification, though only if CRL checking is disabled,
// as OpenSSL doesn't do that.
if (easy._handler.ServerCertificateValidationCallback == null &&
!easy._handler.CheckCertificateRevocationList)
{
// Start by using the default verification provided directly by OpenSSL.
// If it succeeds in verifying the cert chain, we're done. Employing this instead of
// our custom implementation will need to be revisited if we ever decide to introduce a
// "disallowed" store that enables users to "untrust" certs the system trusts.
int sslResult = Interop.Crypto.X509VerifyCert(storeCtx);
if (sslResult == 1)
{
return 1;
}
// X509_verify_cert can return < 0 in the case of programmer error
Debug.Assert(sslResult == 0, "Unexpected error from X509_verify_cert: " + sslResult);
}
// Either OpenSSL verification failed, or there was a server validation callback.
// Either way, fall back to manual and more expensive verification that includes
// checking the user's certs (not just the system store ones as OpenSSL does).
X509Certificate2[] otherCerts;
int otherCertsCount = 0;
bool success;
using (X509Chain chain = new X509Chain())
{
chain.ChainPolicy.RevocationMode = easy._handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
using (SafeSharedX509StackHandle extraStack = Interop.Crypto.X509StoreCtxGetSharedUntrusted(storeCtx))
{
if (extraStack.IsInvalid)
{
otherCerts = Array.Empty<X509Certificate2>();
}
else
{
int extraSize = Interop.Crypto.GetX509StackFieldCount(extraStack);
otherCerts = new X509Certificate2[extraSize];
for (int i = 0; i < extraSize; i++)
{
IntPtr certPtr = Interop.Crypto.GetX509StackField(extraStack, i);
if (certPtr != IntPtr.Zero)
{
X509Certificate2 cert = new X509Certificate2(certPtr);
otherCerts[otherCertsCount++] = cert;
chain.ChainPolicy.ExtraStore.Add(cert);
}
}
}
}
var serverCallback = easy._handler._serverCertificateValidationCallback;
if (serverCallback == null)
{
SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
checkCertName: false, hostName: null); // libcurl already verifies the host name
success = errors == SslPolicyErrors.None;
}
else
{
// Authenticate the remote party: (e.g. when operating in client mode, authenticate the server).
chain.ChainPolicy.ApplicationPolicy.Add(s_serverAuthOid);
SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
checkCertName: true, hostName: easy._requestMessage.RequestUri.Host); // we disabled automatic host verification, so we do it here
try
{
success = serverCallback(easy._requestMessage, leafCert, chain, errors);
}
catch (Exception exc)
{
EventSourceTrace("Server validation callback threw exception: {0}", exc, easy: easy);
easy.FailRequest(exc);
success = false;
}
}
}
for (int i = 0; i < otherCertsCount; i++)
{
otherCerts[i].Dispose();
}
return success ? 1 : 0;
}
}
}
}
}
}
| |
//
// Healthstone System Monitor - (C) 2015-2018 Patrick Lambert - https://dendory.net
//
using System;
using System.Windows;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Management;
using System.ServiceProcess;
using System.Timers;
using System.Diagnostics;
using System.Threading;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Data.Odbc;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
using Microsoft.Win32;
[assembly: AssemblyTitle("Healthstone System Monitor")]
[assembly: AssemblyCopyright("(C) 2015-2018 Patrick Lambert")]
[assembly: AssemblyFileVersion("2.1.4.0")]
namespace Healthstone
{
public class Program : System.ServiceProcess.ServiceBase // Inherit Services
{
static System.Timers.Timer hstimer;
public Dictionary<string, Dictionary<string, string>> cfg;
public string output;
public int alarms;
public WebClient wc;
public WebProxy wp;
public ManagementObjectSearcher wmi;
public RegistryKey rkey;
public PerformanceCounter cpu;
public int port;
public string localusers;
public Program() // Setting service name
{
this.ServiceName = "Healthstone";
}
static void Main(string[] args) // Required elements for a service program
{
Console.WriteLine("Healthstone System Monitor - http://healthstone.ca");
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[] { new Program() };
ServiceBase.Run(servicesToRun);
}
protected override void OnStart(string[] args) // Starting service
{
cfg = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> section = new Dictionary<string, string>();
rkey = Registry.LocalMachine.OpenSubKey("Software\\Healthstone");
if(rkey == null) { EventLog.WriteEntry("Healthstone", "Registry hive missing. Please re-install Healthstone.", EventLogEntryType.Error); System.Environment.Exit(1); }
if(rkey.GetValue("debug") == null) { section.Add("debug", "true"); }
else { section.Add("debug", (string)rkey.GetValue("debug")); }
if(rkey.GetValue("interval") == null) { section.Add("interval", "30"); }
else { section.Add("interval", (string)rkey.GetValue("interval")); }
if(rkey.GetValue("verbose") == null) { section.Add("verbose", "false"); }
else { section.Add("verbose", (string)rkey.GetValue("verbose")); }
if(rkey.GetValue("dashboard") == null) { EventLog.WriteEntry("Healthstone", "Registry entry missing: dashboard", EventLogEntryType.Error); System.Environment.Exit(1); }
else { section.Add("dashboard", (string)rkey.GetValue("dashboard")); }
if(rkey.GetValue("template") == null) { EventLog.WriteEntry("Healthstone", "Registry entry missing: template", EventLogEntryType.Error); System.Environment.Exit(1); }
else { section.Add("template", (string)rkey.GetValue("template")); }
cfg.Add("general", section);
if(rkey.GetValue("proxy") != null) wp = new WebProxy((string)rkey.GetValue("proxy"));
if(rkey.GetValue("tlsonly") != null)
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
if(Int32.Parse(cfg["general"]["interval"]) < 10) // Since this may take a few seconds to run, disallow running it more than once every 10 secs
{
EventLog.WriteEntry("Healthstone", "Configuration error: Invalid interval value (must be above 10 seconds)", EventLogEntryType.Error);
base.Stop();
}
hstimer = new System.Timers.Timer(Int32.Parse(cfg["general"]["interval"]) * 1000); // Set a timer for the value in Interval
hstimer.Elapsed += new System.Timers.ElapsedEventHandler(ParseSections); // Call ParseSections after the timer is up
hstimer.Start();
}
protected override void OnStop() // Stopping the service
{
hstimer.Stop();
}
private string DateToString(string s) // Convert .NET WMI date to DateTime and return as a string
{
int year = int.Parse(s.Substring(0, 4));
int month = int.Parse(s.Substring(4, 2));
int day = int.Parse(s.Substring(6, 2));
int hour = int.Parse(s.Substring(8, 2));
int minute = int.Parse(s.Substring(10, 2));
int second = int.Parse(s.Substring(12, 2));
DateTime date = new DateTime(year, month, day, hour, minute, second);
return date.ToString();
}
private Int32 DateToHours(string s) // Convert .NET WMI date to DateTime then return number of hours between now and then
{
int year = int.Parse(s.Substring(0, 4));
int month = int.Parse(s.Substring(4, 2));
int day = int.Parse(s.Substring(6, 2));
int hour = int.Parse(s.Substring(8, 2));
int minute = int.Parse(s.Substring(10, 2));
int second = int.Parse(s.Substring(12, 2));
DateTime date1 = new DateTime(year, month, day, hour, minute, second);
DateTime date2 = DateTime.Now;
return (int)((date2 - date1).TotalHours);
}
static uint SwapEndianness(ulong x) // Swap Endian value for NTP query
{
return (uint) (((x & 0x000000ff) << 24) + ((x & 0x0000ff00) << 8) + ((x & 0x00ff0000) >> 8) + ((x & 0xff000000) >> 24));
}
private void ParseNewCfg(string data) // Parse config data retrieved from dashboard
{
string dashboard = cfg["general"]["dashboard"];
string template = cfg["general"]["template"];
cfg = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> section = new Dictionary<string, string>();
string sectionName = null;
string line = "";
int index = -1;
try
{
data.Replace("\r", "");
data.Replace("\t", " ");
string[] stringSeparators = new string[] { "\n" };
string[] lines = data.Split(stringSeparators, StringSplitOptions.None);
foreach(string l in lines)
{
line = l.Trim();
if(line.Length > 0 && line[0] != '#') // Avoid empty lines and comments
{
index = line.IndexOf('#');
if(index > 0) { line = line.Substring(0, index); } // Catch same-line comments
if(line[0] == '[') // New section
{
if(sectionName != null)
{
cfg.Add(sectionName.ToLower(), section);
section = new Dictionary<string, string>();
}
sectionName = line.Trim('[').Trim(']');
}
else
{
index = line.IndexOf(':');
if(index > 0) { section.Add(line.ToLower().Substring(0, index).Trim(), line.ToLower().Substring(index + 1, line.Length - index - 1).Trim()); } // Assign key:value pairs to our cfg dictionary
}
}
}
if(sectionName != null)
{
cfg.Add(sectionName.ToLower(), section);
section = new Dictionary<string, string>();
}
}
catch (Exception e)
{
EventLog.WriteEntry("Healthstone", "Template error! Restoring default configuration: " + e, EventLogEntryType.Error);
cfg = new Dictionary<string, Dictionary<string, string>>();
section = new Dictionary<string, string>();
section.Add("debug", "true");
section.Add("interval", "30");
section.Add("verbose", "false");
cfg.Add("general", section);
}
cfg["general"]["dashboard"] = dashboard;
cfg["general"]["template"] = template;
}
private void ParseSections(object sender, System.Timers.ElapsedEventArgs hse) // Main checks loop
{
hstimer.Stop();
float curval = 0;
// Headers
alarms = 0;
output = "Healthstone checks: " + Environment.MachineName; // The output string contains the results from all checks
try // Get computer name
{
wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem");
foreach(ManagementObject items in wmi.Get())
{
output += " - " + items["Caption"] + " (" + items["OSArchitecture"] + ")";
}
}
catch (Exception e)
{
output += " - " + e;
alarms += 1;
}
output += " - " + cfg["general"]["template"] + "\n\n";
// Checks
if(cfg.ContainsKey("checkcpu")) // check cpu load
{
try
{
cpu = new PerformanceCounter();
cpu.CategoryName = "Processor";
cpu.CounterName = "% Processor Time";
cpu.InstanceName = "_Total";
float val1 = cpu.NextValue();
Thread.Sleep(500);
float val2 = cpu.NextValue();
Thread.Sleep(500);
float val3 = cpu.NextValue();
curval = Math.Max(val1, Math.Max(val2, val3));
if(curval > Int32.Parse(cfg["checkcpu"]["maximum"]))
{
output += "--> [CheckCPU] High CPU load: " + curval + "%\n";
alarms += 1;
}
else if(cfg["general"]["verbose"] == "true") { output += "[CheckCPU] CPU load: " + curval + "%\n"; }
}
catch (Exception e)
{
output += "[CheckCPU] Performance Counter failure: " + e + "\n";
alarms += 1;
}
}
if(cfg.ContainsKey("checkmemory")) // check free memory
{
try
{
wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem");
foreach(ManagementObject items in wmi.Get())
{
if((Int32.Parse(items["FreePhysicalMemory"].ToString()) / 1000) < Int32.Parse(cfg["checkmemory"]["minimum"]))
{
output += "--> [CheckMemory] Low physical memory: " + (Int32.Parse(items["FreePhysicalMemory"].ToString()) / 1000) + " MB.\n";
alarms += 1;
}
else if(cfg["general"]["verbose"] == "true") { output += "[CheckMemory] Free physical memory: " + (Int32.Parse(items["FreePhysicalMemory"].ToString()) / 1000) + " MB.\n"; }
}
}
catch (Exception e)
{
output += "--> [CheckMemory] WMI Query failure: " + e + "\n";
alarms += 1;
}
}
if(cfg.ContainsKey("checkprocesses")) // check processes
{
try
{
wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem");
foreach(ManagementObject items in wmi.Get())
{
if(Int32.Parse(items["NumberOfProcesses"].ToString()) > Int32.Parse(cfg["checkprocesses"]["maximum"]))
{
output += "--> [CheckProcesses] There are too many processes running: " + items["NumberOfProcesses"] + ".\n";
alarms += 1;
}
else if(Int32.Parse(items["NumberOfProcesses"].ToString()) < Int32.Parse(cfg["checkprocesses"]["minimum"]))
{
output += "--> [CheckProcesses] There are too few processes running: " + items["NumberOfProcesses"] + ".\n";
alarms += 1;
}
else if(cfg["general"]["verbose"] == "true") { output += "[CheckProcesses] " + items["NumberOfProcesses"] + " processes are running.\n"; }
}
wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process");
foreach(string pp in cfg["checkprocesses"]["include"].Split(' '))
{
string p = pp.Trim();
if(p != "")
{
bool found = false;
foreach(ManagementObject items in wmi.Get())
{
if(string.Compare(items["Caption"].ToString().ToLower(), p) == 0)
{
found = true;
}
}
if(!found)
{
output += "--> [CheckProcesses] Process in include list is not running: " + p + "\n";
alarms += 1;
}
}
}
wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process");
foreach(string pp in cfg["checkprocesses"]["exclude"].Split(' '))
{
string p = pp.Trim();
if(p != "")
{
bool found = false;
foreach(ManagementObject items in wmi.Get())
{
if(string.Compare(items["Caption"].ToString().ToLower(), p) == 0)
{
found = true;
}
}
if(found)
{
output += "--> [CheckProcesses] Process in exclude list is running: " + p + "\n";
alarms += 1;
}
}
}
}
catch (Exception e)
{
output += "--> [CheckProcesses] WMI Query failure: " + e + "\n";
alarms += 1;
}
}
if(cfg.ContainsKey("checkav")) // check for an anti virus
{
try
{
wmi = new ManagementObjectSearcher("root\\SecurityCenter2", "SELECT * FROM AntivirusProduct");
ManagementObjectCollection instances = wmi.Get();
if(instances.Count == 0)
{
output += "--> [CheckAV] No anti virus product installed.\n";
alarms += 1;
}
else
{
foreach(ManagementObject items in instances)
{
if(string.Compare(items["displayName"].ToString().ToLower(), cfg["checkav"]["require"]) != 0)
{
output += "--> [CheckAV] Wrong anti virus product: " + items["displayName"] + "\n";
alarms += 1;
}
else if(cfg["general"]["verbose"] == "true")
{
output += "[CheckAV] " + items["displayName"] + "\n";
}
}
}
}
catch (Exception e)
{
output += "--> [CheckAV] WMI Query failure: " + e + "\n";
alarms += 1;
}
}
if(cfg.ContainsKey("checkdiskspace")) // check disk space
{
try
{
wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_LogicalDisk");
foreach(ManagementObject items in wmi.Get())
{
if(items["FreeSpace"] != null && (cfg["checkdiskspace"]["onlysystemdisk"] != "true" || items["Caption"].ToString() == "C:"))
{
ulong freespace = (ulong)items["FreeSpace"] / 1000000;
if(freespace < UInt64.Parse(cfg["checkdiskspace"]["minimum"]) && freespace > 0)
{
output += "--> [CheckDiskSpace] Low free space on drive " + items["Caption"] + " " + freespace + " MB\n";
alarms += 1;
}
else if(cfg["general"]["verbose"] == "true") { output += "[CheckDiskSpace] Free space on drive " + items["Caption"] + " " + freespace + " MB\n"; }
}
}
}
catch (Exception e)
{
output += "--> [CheckDiskSpace] WMI Query failure: " + e + "\n";
alarms += 1;
}
}
if(cfg.ContainsKey("checkdomain")) // check domnain joined
{
try
{
string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
if(string.Compare(domain.ToLower(), cfg["checkdomain"]["domain"].ToLower()) != 0)
{
output += "--> [CheckDomain] System domain mismatch: " + domain + "\n";
alarms += 1;
}
else if(cfg["general"]["verbose"] == "true") { output += "[CheckDomain] System domain: " + domain + "\n"; }
}
catch (Exception e)
{
output += "--> [CheckDomain] Domain query failure: " + e + "\n";
alarms += 1;
}
}
if(cfg.ContainsKey("checkupdates")) // check Windows updates
{
try
{
string[] WUstatus = new string[6] {"Unknown", "Disabled", "Manual", "Manual", "Automatic", "Unknown"};
rkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update");
string curWU = rkey.GetValue("AUOptions").ToString();
if(string.Compare(WUstatus[Int32.Parse(curWU)].ToLower(), cfg["checkupdates"]["status"]) != 0)
{
output += "--> [CheckUpdates] Windows Updates are set to: " + WUstatus[Int32.Parse(curWU)] + ".\n";
alarms += 1;
}
else if(cfg["general"]["verbose"] == "true") { output += "[CheckUpdates] Windows Updates are set to: " + WUstatus[Int32.Parse(curWU)] + ".\n"; }
}
catch (Exception e)
{
if(output.ToLower().IndexOf("microsoft windows 10") != -1) // Windows 10 updates are on be default, the registry key doesn exist
{ output += "[CheckUpdates] Windows Updates are set to: Default\n"; }
else
{
output += "--> [CheckUpdates] Registry query failure: " + e + "\n";
alarms += 1;
}
}
}
if(cfg.ContainsKey("checklusers")) // check local users
{
try
{
string localusers = "";
ManagementObjectSearcher usersSearcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_UserAccount");
ManagementObjectCollection users = usersSearcher.Get();
var lUsers = users.Cast<ManagementObject>().Where(u => (bool)u["LocalAccount"] == true && (bool)u["Disabled"] == false);
foreach (ManagementObject user in lUsers)
{
localusers += user["Caption"].ToString() + " ";
}
foreach(string pp in cfg["checklusers"]["include"].Split(' '))
{
string p = pp.Trim();
string domainp = Environment.MachineName + "\\" + p;
domainp = domainp.ToLower();
if(p != "")
{
bool found = false;
foreach(string lu in localusers.Split(' '))
{
if(string.Compare(lu.ToLower(), p) == 0 || string.Compare(lu.ToLower(), domainp) == 0)
{
found = true;
}
}
if(!found)
{
output += "--> [CheckLUsers] User in include list is not enabled: " + p + "\n";
alarms += 1;
}
}
}
foreach(string pp in cfg["checklusers"]["exclude"].Split(' '))
{
string p = pp.Trim();
string domainp = Environment.MachineName + "\\" + p;
domainp = domainp.ToLower();
if(p != "")
{
bool found = false;
foreach(string lu in localusers.Split(' '))
{
if(string.Compare(lu.ToLower(), p) == 0 || string.Compare(lu.ToLower(), domainp) == 0)
{
found = true;
}
}
if(found)
{
output += "--> [CheckLUsers] User in exclude list is enabled: " + p + "\n";
alarms += 1;
}
}
}
if(cfg["general"]["verbose"] == "true") { output += "[CheckLUsers] Local users: " + localusers + "\n"; }
}
catch (Exception e)
{
output += "--> [CheckLUsers] WMI Query failure: " + e + "\n";
alarms += 1;
}
}
if(cfg.ContainsKey("checkfirewall")) // check firewall
{
try
{
string firewallresults = "";
rkey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\PublicProfile");
if((int)rkey.GetValue("EnableFirewall") != 1)
{
if(cfg["checkfirewall"]["require"].IndexOf("public") != -1)
{
output += "--> [CheckFirewall] Public firewall is OFF\n";
alarms += 1;
}
firewallresults += "Public: OFF ";
}
else { firewallresults += "Public: ON "; }
rkey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile");
if((int)rkey.GetValue("EnableFirewall") != 1)
{
if(cfg["checkfirewall"]["require"].IndexOf("private") != -1)
{
output += "--> [CheckFirewall] Private firewall is OFF\n";
alarms += 1;
}
firewallresults += "Private: OFF ";
}
else { firewallresults += "Private: ON "; }
rkey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\DomainProfile");
if((int)rkey.GetValue("EnableFirewall") != 1)
{
if(cfg["checkfirewall"]["require"].IndexOf("domain") != -1)
{
output += "--> [CheckFirewall] Domain firewall is OFF\n";
alarms += 1;
}
firewallresults += "Domain: OFF ";
}
else { firewallresults += "Domain: ON "; }
if(cfg["general"]["verbose"] == "true") { output += "[CheckFirewall] " + firewallresults + "\n"; }
}
catch (Exception e)
{
output += "--> [CheckLUsers] WMI Query failure: " + e + "\n";
alarms += 1;
}
}
if(cfg.ContainsKey("checknetwork")) // check network connection
{
try
{
Ping ping = new Ping();
PingReply reply = ping.Send(cfg["checknetwork"]["host"], 4000);
if(reply.Status != IPStatus.Success)
{
output += "--> [CheckNetwork] Host " + cfg["checknetwork"]["host"] + " is not reachable.\n";
alarms += 1;
}
else
{
if(reply.RoundtripTime > Int32.Parse(cfg["checknetwork"]["latency"]))
{
output += "--> [CheckNetwork] High network latency: " + reply.RoundtripTime + "ms.\n";
alarms += 1;
}
else if(cfg["general"]["verbose"] == "true") { output += "[CheckNetwork] Latency: " + reply.RoundtripTime + " ms.\n"; }
}
}
catch (Exception e)
{
output += "--> [CheckNetwork] Ping failure: " + e + "\n";
alarms += 1;
}
}
// Notifications
if(alarms > 1) { output += "\nChecks completed with " + alarms.ToString() + " alarms raised.\n"; }
else { output += "\nChecks completed with " + alarms.ToString() + " alarm raised.\n"; }
try
{
wc = new WebClient();
wc.Proxy = wp;
wc.QueryString.Add("alarms", alarms.ToString());
wc.QueryString.Add("cpu", curval.ToString());
wc.QueryString.Add("name", Environment.MachineName);
wc.QueryString.Add("interval", cfg["general"]["interval"]);
wc.QueryString.Add("template", cfg["general"]["template"]);
wc.QueryString.Add("output", output);
string result = wc.DownloadString(cfg["general"]["dashboard"]);
if(result.ToLower().IndexOf("[general]") != -1)
{
if(cfg["general"]["debug"] == "true") { EventLog.WriteEntry("Healthstone", "Dashboard template provided: " + result, EventLogEntryType.Information); }
ParseNewCfg(result);
}
else { EventLog.WriteEntry("Healthstone", "Unknown reply from dashboard: " + result, EventLogEntryType.Error); }
}
catch (Exception e)
{
EventLog.WriteEntry("Healthstone", "Healthstone dashboard [" + cfg["general"]["dashboard"] + "] could not be contacted: " + e, EventLogEntryType.Error);
}
if(alarms > 0) { EventLog.WriteEntry("Healthstone", output, EventLogEntryType.Warning); }
else { EventLog.WriteEntry("Healthstone", output, EventLogEntryType.Information); }
hstimer.Interval = Int32.Parse(cfg["general"]["interval"]) * 1000;
hstimer.Start();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache.Query
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary;
using NUnit.Framework;
/// <summary>
/// Queries tests.
/// </summary>
public sealed class CacheQueriesTest
{
/** Grid count. */
private const int GridCnt = 2;
/** Cache name. */
private const string CacheName = "cache";
/** Path to XML configuration. */
private const string CfgPath = "config\\cache-query.xml";
/** Maximum amount of items in cache. */
private const int MaxItemCnt = 100;
/// <summary>
///
/// </summary>
[TestFixtureSetUp]
public void StartGrids()
{
TestUtils.JvmDebug = true;
TestUtils.KillProcesses();
IgniteConfiguration cfg = new IgniteConfiguration
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new[]
{
new BinaryTypeConfiguration(typeof (QueryPerson)),
new BinaryTypeConfiguration(typeof (BinarizableScanQueryFilter<QueryPerson>)),
new BinaryTypeConfiguration(typeof (BinarizableScanQueryFilter<BinaryObject>))
}
},
JvmClasspath = TestUtils.CreateTestClasspath(),
JvmOptions = TestUtils.TestJavaOptions(),
SpringConfigUrl = CfgPath
};
for (int i = 0; i < GridCnt; i++)
{
cfg.GridName = "grid-" + i;
Ignition.Start(cfg);
}
}
/// <summary>
///
/// </summary>
[TestFixtureTearDown]
public void StopGrids()
{
for (int i = 0; i < GridCnt; i++)
Ignition.Stop("grid-" + i, true);
}
/// <summary>
///
/// </summary>
[SetUp]
public void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
///
/// </summary>
[TearDown]
public void AfterTest()
{
var cache = Cache();
for (int i = 0; i < GridCnt; i++)
{
for (int j = 0; j < MaxItemCnt; j++)
cache.Remove(j);
Assert.IsTrue(cache.IsEmpty());
}
TestUtils.AssertHandleRegistryIsEmpty(300,
Enumerable.Range(0, GridCnt).Select(x => Ignition.GetIgnite("grid-" + x)).ToArray());
Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
///
/// </summary>
/// <param name="idx"></param>
/// <returns></returns>
private IIgnite GetIgnite(int idx)
{
return Ignition.GetIgnite("grid-" + idx);
}
/// <summary>
///
/// </summary>
/// <param name="idx"></param>
/// <returns></returns>
private ICache<int, QueryPerson> Cache(int idx)
{
return GetIgnite(idx).GetCache<int, QueryPerson>(CacheName);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private ICache<int, QueryPerson> Cache()
{
return Cache(0);
}
/// <summary>
/// Test arguments validation for SQL queries.
/// </summary>
[Test]
public void TestValidationSql()
{
// 1. No sql.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new SqlQuery(typeof(QueryPerson), null)); });
// 2. No type.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new SqlQuery((string)null, "age >= 50")); });
}
/// <summary>
/// Test arguments validation for SQL fields queries.
/// </summary>
[Test]
public void TestValidationSqlFields()
{
// 1. No sql.
Assert.Throws<ArgumentException>(() => { Cache().QueryFields(new SqlFieldsQuery(null)); });
}
/// <summary>
/// Test arguments validation for TEXT queries.
/// </summary>
[Test]
public void TestValidationText()
{
// 1. No text.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new TextQuery(typeof(QueryPerson), null)); });
// 2. No type.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new TextQuery((string)null, "Ivanov")); });
}
/// <summary>
/// Cursor tests.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")]
public void TestCursor()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(1, new QueryPerson("Petrov", 40));
Cache().Put(1, new QueryPerson("Sidorov", 50));
SqlQuery qry = new SqlQuery(typeof(QueryPerson), "age >= 20");
// 1. Test GetAll().
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
cursor.GetAll();
Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); });
Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); });
}
// 2. Test GetEnumerator.
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
cursor.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); });
Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); });
}
}
/// <summary>
/// Test enumerator.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "UnusedVariable")]
public void TestEnumerator()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
Cache().Put(4, new QueryPerson("Unknown", 60));
// 1. Empty result set.
using (
IQueryCursor<ICacheEntry<int, QueryPerson>> cursor =
Cache().Query(new SqlQuery(typeof(QueryPerson), "age = 100")))
{
IEnumerator<ICacheEntry<int, QueryPerson>> e = cursor.GetEnumerator();
Assert.Throws<InvalidOperationException>(() =>
{ ICacheEntry<int, QueryPerson> entry = e.Current; });
Assert.IsFalse(e.MoveNext());
Assert.Throws<InvalidOperationException>(() =>
{ ICacheEntry<int, QueryPerson> entry = e.Current; });
Assert.Throws<NotSupportedException>(() => e.Reset());
}
SqlQuery qry = new SqlQuery(typeof (QueryPerson), "age < 60");
// 2. Page size is bigger than result set.
qry.PageSize = 4;
CheckEnumeratorQuery(qry);
// 3. Page size equal to result set.
qry.PageSize = 3;
CheckEnumeratorQuery(qry);
// 4. Page size if less than result set.
qry.PageSize = 2;
CheckEnumeratorQuery(qry);
}
/// <summary>
/// Test SQL query arguments passing.
/// </summary>
[Test]
public void TestSqlQueryArguments()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
// 1. Empty result set.
using (
IQueryCursor<ICacheEntry<int, QueryPerson>> cursor =
Cache().Query(new SqlQuery(typeof(QueryPerson), "age < ?", 50)))
{
foreach (ICacheEntry<int, QueryPerson> entry in cursor.GetAll())
Assert.IsTrue(entry.Key == 1 || entry.Key == 2);
}
}
/// <summary>
/// Test SQL fields query arguments passing.
/// </summary>
[Test]
public void TestSqlFieldsQueryArguments()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
// 1. Empty result set.
using (
IQueryCursor<IList> cursor = Cache().QueryFields(
new SqlFieldsQuery("SELECT age FROM QueryPerson WHERE age < ?", 50)))
{
foreach (IList entry in cursor.GetAll())
Assert.IsTrue((int) entry[0] < 50);
}
}
/// <summary>
/// Check query result for enumerator test.
/// </summary>
/// <param name="qry">QUery.</param>
private void CheckEnumeratorQuery(SqlQuery qry)
{
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
bool first = false;
bool second = false;
bool third = false;
foreach (var entry in cursor)
{
if (entry.Key == 1)
{
first = true;
Assert.AreEqual("Ivanov", entry.Value.Name);
Assert.AreEqual(30, entry.Value.Age);
}
else if (entry.Key == 2)
{
second = true;
Assert.AreEqual("Petrov", entry.Value.Name);
Assert.AreEqual(40, entry.Value.Age);
}
else if (entry.Key == 3)
{
third = true;
Assert.AreEqual("Sidorov", entry.Value.Name);
Assert.AreEqual(50, entry.Value.Age);
}
else
Assert.Fail("Unexpected value: " + entry);
}
Assert.IsTrue(first && second && third);
}
}
/// <summary>
/// Check SQL query.
/// </summary>
[Test]
public void TestSqlQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary,
[Values(true, false)] bool distrJoin)
{
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, MaxItemCnt, x => x < 50);
// 2. Validate results.
var qry = new SqlQuery(typeof(QueryPerson), "age < 50", loc)
{
EnableDistributedJoins = distrJoin
};
ValidateQueryResults(cache, qry, exp, keepBinary);
}
/// <summary>
/// Check SQL fields query.
/// </summary>
[Test]
public void TestSqlFieldsQuery([Values(true, false)] bool loc, [Values(true, false)] bool distrJoin,
[Values(true, false)] bool enforceJoinOrder)
{
int cnt = MaxItemCnt;
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, cnt, x => x < 50);
// 2. Validate results.
var qry = new SqlFieldsQuery("SELECT name, age FROM QueryPerson WHERE age < 50", loc)
{
EnableDistributedJoins = distrJoin,
EnforceJoinOrder = enforceJoinOrder
};
using (IQueryCursor<IList> cursor = cache.QueryFields(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
foreach (var entry in cursor.GetAll())
{
Assert.AreEqual(2, entry.Count);
Assert.AreEqual(entry[0].ToString(), entry[1].ToString());
exp0.Remove((int)entry[1]);
}
Assert.AreEqual(0, exp0.Count);
}
using (IQueryCursor<IList> cursor = cache.QueryFields(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
foreach (var entry in cursor)
{
Assert.AreEqual(entry[0].ToString(), entry[1].ToString());
exp0.Remove((int)entry[1]);
}
Assert.AreEqual(0, exp0.Count);
}
}
/// <summary>
/// Check text query.
/// </summary>
[Test]
public void TestTextQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary)
{
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, MaxItemCnt, x => x.ToString().StartsWith("1"));
// 2. Validate results.
var qry = new TextQuery(typeof(QueryPerson), "1*", loc);
ValidateQueryResults(cache, qry, exp, keepBinary);
}
/// <summary>
/// Tests that query attempt on non-indexed cache causes an exception.
/// </summary>
[Test]
public void TestIndexingDisabledError()
{
var cache = GetIgnite(0).GetOrCreateCache<int, QueryPerson>("nonindexed_cache");
var queries = new QueryBase[]
{
new TextQuery(typeof (QueryPerson), "1*"),
new SqlQuery(typeof (QueryPerson), "age < 50")
};
foreach (var qry in queries)
{
var err = Assert.Throws<IgniteException>(() => cache.Query(qry));
Assert.AreEqual("Indexing is disabled for cache: nonindexed_cache. " +
"Use setIndexedTypes or setTypeMetadata methods on CacheConfiguration to enable.", err.Message);
}
}
/// <summary>
/// Check scan query.
/// </summary>
[Test]
public void TestScanQuery<TV>([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary)
{
var cache = Cache();
var cnt = MaxItemCnt;
// No predicate
var exp = PopulateCache(cache, loc, cnt, x => true);
var qry = new ScanQuery<int, TV>();
ValidateQueryResults(cache, qry, exp, keepBinary);
// Serializable
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>());
ValidateQueryResults(cache, qry, exp, keepBinary);
// Binarizable
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new BinarizableScanQueryFilter<TV>());
ValidateQueryResults(cache, qry, exp, keepBinary);
// Invalid
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new InvalidScanQueryFilter<TV>());
Assert.Throws<BinaryObjectException>(() => ValidateQueryResults(cache, qry, exp, keepBinary));
// Exception
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV> {ThrowErr = true});
var ex = Assert.Throws<IgniteException>(() => ValidateQueryResults(cache, qry, exp, keepBinary));
Assert.AreEqual(ScanQueryFilter<TV>.ErrMessage, ex.Message);
}
/// <summary>
/// Checks scan query with partitions.
/// </summary>
[Test]
public void TestScanQueryPartitions<TV>([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary)
{
StopGrids();
StartGrids();
var cache = Cache();
var cnt = MaxItemCnt;
var aff = cache.Ignite.GetAffinity(CacheName);
var exp = PopulateCache(cache, loc, cnt, x => true); // populate outside the loop (slow)
for (var part = 0; part < aff.Partitions; part++)
{
//var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys
var exp0 = new HashSet<int>();
foreach (var x in exp)
if (aff.GetPartition(x) == part)
exp0.Add(x);
var qry = new ScanQuery<int, TV> { Partition = part };
ValidateQueryResults(cache, qry, exp0, keepBinary);
}
// Partitions with predicate
exp = PopulateCache(cache, loc, cnt, x => x < 50); // populate outside the loop (slow)
for (var part = 0; part < aff.Partitions; part++)
{
//var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys
var exp0 = new HashSet<int>();
foreach (var x in exp)
if (aff.GetPartition(x) == part)
exp0.Add(x);
var qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>()) { Partition = part };
ValidateQueryResults(cache, qry, exp0, keepBinary);
}
}
/// <summary>
/// Tests the distributed joins flag.
/// </summary>
[Test]
public void TestDistributedJoins()
{
var cache = GetIgnite(0).GetOrCreateCache<int, QueryPerson>(
new CacheConfiguration("replicatedCache")
{
QueryEntities = new[]
{
new QueryEntity(typeof(int), typeof(QueryPerson))
{
Fields = new[] {new QueryField("age", typeof(int))}
}
}
});
const int count = 100;
cache.PutAll(Enumerable.Range(0, count).ToDictionary(x => x, x => new QueryPerson("Name" + x, x)));
// Test non-distributed join: returns partial results
var sql = "select T0.Age from QueryPerson as T0 " +
"inner join QueryPerson as T1 on ((? - T1.Age - 1) = T0._key)";
var res = cache.QueryFields(new SqlFieldsQuery(sql, count)).GetAll().Distinct().Count();
Assert.Greater(res, 0);
Assert.Less(res, count);
// Test distributed join: returns complete results
res = cache.QueryFields(new SqlFieldsQuery(sql, count) {EnableDistributedJoins = true})
.GetAll().Distinct().Count();
Assert.AreEqual(count, res);
}
/// <summary>
/// Validates the query results.
/// </summary>
/// <param name="cache">Cache.</param>
/// <param name="qry">Query.</param>
/// <param name="exp">Expected keys.</param>
/// <param name="keepBinary">Keep binary flag.</param>
private static void ValidateQueryResults(ICache<int, QueryPerson> cache, QueryBase qry, HashSet<int> exp,
bool keepBinary)
{
if (keepBinary)
{
var cache0 = cache.WithKeepBinary<int, IBinaryObject>();
using (var cursor = cache0.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor.GetAll())
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name"));
Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age"));
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
using (var cursor = cache0.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor)
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name"));
Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age"));
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
}
else
{
using (var cursor = cache.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor.GetAll())
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.Name);
Assert.AreEqual(entry.Key, entry.Value.Age);
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
using (var cursor = cache.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor)
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.Name);
Assert.AreEqual(entry.Key, entry.Value.Age);
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
}
}
/// <summary>
/// Asserts that all expected entries have been received.
/// </summary>
private static void AssertMissingExpectedKeys(ICollection<int> exp, ICache<int, QueryPerson> cache,
IList<ICacheEntry<int, object>> all)
{
if (exp.Count == 0)
return;
var sb = new StringBuilder();
var aff = cache.Ignite.GetAffinity(cache.Name);
foreach (var key in exp)
{
var part = aff.GetPartition(key);
sb.AppendFormat(
"Query did not return expected key '{0}' (exists: {1}), partition '{2}', partition nodes: ",
key, cache.Get(key) != null, part);
var partNodes = aff.MapPartitionToPrimaryAndBackups(part);
foreach (var node in partNodes)
sb.Append(node).Append(" ");
sb.AppendLine(";");
}
sb.Append("Returned keys: ");
foreach (var e in all)
sb.Append(e.Key).Append(" ");
sb.AppendLine(";");
Assert.Fail(sb.ToString());
}
/// <summary>
/// Populates the cache with random entries and returns expected results set according to filter.
/// </summary>
/// <param name="cache">The cache.</param>
/// <param name="cnt">Amount of cache entries to create.</param>
/// <param name="loc">Local query flag.</param>
/// <param name="expectedEntryFilter">The expected entry filter.</param>
/// <returns>Expected results set.</returns>
private static HashSet<int> PopulateCache(ICache<int, QueryPerson> cache, bool loc, int cnt,
Func<int, bool> expectedEntryFilter)
{
var rand = new Random();
var exp = new HashSet<int>();
var aff = cache.Ignite.GetAffinity(cache.Name);
var localNode = cache.Ignite.GetCluster().GetLocalNode();
for (var i = 0; i < cnt; i++)
{
var val = rand.Next(100);
cache.Put(val, new QueryPerson(val.ToString(), val));
if (expectedEntryFilter(val) && (!loc || aff.IsPrimary(localNode, val)))
exp.Add(val);
}
return exp;
}
}
/// <summary>
/// Person.
/// </summary>
public class QueryPerson
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="age">Age.</param>
public QueryPerson(string name, int age)
{
Name = name;
Age = age;
}
/// <summary>
/// Name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Age.
/// </summary>
public int Age { get; set; }
}
/// <summary>
/// Query filter.
/// </summary>
[Serializable]
public class ScanQueryFilter<TV> : ICacheEntryFilter<int, TV>
{
// Error message
public const string ErrMessage = "Error in ScanQueryFilter.Invoke";
// Error flag
public bool ThrowErr { get; set; }
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, TV> entry)
{
if (ThrowErr)
throw new Exception(ErrMessage);
return entry.Key < 50;
}
}
/// <summary>
/// binary query filter.
/// </summary>
public class BinarizableScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable
{
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
var w = writer.GetRawWriter();
w.WriteBoolean(ThrowErr);
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
var r = reader.GetRawReader();
ThrowErr = r.ReadBoolean();
}
}
/// <summary>
/// Filter that can't be serialized.
/// </summary>
public class InvalidScanQueryFilter<TV> : ScanQueryFilter<TV>
{
// No-op.
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Cluster;
/// <summary>
/// Wraps IGridCache implementation to simplify async mode testing.
/// </summary>
internal class CacheTestAsyncWrapper<TK, TV> : ICache<TK, TV>
{
private readonly ICache<TK, TV> _cache;
/// <summary>
/// Initializes a new instance of the <see cref="CacheTestAsyncWrapper{K, V}"/> class.
/// </summary>
/// <param name="cache">The cache to be wrapped.</param>
public CacheTestAsyncWrapper(ICache<TK, TV> cache)
{
Debug.Assert(cache != null);
_cache = cache;
}
/** <inheritDoc /> */
public string Name
{
get { return _cache.Name; }
}
/** <inheritDoc /> */
public IIgnite Ignite
{
get { return _cache.Ignite; }
}
/** <inheritDoc /> */
public CacheConfiguration GetConfiguration()
{
return _cache.GetConfiguration();
}
/** <inheritDoc /> */
public bool IsEmpty()
{
return _cache.IsEmpty();
}
/** <inheritDoc /> */
public bool IsKeepBinary
{
get { return _cache.IsKeepBinary; }
}
/** <inheritDoc /> */
public ICache<TK, TV> WithSkipStore()
{
return _cache.WithSkipStore().WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc)
{
return _cache.WithExpiryPolicy(plc).WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
return _cache.WithKeepBinary<TK1, TV1>().WrapAsync();
}
/** <inheritDoc /> */
public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
_cache.LoadCacheAsync(p, args).WaitResult();
}
/** <inheritDoc /> */
public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return _cache.LoadCacheAsync(p, args);
}
/** <inheritDoc /> */
public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
_cache.LocalLoadCacheAsync(p, args).WaitResult();
}
/** <inheritDoc /> */
public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return _cache.LocalLoadCacheAsync(p, args);
}
/** <inheritDoc /> */
public void LoadAll(IEnumerable<TK> keys, bool replaceExistingValues)
{
_cache.LoadAll(keys, replaceExistingValues);
}
/** <inheritDoc /> */
public Task LoadAllAsync(IEnumerable<TK> keys, bool replaceExistingValues)
{
return _cache.LoadAllAsync(keys, replaceExistingValues);
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
return _cache.ContainsKeyAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ContainsKeyAsync(TK key)
{
return _cache.ContainsKeyAsync(key);
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
return _cache.ContainsKeysAsync(keys).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys)
{
return _cache.ContainsKeysAsync(keys);
}
/** <inheritDoc /> */
public TV LocalPeek(TK key, params CachePeekMode[] modes)
{
return _cache.LocalPeek(key, modes);
}
/** <inheritDoc /> */
public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes)
{
return _cache.TryLocalPeek(key, out value, modes);
}
/** <inheritDoc /> */
public TV this[TK key]
{
get { return _cache[key]; }
set { _cache[key] = value; }
}
/** <inheritDoc /> */
public TV Get(TK key)
{
return _cache.GetAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<TV> GetAsync(TK key)
{
return _cache.GetAsync(key);
}
/** <inheritDoc /> */
public bool TryGet(TK key, out TV value)
{
return _cache.TryGet(key, out value);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> TryGetAsync(TK key)
{
return _cache.TryGetAsync(key);
}
/** <inheritDoc /> */
public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys)
{
return _cache.GetAllAsync(keys).GetResult();
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys)
{
return _cache.GetAllAsync(keys);
}
/** <inheritDoc /> */
public void Put(TK key, TV val)
{
_cache.PutAsync(key, val).WaitResult();
}
/** <inheritDoc /> */
public Task PutAsync(TK key, TV val)
{
return _cache.PutAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPut(TK key, TV val)
{
return _cache.GetAndPutAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val)
{
return _cache.GetAndPutAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndReplace(TK key, TV val)
{
return _cache.GetAndReplaceAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val)
{
return _cache.GetAndReplaceAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndRemove(TK key)
{
return _cache.GetAndRemoveAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndRemoveAsync(TK key)
{
return _cache.GetAndRemoveAsync(key);
}
/** <inheritDoc /> */
public bool PutIfAbsent(TK key, TV val)
{
return _cache.PutIfAbsentAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<bool> PutIfAbsentAsync(TK key, TV val)
{
return _cache.PutIfAbsentAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val)
{
return _cache.GetAndPutIfAbsentAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val)
{
return _cache.GetAndPutIfAbsentAsync(key, val);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV val)
{
return _cache.ReplaceAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV val)
{
return _cache.ReplaceAsync(key, val);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
return _cache.ReplaceAsync(key, oldVal, newVal).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal)
{
return _cache.ReplaceAsync(key, oldVal, newVal);
}
/** <inheritDoc /> */
public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals)
{
_cache.PutAllAsync(vals).WaitResult();
}
/** <inheritDoc /> */
public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals)
{
return _cache.PutAllAsync(vals);
}
/** <inheritDoc /> */
public void LocalEvict(IEnumerable<TK> keys)
{
_cache.LocalEvict(keys);
}
/** <inheritDoc /> */
public void Clear()
{
_cache.ClearAsync().WaitResult();
}
/** <inheritDoc /> */
public Task ClearAsync()
{
return _cache.ClearAsync();
}
/** <inheritDoc /> */
public void Clear(TK key)
{
_cache.ClearAsync(key).WaitResult();
}
/** <inheritDoc /> */
public Task ClearAsync(TK key)
{
return _cache.ClearAsync(key);
}
/** <inheritDoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
_cache.ClearAllAsync(keys).WaitResult();
}
/** <inheritDoc /> */
public Task ClearAllAsync(IEnumerable<TK> keys)
{
return _cache.ClearAllAsync(keys);
}
/** <inheritDoc /> */
public void LocalClear(TK key)
{
_cache.LocalClear(key);
}
/** <inheritDoc /> */
public void LocalClearAll(IEnumerable<TK> keys)
{
_cache.LocalClearAll(keys);
}
/** <inheritDoc /> */
public bool Remove(TK key)
{
return _cache.RemoveAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key)
{
return _cache.RemoveAsync(key);
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
return _cache.RemoveAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key, TV val)
{
return _cache.RemoveAsync(key, val);
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
Task task = _cache.RemoveAllAsync(keys);
task.WaitResult();
}
/** <inheritDoc /> */
public Task RemoveAllAsync(IEnumerable<TK> keys)
{
return _cache.RemoveAllAsync(keys);
}
/** <inheritDoc /> */
public void RemoveAll()
{
Task task = _cache.RemoveAllAsync();
task.WaitResult();
}
/** <inheritDoc /> */
public Task RemoveAllAsync()
{
return _cache.RemoveAllAsync();
}
/** <inheritDoc /> */
public int GetLocalSize(params CachePeekMode[] modes)
{
return _cache.GetLocalSize(modes);
}
/** <inheritDoc /> */
public int GetSize(params CachePeekMode[] modes)
{
return _cache.GetSizeAsync(modes).GetResult();
}
/** <inheritDoc /> */
public Task<int> GetSizeAsync(params CachePeekMode[] modes)
{
return _cache.GetSizeAsync(modes);
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry)
{
return _cache.Query(qry);
}
/** <inheritDoc /> */
public IFieldsQueryCursor Query(SqlFieldsQuery qry)
{
return _cache.Query(qry);
}
/** <inheritDoc /> */
[Obsolete]
public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry)
{
return _cache.QueryFields(qry);
}
/** <inheritDoc /> */
IContinuousQueryHandle ICache<TK, TV>.QueryContinuous(ContinuousQuery<TK, TV> qry)
{
return _cache.QueryContinuous(qry);
}
/** <inheritDoc /> */
public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry)
{
return _cache.QueryContinuous(qry, initialQry);
}
/** <inheritDoc /> */
public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(params CachePeekMode[] peekModes)
{
return _cache.GetLocalEntries(peekModes);
}
/** <inheritDoc /> */
public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAsync(key, processor, arg).GetResult();
}
/** <inheritDoc /> */
public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAsync(key, processor, arg);
}
/** <inheritDoc /> */
public ICollection<ICacheEntryProcessorResult<TK, TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAllAsync(keys, processor, arg).GetResult();
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntryProcessorResult<TK, TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAllAsync(keys, processor, arg);
}
/** <inheritDoc /> */
public ICacheLock Lock(TK key)
{
return _cache.Lock(key);
}
/** <inheritDoc /> */
public ICacheLock LockAll(IEnumerable<TK> keys)
{
return _cache.LockAll(keys);
}
/** <inheritDoc /> */
public bool IsLocalLocked(TK key, bool byCurrentThread)
{
return _cache.IsLocalLocked(key, byCurrentThread);
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics()
{
return _cache.GetMetrics();
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics(IClusterGroup clusterGroup)
{
return _cache.GetMetrics(clusterGroup);
}
/** <inheritDoc /> */
public ICacheMetrics GetLocalMetrics()
{
return _cache.GetLocalMetrics();
}
/** <inheritDoc /> */
public Task Rebalance()
{
return _cache.Rebalance();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithNoRetries()
{
return _cache.WithNoRetries();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithPartitionRecover()
{
return _cache.WithPartitionRecover();
}
/** <inheritDoc /> */
public ICollection<int> GetLostPartitions()
{
return _cache.GetLostPartitions();
}
/** <inheritDoc /> */
public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator()
{
return _cache.GetEnumerator();
}
/** <inheritDoc /> */
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IQueryMetrics GetQueryMetrics()
{
return _cache.GetQueryMetrics();
}
public void ResetQueryMetrics()
{
_cache.ResetQueryMetrics();
}
}
/// <summary>
/// Extension methods for IGridCache.
/// </summary>
public static class CacheExtensions
{
/// <summary>
/// Wraps specified instance into GridCacheTestAsyncWrapper.
/// </summary>
public static ICache<TK, TV> WrapAsync<TK, TV>(this ICache<TK, TV> cache)
{
return new CacheTestAsyncWrapper<TK, TV>(cache);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/oslogin/common/common.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.Cloud.OsLogin.Common {
/// <summary>Holder for reflection information generated from google/cloud/oslogin/common/common.proto</summary>
public static partial class CommonReflection {
#region Descriptor
/// <summary>File descriptor for google/cloud/oslogin/common/common.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CommonReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cihnb29nbGUvY2xvdWQvb3Nsb2dpbi9jb21tb24vY29tbW9uLnByb3RvEhtn",
"b29nbGUuY2xvdWQub3Nsb2dpbi5jb21tb24aHGdvb2dsZS9hcGkvYW5ub3Rh",
"dGlvbnMucHJvdG8iqAEKDFBvc2l4QWNjb3VudBIPCgdwcmltYXJ5GAEgASgI",
"EhAKCHVzZXJuYW1lGAIgASgJEgsKA3VpZBgDIAEoAxILCgNnaWQYBCABKAMS",
"FgoOaG9tZV9kaXJlY3RvcnkYBSABKAkSDQoFc2hlbGwYBiABKAkSDQoFZ2Vj",
"b3MYByABKAkSEQoJc3lzdGVtX2lkGAggASgJEhIKCmFjY291bnRfaWQYCSAB",
"KAkiTgoMU3NoUHVibGljS2V5EgsKA2tleRgBIAEoCRIcChRleHBpcmF0aW9u",
"X3RpbWVfdXNlYxgCIAEoAxITCgtmaW5nZXJwcmludBgDIAEoCUKuAQofY29t",
"Lmdvb2dsZS5jbG91ZC5vc2xvZ2luLmNvbW1vbkIMT3NMb2dpblByb3RvWkFn",
"b29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Nsb3VkL29z",
"bG9naW4vY29tbW9uO2NvbW1vbqoCG0dvb2dsZS5DbG91ZC5Pc0xvZ2luLkNv",
"bW1vbsoCG0dvb2dsZVxDbG91ZFxPc0xvZ2luXENvbW1vbmIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsLogin.Common.PosixAccount), global::Google.Cloud.OsLogin.Common.PosixAccount.Parser, new[]{ "Primary", "Username", "Uid", "Gid", "HomeDirectory", "Shell", "Gecos", "SystemId", "AccountId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsLogin.Common.SshPublicKey), global::Google.Cloud.OsLogin.Common.SshPublicKey.Parser, new[]{ "Key", "ExpirationTimeUsec", "Fingerprint" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// The POSIX account information associated with a Google account.
/// </summary>
public sealed partial class PosixAccount : pb::IMessage<PosixAccount> {
private static readonly pb::MessageParser<PosixAccount> _parser = new pb::MessageParser<PosixAccount>(() => new PosixAccount());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PosixAccount> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.OsLogin.Common.CommonReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PosixAccount() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PosixAccount(PosixAccount other) : this() {
primary_ = other.primary_;
username_ = other.username_;
uid_ = other.uid_;
gid_ = other.gid_;
homeDirectory_ = other.homeDirectory_;
shell_ = other.shell_;
gecos_ = other.gecos_;
systemId_ = other.systemId_;
accountId_ = other.accountId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PosixAccount Clone() {
return new PosixAccount(this);
}
/// <summary>Field number for the "primary" field.</summary>
public const int PrimaryFieldNumber = 1;
private bool primary_;
/// <summary>
/// Only one POSIX account can be marked as primary.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Primary {
get { return primary_; }
set {
primary_ = value;
}
}
/// <summary>Field number for the "username" field.</summary>
public const int UsernameFieldNumber = 2;
private string username_ = "";
/// <summary>
/// The username of the POSIX account.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Username {
get { return username_; }
set {
username_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "uid" field.</summary>
public const int UidFieldNumber = 3;
private long uid_;
/// <summary>
/// The user ID.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Uid {
get { return uid_; }
set {
uid_ = value;
}
}
/// <summary>Field number for the "gid" field.</summary>
public const int GidFieldNumber = 4;
private long gid_;
/// <summary>
/// The default group ID.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Gid {
get { return gid_; }
set {
gid_ = value;
}
}
/// <summary>Field number for the "home_directory" field.</summary>
public const int HomeDirectoryFieldNumber = 5;
private string homeDirectory_ = "";
/// <summary>
/// The path to the home directory for this account.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string HomeDirectory {
get { return homeDirectory_; }
set {
homeDirectory_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "shell" field.</summary>
public const int ShellFieldNumber = 6;
private string shell_ = "";
/// <summary>
/// The path to the logic shell for this account.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Shell {
get { return shell_; }
set {
shell_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "gecos" field.</summary>
public const int GecosFieldNumber = 7;
private string gecos_ = "";
/// <summary>
/// The GECOS (user information) entry for this account.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Gecos {
get { return gecos_; }
set {
gecos_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "system_id" field.</summary>
public const int SystemIdFieldNumber = 8;
private string systemId_ = "";
/// <summary>
/// System identifier for which account the username or uid applies to.
/// By default, the empty value is used.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string SystemId {
get { return systemId_; }
set {
systemId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "account_id" field.</summary>
public const int AccountIdFieldNumber = 9;
private string accountId_ = "";
/// <summary>
/// Output only. A POSIX account identifier.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string AccountId {
get { return accountId_; }
set {
accountId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PosixAccount);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PosixAccount other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Primary != other.Primary) return false;
if (Username != other.Username) return false;
if (Uid != other.Uid) return false;
if (Gid != other.Gid) return false;
if (HomeDirectory != other.HomeDirectory) return false;
if (Shell != other.Shell) return false;
if (Gecos != other.Gecos) return false;
if (SystemId != other.SystemId) return false;
if (AccountId != other.AccountId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Primary != false) hash ^= Primary.GetHashCode();
if (Username.Length != 0) hash ^= Username.GetHashCode();
if (Uid != 0L) hash ^= Uid.GetHashCode();
if (Gid != 0L) hash ^= Gid.GetHashCode();
if (HomeDirectory.Length != 0) hash ^= HomeDirectory.GetHashCode();
if (Shell.Length != 0) hash ^= Shell.GetHashCode();
if (Gecos.Length != 0) hash ^= Gecos.GetHashCode();
if (SystemId.Length != 0) hash ^= SystemId.GetHashCode();
if (AccountId.Length != 0) hash ^= AccountId.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 (Primary != false) {
output.WriteRawTag(8);
output.WriteBool(Primary);
}
if (Username.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Username);
}
if (Uid != 0L) {
output.WriteRawTag(24);
output.WriteInt64(Uid);
}
if (Gid != 0L) {
output.WriteRawTag(32);
output.WriteInt64(Gid);
}
if (HomeDirectory.Length != 0) {
output.WriteRawTag(42);
output.WriteString(HomeDirectory);
}
if (Shell.Length != 0) {
output.WriteRawTag(50);
output.WriteString(Shell);
}
if (Gecos.Length != 0) {
output.WriteRawTag(58);
output.WriteString(Gecos);
}
if (SystemId.Length != 0) {
output.WriteRawTag(66);
output.WriteString(SystemId);
}
if (AccountId.Length != 0) {
output.WriteRawTag(74);
output.WriteString(AccountId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Primary != false) {
size += 1 + 1;
}
if (Username.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Username);
}
if (Uid != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Uid);
}
if (Gid != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Gid);
}
if (HomeDirectory.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(HomeDirectory);
}
if (Shell.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Shell);
}
if (Gecos.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Gecos);
}
if (SystemId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(SystemId);
}
if (AccountId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(AccountId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PosixAccount other) {
if (other == null) {
return;
}
if (other.Primary != false) {
Primary = other.Primary;
}
if (other.Username.Length != 0) {
Username = other.Username;
}
if (other.Uid != 0L) {
Uid = other.Uid;
}
if (other.Gid != 0L) {
Gid = other.Gid;
}
if (other.HomeDirectory.Length != 0) {
HomeDirectory = other.HomeDirectory;
}
if (other.Shell.Length != 0) {
Shell = other.Shell;
}
if (other.Gecos.Length != 0) {
Gecos = other.Gecos;
}
if (other.SystemId.Length != 0) {
SystemId = other.SystemId;
}
if (other.AccountId.Length != 0) {
AccountId = other.AccountId;
}
}
[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: {
Primary = input.ReadBool();
break;
}
case 18: {
Username = input.ReadString();
break;
}
case 24: {
Uid = input.ReadInt64();
break;
}
case 32: {
Gid = input.ReadInt64();
break;
}
case 42: {
HomeDirectory = input.ReadString();
break;
}
case 50: {
Shell = input.ReadString();
break;
}
case 58: {
Gecos = input.ReadString();
break;
}
case 66: {
SystemId = input.ReadString();
break;
}
case 74: {
AccountId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The SSH public key information associated with a Google account.
/// </summary>
public sealed partial class SshPublicKey : pb::IMessage<SshPublicKey> {
private static readonly pb::MessageParser<SshPublicKey> _parser = new pb::MessageParser<SshPublicKey>(() => new SshPublicKey());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<SshPublicKey> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.OsLogin.Common.CommonReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SshPublicKey() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SshPublicKey(SshPublicKey other) : this() {
key_ = other.key_;
expirationTimeUsec_ = other.expirationTimeUsec_;
fingerprint_ = other.fingerprint_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SshPublicKey Clone() {
return new SshPublicKey(this);
}
/// <summary>Field number for the "key" field.</summary>
public const int KeyFieldNumber = 1;
private string key_ = "";
/// <summary>
/// Public key text in SSH format, defined by
/// <a href="https://www.ietf.org/rfc/rfc4253.txt" target="_blank">RFC4253</a>
/// section 6.6.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Key {
get { return key_; }
set {
key_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "expiration_time_usec" field.</summary>
public const int ExpirationTimeUsecFieldNumber = 2;
private long expirationTimeUsec_;
/// <summary>
/// An expiration time in microseconds since epoch.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long ExpirationTimeUsec {
get { return expirationTimeUsec_; }
set {
expirationTimeUsec_ = value;
}
}
/// <summary>Field number for the "fingerprint" field.</summary>
public const int FingerprintFieldNumber = 3;
private string fingerprint_ = "";
/// <summary>
/// Output only. The SHA-256 fingerprint of the SSH public key.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Fingerprint {
get { return fingerprint_; }
set {
fingerprint_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as SshPublicKey);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(SshPublicKey other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Key != other.Key) return false;
if (ExpirationTimeUsec != other.ExpirationTimeUsec) return false;
if (Fingerprint != other.Fingerprint) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Key.Length != 0) hash ^= Key.GetHashCode();
if (ExpirationTimeUsec != 0L) hash ^= ExpirationTimeUsec.GetHashCode();
if (Fingerprint.Length != 0) hash ^= Fingerprint.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.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Key);
}
if (ExpirationTimeUsec != 0L) {
output.WriteRawTag(16);
output.WriteInt64(ExpirationTimeUsec);
}
if (Fingerprint.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Fingerprint);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Key.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Key);
}
if (ExpirationTimeUsec != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(ExpirationTimeUsec);
}
if (Fingerprint.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Fingerprint);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(SshPublicKey other) {
if (other == null) {
return;
}
if (other.Key.Length != 0) {
Key = other.Key;
}
if (other.ExpirationTimeUsec != 0L) {
ExpirationTimeUsec = other.ExpirationTimeUsec;
}
if (other.Fingerprint.Length != 0) {
Fingerprint = other.Fingerprint;
}
}
[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: {
Key = input.ReadString();
break;
}
case 16: {
ExpirationTimeUsec = input.ReadInt64();
break;
}
case 26: {
Fingerprint = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace WebApplicationApiClient
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Activities operations.
/// </summary>
public partial class Activities : IServiceOperations<WebApiApplication>, IActivities
{
/// <summary>
/// Initializes a new instance of the Activities class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Activities(WebApiApplication client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the WebApiApplication
/// </summary>
public WebApiApplication Client { get; private set; }
/// <summary>
/// Gets all activities.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<Activity>>> GetWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Get", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "api/Activities").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<IList<Activity>>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<IList<Activity>>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Creates a new activity.
/// </summary>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<object>> PostWithHttpMessagesAsync(Activity value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (value == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "value");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("value", value);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "api/Activities").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(value, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Created")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<object>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<object>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Deletes an activity by id.
/// </summary>
/// <param name='id'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<bool?>> DeleteWithHttpMessagesAsync(int? id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (id == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "id");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("id", id);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "api/Activities/{id}").ToString();
url = url.Replace("{id}", Uri.EscapeDataString(JsonConvert.SerializeObject(id, this.Client.SerializationSettings).Trim('"')));
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("DELETE");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "NotFound")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<bool?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<bool?>(responseContent, this.Client.DeserializationSettings);
}
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "NotFound"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<bool?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
using Microsoft.DirectX.Direct3D;
using System.Drawing;
using TGC.Core.Direct3D;
using TGC.Core.Mathematica;
using TGC.Core.Shaders;
using TGC.Core.Textures;
namespace TGC.Core.BoundingVolumes
{
/// <summary>
/// Clase que representa el volumen del Frustum (vision actual).
/// Las normales de los planos del Frustum apuntan hacia adentro.
/// Tambien permite dibujar una malla debug del frustum
/// Solo puede ser invocado cuando se esta ejecutando un bloque de Render() de un TGCExample
/// </summary>
public class TgcFrustum
{
/// <summary>
/// Tipos de planos del Frustum
/// </summary>
public enum PlaneTypes
{
Left = 0,
Right = 1,
Top = 2,
Bottom = 3,
Near = 4,
Far = 5
}
private static readonly TGCVector3 UP_VECTOR = TGCVector3.Up;
public TgcFrustum()
{
FrustumPlanes = new TGCPlane[6];
Color = Color.Green;
AlphaBlendingValue = 0.7f;
}
/// <summary>
/// VertexBuffer para mesh debug de Frustum
/// </summary>
private VertexBuffer VertexBuffer { get; set; }
/// <summary>
/// Los 6 planos que componen el Frustum.
/// Estan en el siguiente orden:
/// Left, Right, Top, Bottom, Near, Far
/// Estan normalizados.
/// Sus normales hacia adentro.
/// </summary>
public TGCPlane[] FrustumPlanes { get; } = new TGCPlane[6];
/// <summary>
/// Shader del mesh
/// </summary>
public Effect Effect { get; set; }
/// <summary>
/// Technique que se va a utilizar en el effect.
/// Cada vez que se llama a Render() se carga este Technique (pisando lo que el shader ya tenia seteado)
/// </summary>
public string Technique { get; set; }
/// <summary>
/// Left plane
/// </summary>
public TGCPlane LeftPlane
{
get { return FrustumPlanes[(int)PlaneTypes.Left]; }
}
/// <summary>
/// Right plane
/// </summary>
public TGCPlane RightPlane
{
get { return FrustumPlanes[(int)PlaneTypes.Right]; }
}
/// <summary>
/// Top plane
/// </summary>
public TGCPlane TopPlane
{
get { return FrustumPlanes[(int)PlaneTypes.Top]; }
}
/// <summary>
/// Bottom plane
/// </summary>
public TGCPlane BottomPlane
{
get { return FrustumPlanes[(int)PlaneTypes.Bottom]; }
}
/// <summary>
/// Near plane
/// </summary>
public TGCPlane NearPlane
{
get { return FrustumPlanes[(int)PlaneTypes.Near]; }
}
/// <summary>
/// Far plane
/// </summary>
public TGCPlane FarPlane
{
get { return FrustumPlanes[(int)PlaneTypes.Far]; }
}
/// <summary>
/// Transparencia (0, 1)
/// </summary>
public float AlphaBlendingValue { get; set; }
/// <summary>
/// Color del mesh debug
/// </summary>
public Color Color { get; set; }
/// <summary>
/// Actualiza los planos que conforman el volumen del Frustum.
/// Los planos se calculan con las normales apuntando hacia adentro
/// </summary>
/// <param name="viewMatrix">View matrix</param>
/// <param name="projectionMatrix">Projection matrix</param>
public void updateVolume(TGCMatrix viewMatrix, TGCMatrix projectionMatrix)
{
var viewProjection = viewMatrix * projectionMatrix;
//Left plane
FrustumPlanes[0].A = viewProjection.M14 + viewProjection.M11;
FrustumPlanes[0].B = viewProjection.M24 + viewProjection.M21;
FrustumPlanes[0].C = viewProjection.M34 + viewProjection.M31;
FrustumPlanes[0].D = viewProjection.M44 + viewProjection.M41;
//Right plane
FrustumPlanes[1].A = viewProjection.M14 - viewProjection.M11;
FrustumPlanes[1].B = viewProjection.M24 - viewProjection.M21;
FrustumPlanes[1].C = viewProjection.M34 - viewProjection.M31;
FrustumPlanes[1].D = viewProjection.M44 - viewProjection.M41;
//Top plane
FrustumPlanes[2].A = viewProjection.M14 - viewProjection.M12;
FrustumPlanes[2].B = viewProjection.M24 - viewProjection.M22;
FrustumPlanes[2].C = viewProjection.M34 - viewProjection.M32;
FrustumPlanes[2].D = viewProjection.M44 - viewProjection.M42;
//Bottom plane
FrustumPlanes[3].A = viewProjection.M14 + viewProjection.M12;
FrustumPlanes[3].B = viewProjection.M24 + viewProjection.M22;
FrustumPlanes[3].C = viewProjection.M34 + viewProjection.M32;
FrustumPlanes[3].D = viewProjection.M44 + viewProjection.M42;
//Near plane
FrustumPlanes[4].A = viewProjection.M13;
FrustumPlanes[4].B = viewProjection.M23;
FrustumPlanes[4].C = viewProjection.M33;
FrustumPlanes[4].D = viewProjection.M43;
//Far plane
FrustumPlanes[5].A = viewProjection.M14 - viewProjection.M13;
FrustumPlanes[5].B = viewProjection.M24 - viewProjection.M23;
FrustumPlanes[5].C = viewProjection.M34 - viewProjection.M33;
FrustumPlanes[5].D = viewProjection.M44 - viewProjection.M43;
//Normalize planes
for (var i = 0; i < 6; i++)
{
FrustumPlanes[i] = TGCPlane.Normalize(FrustumPlanes[i]);
}
}
/// <summary>
/// Calcular los 8 vertices del Frustum
/// Basado en: http://www.lighthouse3d.com/tutorials/view-frustum-culling/geometric-approach-implementation/
/// </summary>
/// <param name="position"></param>
/// <param name="lookAt"></param>
/// <param name="aspectRatio"></param>
/// <param name="nearDistance"></param>
/// <param name="farDistance"></param>
/// <param name="fieldOfViewY"></param>
/// <returns>Los 8 vertices del Frustum</returns>
private TGCVector3[] computeFrustumCorners(TGCVector3 position, TGCVector3 lookAt, float aspectRatio, float nearDistance,
float farDistance, float fieldOfViewY)
{
var corners = new TGCVector3[8];
/*
(ntl)0 ---- 1(ntr)
| | Near-face
(nbl)2 ---- 3(nbr)
(ftl)4 ---- 5(ftr)
| | Far-face
(fbl)6 ---- 7(fbr)
*/
var tang = FastMath.Tan(fieldOfViewY * 0.5f);
var nh = nearDistance * tang;
var nw = nh * aspectRatio;
var fh = farDistance * tang;
var fw = fh * aspectRatio;
// compute the Z axis of camera
// this axis points in the opposite direction from
// the looking direction
var Z = TGCVector3.Subtract(position, lookAt);
Z.Normalize();
// X axis of camera with given "up" vector and Z axis
var X = TGCVector3.Cross(UP_VECTOR, Z);
X.Normalize();
// the real "up" vector is the cross product of Z and X
var Y = TGCVector3.Cross(Z, X);
// compute the centers of the near and far planes
var nc = position - Z * nearDistance;
var fc = position - Z * farDistance;
// compute the 4 corners of the frustum on the near plane
corners[0] = nc + Y * nh - X * nw; //ntl
corners[1] = nc + Y * nh + X * nw; //ntr
corners[2] = nc - Y * nh - X * nw; //nbl
corners[3] = nc - Y * nh + X * nw; //nbr
// compute the 4 corners of the frustum on the far plane
corners[4] = fc + Y * fh - X * fw; //ftl
corners[5] = fc + Y * fh + X * fw; //ftr
corners[6] = fc - Y * fh - X * fw; //fbl
corners[7] = fc - Y * fh + X * fw; //fbr
return corners;
}
/// <summary>
/// Actualizar el mesh para debug del Frustum
/// </summary>
/// <param name="position"></param>
/// <param name="lookAt"></param>
public void updateMesh(TGCVector3 position, TGCVector3 lookAt)
{
updateMesh(position, lookAt, D3DDevice.Instance.AspectRatio, D3DDevice.Instance.ZNearPlaneDistance,
D3DDevice.Instance.ZFarPlaneDistance, D3DDevice.Instance.FieldOfView);
}
/// <summary>
/// Actualizar el mesh para debug del Frustum
/// Basado en: http://zach.in.tu-clausthal.de/teaching/cg_literatur/lighthouse3d_view_frustum_culling/index.html
/// </summary>
/// <param name="position"></param>
/// <param name="lookAt"></param>
/// <param name="aspectRatio"></param>
/// <param name="nearDistance"></param>
/// <param name="farDistance"></param>
/// <param name="fieldOfViewY"></param>
public void updateMesh(TGCVector3 position, TGCVector3 lookAt, float aspectRatio, float nearDistance,
float farDistance, float fieldOfViewY)
{
//Calcular los 8 vertices extremos
var corners = computeFrustumCorners(position, lookAt, aspectRatio, nearDistance, farDistance, fieldOfViewY);
//Crear vertexBuffer
if (VertexBuffer == null)
{
VertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 36, D3DDevice.Instance.Device,
Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default);
}
//Cargar vertices de las 6 caras
var vertices = new CustomVertex.PositionColored[36];
var color = Color.ToArgb();
// Front face
vertices[0] = new CustomVertex.PositionColored(corners[0], color);
vertices[1] = new CustomVertex.PositionColored(corners[2], color);
vertices[2] = new CustomVertex.PositionColored(corners[3], color);
vertices[3] = new CustomVertex.PositionColored(corners[0], color);
vertices[4] = new CustomVertex.PositionColored(corners[3], color);
vertices[5] = new CustomVertex.PositionColored(corners[2], color);
// Back face
vertices[6] = new CustomVertex.PositionColored(corners[5], color);
vertices[7] = new CustomVertex.PositionColored(corners[4], color);
vertices[8] = new CustomVertex.PositionColored(corners[6], color);
vertices[9] = new CustomVertex.PositionColored(corners[6], color);
vertices[10] = new CustomVertex.PositionColored(corners[7], color);
vertices[11] = new CustomVertex.PositionColored(corners[5], color);
// Top face
vertices[12] = new CustomVertex.PositionColored(corners[4], color);
vertices[13] = new CustomVertex.PositionColored(corners[5], color);
vertices[14] = new CustomVertex.PositionColored(corners[1], color);
vertices[15] = new CustomVertex.PositionColored(corners[4], color);
vertices[16] = new CustomVertex.PositionColored(corners[1], color);
vertices[17] = new CustomVertex.PositionColored(corners[0], color);
// Bottom face
vertices[18] = new CustomVertex.PositionColored(corners[2], color);
vertices[19] = new CustomVertex.PositionColored(corners[3], color);
vertices[20] = new CustomVertex.PositionColored(corners[7], color);
vertices[21] = new CustomVertex.PositionColored(corners[2], color);
vertices[22] = new CustomVertex.PositionColored(corners[7], color);
vertices[23] = new CustomVertex.PositionColored(corners[6], color);
// Left face
vertices[24] = new CustomVertex.PositionColored(corners[4], color);
vertices[25] = new CustomVertex.PositionColored(corners[0], color);
vertices[26] = new CustomVertex.PositionColored(corners[2], color);
vertices[27] = new CustomVertex.PositionColored(corners[4], color);
vertices[28] = new CustomVertex.PositionColored(corners[2], color);
vertices[29] = new CustomVertex.PositionColored(corners[6], color);
// Right face
vertices[30] = new CustomVertex.PositionColored(corners[1], color);
vertices[31] = new CustomVertex.PositionColored(corners[5], color);
vertices[32] = new CustomVertex.PositionColored(corners[7], color);
vertices[33] = new CustomVertex.PositionColored(corners[1], color);
vertices[34] = new CustomVertex.PositionColored(corners[7], color);
vertices[35] = new CustomVertex.PositionColored(corners[3], color);
//Actualizar vertexBuffer
VertexBuffer.SetData(vertices, 0, LockFlags.None);
vertices = null;
}
/// <summary>
/// Dibujar mesh debug del Frustum.
/// Antes se debe llamar a updateMesh()
/// Setear el effect para el shader antes
/// </summary>
public void render()
{
TexturesManager.Instance.clear(0);
TexturesManager.Instance.clear(1);
//Cargar shader si es la primera vez
if (Effect == null)
{
Effect = TGCShaders.Instance.VariosShader;
Technique = TGCShaders.T_POSITION_COLORED_ALPHA;
}
TGCShaders.Instance.SetShaderMatrixIdentity(Effect);
D3DDevice.Instance.Device.VertexDeclaration = TGCShaders.Instance.VdecPositionColored;
Effect.Technique = Technique;
D3DDevice.Instance.Device.SetStreamSource(0, VertexBuffer, 0);
//Transparencia
Effect.SetValue("alphaValue", AlphaBlendingValue);
D3DDevice.Instance.Device.RenderState.AlphaTestEnable = true;
D3DDevice.Instance.Device.RenderState.AlphaBlendEnable = true;
//Draw shader
Effect.Begin(0);
Effect.BeginPass(0);
D3DDevice.Instance.Device.DrawPrimitives(PrimitiveType.TriangleList, 0, 12);
Effect.EndPass();
Effect.End();
D3DDevice.Instance.Device.RenderState.AlphaTestEnable = false;
D3DDevice.Instance.Device.RenderState.AlphaBlendEnable = false;
}
/// <summary>
/// Liberar recursos
/// </summary>
public void dispose()
{
VertexBuffer.Dispose();
}
}
}
| |
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using TouchScript.Devices.Display;
using TouchScript.Hit;
using TouchScript.InputSources;
using TouchScript.Layers;
using TouchScript.Utils;
#if DEBUG
using TouchScript.Utils.Debug;
#endif
using UnityEngine;
namespace TouchScript
{
/// <summary>
/// Default implementation of <see cref="ITouchManager"/>.
/// </summary>
internal sealed class TouchManagerInstance : DebuggableMonoBehaviour, ITouchManager
{
#region Events
/// <inheritdoc />
public event EventHandler FrameStarted
{
add { frameStartedInvoker += value; }
remove { frameStartedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler FrameFinished
{
add { frameFinishedInvoker += value; }
remove { frameFinishedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchesBegan
{
add { touchesBeganInvoker += value; }
remove { touchesBeganInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchesMoved
{
add { touchesMovedInvoker += value; }
remove { touchesMovedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchesEnded
{
add { touchesEndedInvoker += value; }
remove { touchesEndedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchesCancelled
{
add { touchesCancelledInvoker += value; }
remove { touchesCancelledInvoker -= value; }
}
// Needed to overcome iOS AOT limitations
private EventHandler<TouchEventArgs> touchesBeganInvoker, touchesMovedInvoker,
touchesEndedInvoker, touchesCancelledInvoker;
private EventHandler frameStartedInvoker, frameFinishedInvoker;
#endregion
#region Public properties
public static TouchManagerInstance Instance
{
get
{
if (shuttingDown) return null;
if (instance == null)
{
if (!Application.isPlaying) return null;
var objects = FindObjectsOfType<TouchManagerInstance>();
if (objects.Length == 0)
{
var go = new GameObject("TouchManager Instance");
instance = go.AddComponent<TouchManagerInstance>();
}
else if (objects.Length >= 1)
{
instance = objects[0];
}
}
return instance;
}
}
/// <inheritdoc />
public IDisplayDevice DisplayDevice
{
get
{
if (displayDevice == null)
{
displayDevice = ScriptableObject.CreateInstance<GenericDisplayDevice>();
}
return displayDevice;
}
set
{
if (value == null)
{
displayDevice = ScriptableObject.CreateInstance<GenericDisplayDevice>();
}
else
{
displayDevice = value;
}
updateDPI();
}
}
/// <inheritdoc />
public float DPI
{
get { return dpi; }
}
/// <inheritdoc />
public bool ShouldCreateCameraLayer
{
get { return shouldCreateCameraLayer; }
set { shouldCreateCameraLayer = value; }
}
/// <inheritdoc />
public IList<TouchLayer> Layers
{
get { return new ReadOnlyCollection<TouchLayer>(layers); }
}
/// <inheritdoc />
public float DotsPerCentimeter
{
get { return dotsPerCentimeter; }
}
/// <inheritdoc />
public int NumberOfTouches
{
get { return touches.Count; }
}
/// <inheritdoc />
public IList<ITouch> ActiveTouches
{
get { return touches.Cast<ITouch>().ToList(); }
}
#endregion
#region Private variables
private static bool shuttingDown = false;
private static TouchManagerInstance instance;
private Boolean shouldCreateCameraLayer = true;
private IDisplayDevice displayDevice;
private float dpi = 96;
private float dotsPerCentimeter = TouchManager.CM_TO_INCH * 96;
private List<TouchLayer> layers = new List<TouchLayer>(10);
private List<TouchPoint> touches = new List<TouchPoint>(30);
private Dictionary<int, TouchPoint> idToTouch = new Dictionary<int, TouchPoint>(30);
// Upcoming changes
private List<TouchPoint> touchesBegan = new List<TouchPoint>(10);
private HashSet<int> touchesUpdated = new HashSet<int>();
private HashSet<int> touchesEnded = new HashSet<int>();
private HashSet<int> touchesCancelled = new HashSet<int>();
private List<CancelledTouch> touchesManuallyCancelled = new List<CancelledTouch>(10);
private static ObjectPool<TouchPoint> touchPointPool = new ObjectPool<TouchPoint>(10, null, null, (t) => t.INTERNAL_Reset());
private static ObjectPool<List<ITouch>> touchListPool = new ObjectPool<List<ITouch>>(2, () => new List<ITouch>(10), null, (l) => l.Clear());
private static ObjectPool<List<TouchPoint>> touchPointListPool = new ObjectPool<List<TouchPoint>>(1, () => new List<TouchPoint>(10), null, (l) => l.Clear());
private static ObjectPool<List<int>> intListPool = new ObjectPool<List<int>>(1, () => new List<int>(10), null, (l) => l.Clear());
private static ObjectPool<List<CancelledTouch>> cancelledListPool = new ObjectPool<List<CancelledTouch>>(1, () => new List<CancelledTouch>(10), null, (l) => l.Clear());
private int nextTouchId = 0;
#endregion
#region Public methods
/// <inheritdoc />
public bool AddLayer(TouchLayer layer)
{
if (layer == null) return false;
if (layers.Contains(layer)) return true;
layers.Add(layer);
return true;
}
/// <inheritdoc />
public bool AddLayer(TouchLayer layer, int index)
{
if (layer == null) return false;
if (index >= layers.Count) return AddLayer(layer);
var i = layers.IndexOf(layer);
if (i == -1)
{
layers.Insert(index, layer);
}
else
{
if (index == i || i == index - 1) return true;
layers.RemoveAt(i);
if (index < i) layers.Insert(index, layer);
else layers.Insert(index - 1, layer);
}
return true;
}
/// <inheritdoc />
public bool RemoveLayer(TouchLayer layer)
{
if (layer == null) return false;
var result = layers.Remove(layer);
return result;
}
/// <inheritdoc />
public void ChangeLayerIndex(int at, int to)
{
if (at < 0 || at >= layers.Count) return;
if (to < 0 || to >= layers.Count) return;
var data = layers[at];
layers.RemoveAt(at);
layers.Insert(to, data);
}
/// <inheritdoc />
public Transform GetHitTarget(Vector2 position)
{
ITouchHit hit;
TouchLayer layer;
if (GetHitTarget(position, out hit, out layer)) return hit.Transform;
return null;
}
/// <inheritdoc />
public bool GetHitTarget(Vector2 position, out ITouchHit hit)
{
TouchLayer layer;
return GetHitTarget(position, out hit, out layer);
}
/// <inheritdoc />
public bool GetHitTarget(Vector2 position, out ITouchHit hit, out TouchLayer layer)
{
hit = null;
layer = null;
var count = layers.Count;
for (var i = 0; i < count; i++)
{
var touchLayer = layers[i];
if (touchLayer == null) continue;
ITouchHit _hit;
if (touchLayer.Hit(position, out _hit) == TouchLayer.LayerHitResult.Hit)
{
hit = _hit;
layer = touchLayer;
return true;
}
}
return false;
}
/// <inheritdoc />
public void CancelTouch(int id, bool redispatch = false)
{
touchesManuallyCancelled.Add(new CancelledTouch(id, redispatch));
}
#endregion
#region Internal methods
internal ITouch INTERNAL_BeginTouch(Vector2 position)
{
return INTERNAL_BeginTouch(position, null);
}
internal ITouch INTERNAL_BeginTouch(Vector2 position, Tags tags)
{
TouchPoint touch;
lock (touchesBegan)
{
touch = touchPointPool.Get();
touch.INTERNAL_Init(nextTouchId++, position, tags);
touchesBegan.Add(touch);
}
return touch;
}
/// <summary>
/// Update touch without moving it
/// </summary>
/// <param name="id">Touch id</param>
internal void INTERNAL_UpdateTouch(int id)
{
lock (touchesUpdated)
{
if (idToTouch.ContainsKey(id)) touchesUpdated.Add(id);
}
}
internal void INTERNAL_MoveTouch(int id, Vector2 position)
{
lock (touchesUpdated)
{
TouchPoint touch;
if (idToTouch.TryGetValue(id, out touch))
{
touch.INTERNAL_SetPosition(position);
touchesUpdated.Add(id);
}
}
}
/// <inheritdoc />
internal void INTERNAL_EndTouch(int id)
{
lock (touchesEnded)
{
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
// This touch was added this frame
touch = touchesBegan.Find((t) => t.Id == id);
// No touch with such id
if (touch == null) return;
}
touchesEnded.Add(touch.Id);
}
}
/// <inheritdoc />
internal void INTERNAL_CancelTouch(int id)
{
lock (touchesCancelled)
{
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
// This touch was added this frame
touch = touchesBegan.Find((t) => t.Id == id);
// No touch with such id
if (touch == null) return;
}
touchesCancelled.Add(touch.Id);
}
}
#endregion
#region Unity
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(this);
return;
}
gameObject.hideFlags = HideFlags.HideInHierarchy;
DontDestroyOnLoad(gameObject);
updateDPI();
StopAllCoroutines();
StartCoroutine(lateAwake());
touchListPool.WarmUp(2);
touchPointListPool.WarmUp(1);
intListPool.WarmUp(1);
cancelledListPool.WarmUp(1);
#if DEBUG
DebugMode = true;
#endif
}
private void OnLevelWasLoaded(int value)
{
StopAllCoroutines();
StartCoroutine(lateAwake());
}
private IEnumerator lateAwake()
{
yield return null;
updateLayers();
createCameraLayer();
createTouchInput();
}
private void Update()
{
updateTouches();
}
private void OnApplicationQuit()
{
shuttingDown = true;
}
#endregion
#region Private functions
private void updateDPI()
{
dpi = DisplayDevice == null ? 96 : DisplayDevice.DPI;
dotsPerCentimeter = TouchManager.CM_TO_INCH * dpi;
#if DEBUG
debugTouchSize = Vector2.one * dotsPerCentimeter;
#endif
}
private void updateLayers()
{
// filter empty layers
layers = layers.FindAll(l => l != null);
}
private void createCameraLayer()
{
if (layers.Count == 0 && shouldCreateCameraLayer)
{
if (Camera.main != null)
{
if (Application.isEditor) Debug.LogWarning("No camera layers, adding CameraLayer for the main camera. (this message is harmless)");
var layer = Camera.main.gameObject.AddComponent<CameraLayer>();
AddLayer(layer);
}
}
}
private void createTouchInput()
{
var inputs = FindObjectsOfType(typeof(InputSource));
if (inputs.Length == 0)
{
GameObject obj = null;
var objects = FindObjectsOfType<TouchManager>();
if (objects.Length == 0)
{
obj = GameObject.Find("TouchScript");
if (obj == null) obj = new GameObject("TouchScript");
}
else
{
obj = objects[0].gameObject;
}
switch (Application.platform)
{
case RuntimePlatform.IPhonePlayer:
case RuntimePlatform.Android:
case RuntimePlatform.BlackBerryPlayer:
case RuntimePlatform.MetroPlayerARM:
case RuntimePlatform.MetroPlayerX64:
case RuntimePlatform.MetroPlayerX86:
case RuntimePlatform.WP8Player:
obj.AddComponent<MobileInput>();
break;
default:
obj.AddComponent<MouseInput>();
break;
}
}
}
private void updateBegan(List<TouchPoint> points)
{
var count = points.Count;
var list = touchListPool.Get();
var layerCount = layers.Count;
for (var i = 0; i < count; i++)
{
var touch = points[i];
list.Add(touch);
touches.Add(touch);
idToTouch.Add(touch.Id, touch);
for (var j = 0; j< layerCount; j++)
{
var touchLayer = Layers[j];
if (touchLayer == null) continue;
if (touchLayer.INTERNAL_BeginTouch(touch)) break;
}
#if DEBUG
addDebugFigureForTouch(touch);
#endif
}
if (touchesBeganInvoker != null) touchesBeganInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(list));
touchListPool.Release(list);
}
private void updateUpdated(List<int> points)
{
var updatedCount = points.Count;
var list = touchListPool.Get();
// Need to loop through all touches to reset those which did not move
var count = touches.Count;
for (var i = 0; i < count; i++)
{
touches[i].INTERNAL_ResetPosition();
}
for (var i = 0; i < updatedCount; i++)
{
var id = points[i];
var touch = idToTouch[id];
list.Add(touch);
if (touch.Layer != null) touch.Layer.INTERNAL_UpdateTouch(touch);
#if DEBUG
addDebugFigureForTouch(touch);
#endif
}
if (touchesMovedInvoker != null) touchesMovedInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(list));
touchListPool.Release(list);
}
private void updateEnded(List<int> points)
{
var endedCount = points.Count;
var list = touchListPool.Get();
for (var i = 0; i < endedCount; i++)
{
var id = points[i];
var touch = idToTouch[id];
idToTouch.Remove(id);
touches.Remove(touch);
list.Add(touch);
if (touch.Layer != null) touch.Layer.INTERNAL_EndTouch(touch);
#if DEBUG
removeDebugFigureForTouch(touch);
#endif
}
if (touchesEndedInvoker != null) touchesEndedInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(list));
for (var i = 0; i < endedCount; i++) touchPointPool.Release(list[i] as TouchPoint);
touchListPool.Release(list);
}
private void updateCancelled(List<int> points)
{
var cancelledCount = points.Count;
var list = touchListPool.Get();
for (var i = 0; i < cancelledCount; i++)
{
var id = points[i];
var touch = idToTouch[id];
idToTouch.Remove(id);
touches.Remove(touch);
list.Add(touch);
if (touch.Layer != null) touch.Layer.INTERNAL_CancelTouch(touch);
#if DEBUG
removeDebugFigureForTouch(touch);
#endif
}
if (touchesCancelledInvoker != null) touchesCancelledInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(list));
for (var i = 0; i < cancelledCount; i++) touchPointPool.Release(list[i] as TouchPoint);
touchListPool.Release(list);
}
private void updateManuallyCancelled(List<CancelledTouch> points)
{
var cancelledCount = points.Count;
var list = touchListPool.Get();
var redispatchList = touchListPool.Get();
var releaseList = touchListPool.Get();
for (var i = 0; i < cancelledCount; i++)
{
var data = points[i];
var id = data.Id;
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
// might be dead already
continue;
}
if (data.Redispatch)
{
redispatchList.Add(touch);
}
else
{
idToTouch.Remove(id);
touches.Remove(touch);
releaseList.Add(touch);
#if DEBUG
removeDebugFigureForTouch(touch);
#endif
}
list.Add(touch);
if (touch.Layer != null) touch.Layer.INTERNAL_CancelTouch(touch);
}
if (touchesCancelledInvoker != null) touchesCancelledInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(list));
touchListPool.Release(list);
var count = releaseList.Count;
for (var i = 0; i < count; i++) touchPointPool.Release(releaseList[i] as TouchPoint);
touchListPool.Release(releaseList);
count = redispatchList.Count;
if (count > 0)
{
var layerCount = layers.Count;
for (var i = 0; i < count; i++)
{
var touch = redispatchList[i] as TouchPoint;
for (var j = 0; j < layerCount; j++)
{
var touchLayer = Layers[j];
if (touchLayer == null) continue;
if (touchLayer.INTERNAL_BeginTouch(touch)) break;
}
}
if (touchesBeganInvoker != null) touchesBeganInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(redispatchList));
}
touchListPool.Release(redispatchList);
}
private void updateTouches()
{
if (frameStartedInvoker != null) frameStartedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
// need to copy buffers here since they might get updated during execution
if (touchesBegan.Count > 0)
{
var updateList = touchPointListPool.Get();
lock (touchesBegan)
{
updateList.AddRange(touchesBegan);
touchesBegan.Clear();
}
updateBegan(updateList);
touchPointListPool.Release(updateList);
}
if (touchesUpdated.Count > 0)
{
var updateList = intListPool.Get();
lock (touchesUpdated)
{
updateList.AddRange(touchesUpdated);
touchesUpdated.Clear();
}
updateUpdated(updateList);
intListPool.Release(updateList);
}
if (touchesEnded.Count > 0)
{
var updateList = intListPool.Get();
lock (touchesEnded)
{
updateList.AddRange(touchesEnded);
touchesEnded.Clear();
}
updateEnded(updateList);
intListPool.Release(updateList);
}
if (touchesCancelled.Count > 0)
{
var updateList = intListPool.Get();
lock (touchesCancelled)
{
updateList.AddRange(touchesCancelled);
touchesCancelled.Clear();
}
updateCancelled(updateList);
intListPool.Release(updateList);
}
if (touchesManuallyCancelled.Count > 0)
{
var updateList = cancelledListPool.Get();
lock (touchesManuallyCancelled)
{
updateList.AddRange(touchesManuallyCancelled);
touchesManuallyCancelled.Clear();
}
updateManuallyCancelled(updateList);
cancelledListPool.Release(updateList);
}
if (frameFinishedInvoker != null) frameFinishedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
}
#if DEBUG
private Vector2 debugTouchSize;
private void removeDebugFigureForTouch(ITouch touch)
{
GLDebug.RemoveFigure(TouchManager.DEBUG_GL_TOUCH + touch.Id);
}
private void addDebugFigureForTouch(ITouch touch)
{
GLDebug.DrawSquareScreenSpace(TouchManager.DEBUG_GL_TOUCH + touch.Id, touch.Position, 0, debugTouchSize, GLDebug.MULTIPLY, float.PositiveInfinity);
}
#endif
#endregion
#region Structs
private struct CancelledTouch
{
public int Id;
public bool Redispatch;
public CancelledTouch(int id, bool redispatch = false)
{
Id = id;
Redispatch = redispatch;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Tools.ServiceModel.SvcUtil.XmlSerializer
{
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
internal enum SwitchType
{
Flag,
SingletonValue,
ValueList
}
internal class CommandSwitch
{
private readonly string _name;
private readonly string _abbreviation;
private readonly SwitchType _switchType;
internal CommandSwitch(string name, string abbreviation, SwitchType switchType)
{
//ensure that either name doesn't start with '/' or '-'
//also convert to lower-case
if ((name[0] == '/') || (name[0] == '-'))
_name = (name.Substring(1)).ToLower(CultureInfo.InvariantCulture);
else
_name = name.ToLower(CultureInfo.InvariantCulture);
if ((abbreviation[0] == '/') || (abbreviation[0] == '-'))
_abbreviation = (abbreviation.Substring(1)).ToLower(CultureInfo.InvariantCulture);
else
_abbreviation = abbreviation.ToLower(CultureInfo.InvariantCulture);
_switchType = switchType;
}
internal string Name
{
get { return _name; }
}
#if NotUsed
internal string Abbreviation
{
get { return abbreviation; }
}
#endif
internal SwitchType SwitchType
{
get { return _switchType; }
}
internal bool Equals(string other)
{
string temp;
//ensure that compare doesn't start with '/' or '-'
//also convert to lower-case
if ((other[0] == '/') || (other[0] == '-'))
temp = (other.Substring(1)).ToLower(CultureInfo.InvariantCulture);
else
temp = other.ToLower(CultureInfo.InvariantCulture);
//if equal to name, then return the OK
if (_name.Equals(temp))
return true;
//now check abbreviation
return _abbreviation.Equals(temp);
}
internal static CommandSwitch FindSwitch(string name, CommandSwitch[] switches)
{
foreach (CommandSwitch cs in switches)
if (cs.Equals(name))
return cs;
//if no match found, then return null
return null;
}
}
internal class ArgumentDictionary
{
private Dictionary<string, IList<string>> _contents;
internal ArgumentDictionary(int capacity)
{
_contents = new Dictionary<string, IList<string>>(capacity);
}
internal void Add(string key, string value)
{
IList<string> values;
if (!ContainsArgument(key))
{
values = new List<string>();
Add(key, values);
}
else
values = GetArguments(key);
values.Add(value);
}
internal string GetArgument(string key)
{
IList<string> values;
if (_contents.TryGetValue(key.ToLower(CultureInfo.InvariantCulture), out values))
{
#if SM_TOOL
Tool.Assert((values.Count == 1), "contains more than one argument please call GetArguments");
#endif
return values[0];
}
#if SM_TOOL
Tool.Assert(false, "argument was not specified please call ContainsArgument to check this");
#endif
return null; // unreachable code but the compiler doesn't know this.
}
internal IList<string> GetArguments(string key)
{
IList<string> result;
if (!_contents.TryGetValue(key.ToLower(CultureInfo.InvariantCulture), out result))
result = new List<string>();
return result;
}
internal bool ContainsArgument(string key)
{
return _contents.ContainsKey(key.ToLower(CultureInfo.InvariantCulture));
}
internal void Add(string key, IList<string> values)
{
_contents.Add(key.ToLower(CultureInfo.InvariantCulture), values);
}
internal int Count
{
get { return _contents.Count; }
}
}
internal static class CommandParser
{
internal static ArgumentDictionary ParseCommand(string[] cmd, CommandSwitch[] switches)
{
ArgumentDictionary arguments; //switches/values from cmd line
string arg; //argument to test next
CommandSwitch argSwitch; //switch corresponding to that argument
string argValue; //value corresponding to that argument
int delim; //location of value delimiter (':' or '=')
arguments = new ArgumentDictionary(cmd.Length);
foreach (string s in cmd)
{
arg = s;
bool argIsFlag = true;
//if argument does not start with switch indicator, place into "default" arguments
if ((arg[0] != '/') && (arg[0] != '-'))
{
arguments.Add(String.Empty, arg);
continue;
}
//if we have something which begins with '/' or '-', throw if nothing after it
if (arg.Length == 1)
throw new ArgumentException(SR.Format(SR.ErrSwitchMissing, arg));
//yank switch indicator ('/' or '-') off of command argument
arg = arg.Substring(1);
//check to make sure delimiter does not start off switch
delim = arg.IndexOfAny(new char[] { ':', '=' });
if (delim == 0)
throw new ArgumentException(SR.Format(SR.ErrUnexpectedDelimiter));
//if there is no value, than create a null string
if (delim == (-1))
argValue = String.Empty;
else
{
//assume valid argument now; must remove value attached to it
//must avoid copying delimeter into either arguments
argValue = arg.Substring(delim + 1);
arg = arg.Substring(0, delim);
argIsFlag = false;
}
//check if this switch exists in the list of possible switches
//if no match found, then throw an exception
argSwitch = CommandSwitch.FindSwitch(arg.ToLower(CultureInfo.InvariantCulture), switches);
if (argSwitch == null)
{
// Paths start with "/" on Unix, so the arg could potentially be a path.
// If we didn't find any matched option, check and see if it's a path.
string potentialPath = "/" + arg;
if (File.Exists(potentialPath))
{
arguments.Add(string.Empty, potentialPath);
continue;
}
throw new ArgumentException(SR.Format(SR.ErrUnknownSwitch, arg.ToLower(CultureInfo.InvariantCulture)));
}
//check if switch is allowed to have a value
// if not and a value has been specified, then thrown an exception
if (argSwitch.SwitchType == SwitchType.Flag)
{
if (!argIsFlag)
throw new ArgumentException(SR.Format(SR.ErrUnexpectedValue, arg.ToLower(CultureInfo.InvariantCulture)));
}
else
{
if (argIsFlag)
throw new ArgumentException(SR.Format(SR.ErrExpectedValue, arg.ToLower(CultureInfo.InvariantCulture)));
}
//check if switch is allowed to be specified multiple times
// if not and it has already been specified and a new value has been paresd, throw an exception
if (argSwitch.SwitchType != SwitchType.ValueList && arguments.ContainsArgument(argSwitch.Name))
{
throw new ArgumentException(SR.Format(SR.ErrSingleUseSwitch, arg.ToLower(CultureInfo.InvariantCulture)));
}
else
{
arguments.Add(argSwitch.Name, argValue);
}
}
return arguments;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using LanguageExt.ClassInstances;
using LanguageExt.Common;
using LanguageExt.DataTypes.Serialisation;
using static LanguageExt.Prelude;
namespace LanguageExt
{
/// <summary>
/// Equivalent of `Either<Error, A>`
/// Called `Fin` because it is expected to be used as the concrete result of a computation
/// </summary>
[Serializable]
public readonly struct Fin<A> :
IComparable<Fin<A>>,
IComparable,
IEquatable<Fin<A>>,
IEnumerable<Fin<A>>,
ISerializable
{
internal readonly Error error;
internal readonly A value;
public readonly bool IsSucc;
/// <summary>
/// Ctor
/// </summary>
[MethodImpl(Opt.Default)]
internal Fin(in Error error)
{
this.error = error;
this.value = default;
IsSucc = false;
}
/// <summary>
/// Ctor
/// </summary>
[MethodImpl(Opt.Default)]
internal Fin(in A value)
{
this.error = default;
this.value = value;
IsSucc = true;
}
[Pure, MethodImpl(Opt.Default)]
public static Fin<A> Succ(A value) =>
value is null
? throw new ValueIsNullException(nameof(value))
: new Fin<A>(value);
[Pure, MethodImpl(Opt.Default)]
public static Fin<A> Fail(Error error) =>
new Fin<A>(error);
[Pure, MethodImpl(Opt.Default)]
public static Fin<A> Fail(string error) =>
new Fin<A>(Error.New(error));
[Pure]
public bool IsFail
{
[MethodImpl(Opt.Default)]
get => !IsSucc;
}
[Pure]
public bool IsBottom
{
[MethodImpl(Opt.Default)]
get => IsFail && error.IsDefault();
}
/// <summary>
/// Reference version for use in pattern-matching
/// </summary>
[Pure]
public object Case =>
IsSucc
? (object)value
: (object)error;
/// <summary>
/// Equality
/// </summary>
public override bool Equals(object obj) =>
obj is Fin<A> ma && Equals(ma);
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode() =>
IsSucc
? FNV32.OffsetBasis
: Value.GetHashCode();
[Pure, MethodImpl(Opt.Default)]
public static implicit operator Fin<A>(A value) =>
Fin<A>.Succ(value);
[Pure, MethodImpl(Opt.Default)]
public static implicit operator Fin<A>(Error error) =>
Fin<A>.Fail(error);
[Pure, MethodImpl(Opt.Default)]
public static explicit operator A(Fin<A> ma) =>
ma.IsSucc
? ma.Value
: throw new EitherIsNotRightException();
[Pure, MethodImpl(Opt.Default)]
public static explicit operator Error(Fin<A> ma) =>
ma.IsFail
? ma.Error
: throw new EitherIsNotLeftException();
[Pure, MethodImpl(Opt.Default)]
public static Fin<A> operator |(Fin<A> left, Fin<A> right) =>
left.IsSucc
? left
: right;
[Pure, MethodImpl(Opt.Default)]
public static bool operator true(Fin<A> ma) =>
ma.IsSucc;
[Pure, MethodImpl(Opt.Default)]
public static bool operator false(Fin<A> ma) =>
ma.IsFail;
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs < rhs</returns>
[Pure]
public static bool operator <(Fin<A> lhs, A rhs) =>
lhs < FinSucc(rhs);
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs < rhs</returns>
[Pure]
public static bool operator <=(Fin<A> lhs, A rhs) =>
lhs <= FinSucc(rhs);
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs < rhs</returns>
[Pure]
public static bool operator >(Fin<A> lhs, A rhs) =>
lhs > FinSucc(rhs);
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs < rhs</returns>
[Pure]
public static bool operator >=(Fin<A> lhs, A rhs) =>
lhs >= FinSucc(rhs);
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs < rhs</returns>
[Pure]
public static bool operator <(A lhs, Fin<A> rhs) =>
FinSucc(lhs) < rhs;
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs < rhs</returns>
[Pure]
public static bool operator <=(A lhs, Fin<A> rhs) =>
FinSucc(lhs) <= rhs;
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs < rhs</returns>
[Pure]
public static bool operator >(A lhs, Fin<A>rhs) =>
FinSucc(lhs) > rhs;
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs < rhs</returns>
[Pure]
public static bool operator >=(A lhs, Fin<A> rhs) =>
FinSucc(lhs) >= rhs;
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs < rhs</returns>
[Pure]
public static bool operator <(Fin<A> lhs, Fin<A> rhs) =>
lhs.CompareTo(rhs) < 0;
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs <= rhs</returns>
[Pure]
public static bool operator <=(Fin<A> lhs, Fin<A> rhs) =>
lhs.CompareTo(rhs) <= 0;
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs > rhs</returns>
[Pure]
public static bool operator >(Fin<A> lhs, Fin<A> rhs) =>
lhs.CompareTo(rhs) > 0;
/// <summary>
/// Comparison operator
/// </summary>
/// <param name="lhs">The left hand side of the operation</param>
/// <param name="rhs">The right hand side of the operation</param>
/// <returns>True if lhs >= rhs</returns>
[Pure]
public static bool operator >=(Fin<A> lhs, Fin<A> rhs) =>
lhs.CompareTo(rhs) >= 0;
/// <summary>
/// Equality operator override
/// </summary>
[Pure]
public static bool operator ==(Fin<A> lhs, A rhs) =>
lhs.Equals(FinSucc(rhs));
/// <summary>
/// Equality operator override
/// </summary>
[Pure]
public static bool operator ==(A lhs, Fin<A> rhs) =>
FinSucc(lhs).Equals(rhs);
/// <summary>
/// Equality operator override
/// </summary>
[Pure]
public static bool operator ==(Fin<A> lhs, Fin<A> rhs) =>
lhs.Equals(rhs);
/// <summary>
/// Non-equality operator override
/// </summary>
[Pure]
public static bool operator !=(Fin<A> lhs, A rhs) =>
!(lhs == rhs);
/// <summary>
/// Non-equality operator override
/// </summary>
[Pure]
public static bool operator !=(A lhs, Fin<A> rhs) =>
!(lhs == rhs);
/// <summary>
/// Non-equality operator override
/// </summary>
[Pure]
public static bool operator !=(Fin<A> lhs, Fin<A> rhs) =>
!(lhs == rhs);
/// <summary>
/// Equality operator override
/// </summary>
[Pure]
public static bool operator ==(Fin<A> lhs, Error rhs) =>
lhs.Equals(FinFail<A>(rhs));
/// <summary>
/// Equality operator override
/// </summary>
[Pure]
public static bool operator ==(Error lhs, Fin<A> rhs) =>
FinFail<A>(lhs).Equals(rhs);
/// <summary>
/// Non-equality operator override
/// </summary>
[Pure]
public static bool operator !=(Fin<A> lhs, Error rhs) =>
!(lhs == rhs);
/// <summary>
/// Non-equality operator override
/// </summary>
[Pure]
public static bool operator !=(Error lhs, Fin<A> rhs) =>
!(lhs == rhs);
internal A Value
{
[MethodImpl(Opt.Default)]
get => IsSucc
? value
: throw new ValueIsNoneException();
}
internal Error Error
{
[MethodImpl(Opt.Default)]
get => IsBottom
? Errors.Bottom
: error;
}
[Pure, MethodImpl(Opt.Default)]
static Option<T> convert<T>(in object value)
{
if (value == null)
{
return None;
}
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch
{
return None;
}
}
[Pure, MethodImpl(Opt.Default)]
internal Fin<B> Cast<B>() =>
IsSucc
? convert<B>(Value)
.Map(Fin<B>.Succ)
.IfNone(() => Fin<B>.Fail(Error.New($"Can't cast success value of `{nameof(A)}` to `{nameof(B)}` ")))
: Fin<B>.Fail(error);
[Pure, MethodImpl(Opt.Default)]
public int CompareTo(Fin<A> other) =>
IsSucc && other.IsSucc
? default(OrdDefault<A>).Compare(value, other.value)
: !IsSucc && !other.IsSucc
? 0
: IsSucc && !other.IsSucc
? 1
: -1;
[Pure, MethodImpl(Opt.Default)]
public bool Equals(Fin<A> other) =>
(IsSucc && other.IsSucc && default(EqDefault<A>).Equals(value, other.value)) || (IsSucc == false && other.IsSucc == false);
[Pure, MethodImpl(Opt.Default)]
public IEnumerator<Fin<A>> GetEnumerator()
{
if (IsSucc)
{
yield return Value;
}
}
[Pure, MethodImpl(Opt.Default)]
public override string ToString() =>
IsSucc
? $"Succ({Value})"
: $"Fail({Error})";
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("State", IsSucc);
if (IsSucc)
{
info.AddValue("Succ", value);
}
else
{
info.AddValue("Fail", error);
}
}
Fin(SerializationInfo info, StreamingContext context)
{
IsSucc = (bool)info.GetValue("State", typeof(bool));
if (IsSucc)
{
value = (A)info.GetValue("Succ", typeof(A));
error = default;
}
else
{
value = default;
error = (Error)info.GetValue("Fail", typeof(Error));
}
}
IEnumerator IEnumerable.GetEnumerator() =>
GetEnumerator();
[Pure, MethodImpl(Opt.Default)]
public int CompareTo(object obj) =>
obj is Fin<A> t ? CompareTo(t) : 1;
[Pure, MethodImpl(Opt.Default)]
public B Match<B>(Func<A, B> Succ, Func<Error, B> Fail) =>
IsSucc
? Succ(Value)
: Fail(Error);
[MethodImpl(Opt.Default)]
public Unit Match(Action<A> Succ, Action<Error> Fail)
{
if (IsSucc)
{
Succ(Value);
}
else
{
Fail(Error);
}
return default;
}
[Pure, MethodImpl(Opt.Default)]
public A IfFail(Func<Error, A> Fail) =>
IsSucc
? Value
: Fail(Error);
[Pure, MethodImpl(Opt.Default)]
public A IfFail(in A alternative) =>
IsSucc
? Value
: alternative;
[MethodImpl(Opt.Default)]
public Unit IfFail(Action<Error> Fail)
{
if (IsFail)
{
Fail(Error);
}
return default;
}
[MethodImpl(Opt.Default)]
public Unit IfSucc(Action<A> Succ)
{
if (IsSucc)
{
Succ(Value);
}
return default;
}
[MethodImpl(Opt.Default)]
public Unit Iter(Action<A> Succ)
{
if (IsSucc)
{
Succ(Value);
}
return default;
}
[Pure, MethodImpl(Opt.Default)]
public Fin<A> Do(Action<A> Succ)
{
if (IsSucc)
{
Succ(Value);
}
return this;
}
[Pure, MethodImpl(Opt.Default)]
public S Fold<S>(in S state, Func<S, A, S> f) =>
IsSucc
? f(state, Value)
: state;
[Pure, MethodImpl(Opt.Default)]
public S BiFold<S>(in S state, Func<S, A, S> Succ, Func<S, Error, S> Fail) =>
IsSucc
? Succ(state, Value)
: Fail(state, Error);
[Pure, MethodImpl(Opt.Default)]
public bool Exists(Func<A, bool> f) =>
IsSucc && f(Value);
[Pure, MethodImpl(Opt.Default)]
public bool ForAll(Func<A, bool> f) =>
IsFail || (IsSucc && f(Value));
[Pure, MethodImpl(Opt.Default)]
public Fin<B> Map<B>(Func<A, B> f) =>
IsSucc
? Fin<B>.Succ(f(Value))
: Fin<B>.Fail(Error);
[Pure, MethodImpl(Opt.Default)]
public Fin<B> BiMap<B>(Func<A, B> Succ, Func<Error, Error> Fail) =>
IsSucc
? Fin<B>.Succ(Succ(Value))
: Fin<B>.Fail(Fail(Error));
[Pure, MethodImpl(Opt.Default)]
public Fin<B> BiMap<B>(Func<A, B> Succ, Func<Error, B> Fail) =>
IsSucc
? Fin<B>.Succ(Succ(Value))
: Fin<B>.Succ(Fail(Error));
[Pure, MethodImpl(Opt.Default)]
public Fin<B> Select<B>(Func<A, B> f) =>
IsSucc
? Fin<B>.Succ(f(Value))
: Fin<B>.Fail(Error);
[Pure, MethodImpl(Opt.Default)]
public Fin<B> Bind<B>(Func<A, Fin<B>> f) =>
IsSucc
? f(Value)
: Fin<B>.Fail(Error);
[Pure, MethodImpl(Opt.Default)]
public Fin<B> BiBind<B>(Func<A, Fin<B>> Succ, Func<Error, Fin<B>> Fail) =>
IsSucc
? Succ(Value)
: Fail(Error);
[Pure, MethodImpl(Opt.Default)]
public Fin<B> SelectMany<B>(Func<A, Fin<B>> f) =>
IsSucc
? f(Value)
: Fin<B>.Fail(Error);
[Pure, MethodImpl(Opt.Default)]
public Fin<C> SelectMany<B, C>(Func<A, Fin<B>> bind, Func<A, B, C> project)
{
if(IsSucc)
{
var mb = bind(Value);
return mb.IsSucc
? project(value, mb.Value)
: Fin<C>.Fail(mb.Error);
}
else
{
return Fin<C>.Fail(Error);
}
}
[Pure, MethodImpl(Opt.Default)]
public System.Collections.Generic.List<A> ToList() =>
IsSucc
? new System.Collections.Generic.List<A>() { Value }
: new System.Collections.Generic.List<A>();
[Pure, MethodImpl(Opt.Default)]
public Lst<A> ToLst() =>
IsSucc
? List(Value)
: Empty;
[Pure, MethodImpl(Opt.Default)]
public Seq<A> ToSeq() =>
IsSucc
? Seq1(Value)
: Empty;
[Pure, MethodImpl(Opt.Default)]
public Arr<A> ToArr() =>
IsSucc
? Array(Value)
: Empty;
[Pure, MethodImpl(Opt.Default)]
public A[] ToArray() =>
IsSucc
? new A[] {Value}
: new A[0];
[Pure, MethodImpl(Opt.Default)]
public Option<A> ToOption() =>
IsSucc
? Some(Value)
: None;
[Pure, MethodImpl(Opt.Default)]
public OptionAsync<A> ToOptionAsync() =>
IsSucc
? SomeAsync(Value)
: None;
[Pure, MethodImpl(Opt.Default)]
public OptionUnsafe<A> ToOptionUnsafe() =>
IsSucc
? SomeUnsafe(Value)
: None;
[Pure, MethodImpl(Opt.Default)]
public Either<Error, A> ToEither() =>
IsSucc
? Right<Error, A>(Value)
: Left<Error, A>(Error);
[Pure, MethodImpl(Opt.Default)]
public EitherUnsafe<Error, A> ToEitherUnsafe() =>
IsSucc
? RightUnsafe<Error, A>(Value)
: LeftUnsafe<Error, A>(Error);
[Pure, MethodImpl(Opt.Default)]
public EitherAsync<Error, A> ToEitherAsync() =>
IsSucc
? RightAsync<Error, A>(Value)
: LeftAsync<Error, A>(Error);
[Pure, MethodImpl(Opt.Default)]
public Eff<A> ToEff() =>
IsSucc
? SuccessEff<A>(Value)
: FailEff<A>(Error);
[Pure, MethodImpl(Opt.Default)]
public Aff<A> ToAff() =>
IsSucc
? SuccessAff<A>(Value)
: FailAff<A>(Error);
public A ThrowIfFail()
{
if (IsFail)
{
Error.Throw();
}
return Value;
}
}
}
| |
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using QuickType;
//
// var getAllEventsResponse = GetAllEventsResponse.FromJson(jsonString);
namespace Visage.Function
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class GetAllEventsResponse
{
[JsonProperty("pagination")]
public Pagination Pagination { get; set; }
[JsonProperty("events")]
public Event[] Events { get; set; }
}
public partial class Event
{
[JsonProperty("name")]
public Description Name { get; set; }
[JsonProperty("description")]
public Description Description { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("vanity_url")]
public Uri VanityUrl { get; set; }
[JsonProperty("start")]
public End Start { get; set; }
[JsonProperty("end")]
public End End { get; set; }
[JsonProperty("organization_id")]
public string OrganizationId { get; set; }
[JsonProperty("created")]
public DateTimeOffset Created { get; set; }
[JsonProperty("changed")]
public DateTimeOffset Changed { get; set; }
[JsonProperty("published")]
public DateTimeOffset Published { get; set; }
[JsonProperty("capacity")]
public long Capacity { get; set; }
[JsonProperty("capacity_is_custom")]
public bool CapacityIsCustom { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("listed")]
public bool Listed { get; set; }
[JsonProperty("shareable")]
public bool Shareable { get; set; }
[JsonProperty("invite_only")]
public bool InviteOnly { get; set; }
[JsonProperty("online_event")]
public bool OnlineEvent { get; set; }
[JsonProperty("show_remaining")]
public bool ShowRemaining { get; set; }
[JsonProperty("tx_time_limit")]
public long TxTimeLimit { get; set; }
[JsonProperty("hide_start_date")]
public bool HideStartDate { get; set; }
[JsonProperty("hide_end_date")]
public bool HideEndDate { get; set; }
[JsonProperty("locale")]
public string Locale { get; set; }
[JsonProperty("is_locked")]
public bool IsLocked { get; set; }
[JsonProperty("privacy_setting")]
public string PrivacySetting { get; set; }
[JsonProperty("is_series")]
public bool IsSeries { get; set; }
[JsonProperty("is_series_parent")]
public bool IsSeriesParent { get; set; }
[JsonProperty("inventory_type")]
public string InventoryType { get; set; }
[JsonProperty("is_reserved_seating")]
public bool IsReservedSeating { get; set; }
[JsonProperty("show_pick_a_seat")]
public bool ShowPickASeat { get; set; }
[JsonProperty("show_seatmap_thumbnail")]
public bool ShowSeatmapThumbnail { get; set; }
[JsonProperty("show_colors_in_seatmap_thumbnail")]
public bool ShowColorsInSeatmapThumbnail { get; set; }
[JsonProperty("source")]
public string Source { get; set; }
[JsonProperty("is_free")]
public bool IsFree { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("summary")]
public string Summary { get; set; }
[JsonProperty("logo_id")]
[JsonConverter(typeof(ParseStringConverter))]
public long LogoId { get; set; }
[JsonProperty("organizer_id")]
public string OrganizerId { get; set; }
[JsonProperty("venue_id")]
[JsonConverter(typeof(ParseStringConverter))]
public long VenueId { get; set; }
[JsonProperty("category_id")]
public object CategoryId { get; set; }
[JsonProperty("subcategory_id")]
public object SubcategoryId { get; set; }
[JsonProperty("format_id")]
[JsonConverter(typeof(ParseStringConverter))]
public long FormatId { get; set; }
[JsonProperty("resource_uri")]
public Uri ResourceUri { get; set; }
[JsonProperty("is_externally_ticketed")]
public bool IsExternallyTicketed { get; set; }
[JsonProperty("logo")]
public Logo Logo { get; set; }
}
public partial class Description
{
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("html")]
public string Html { get; set; }
}
public partial class End
{
[JsonProperty("timezone")]
public string Timezone { get; set; }
[JsonProperty("local")]
public DateTimeOffset Local { get; set; }
[JsonProperty("utc")]
public DateTimeOffset Utc { get; set; }
}
public partial class Logo
{
[JsonProperty("crop_mask")]
public object CropMask { get; set; }
[JsonProperty("original")]
public Original Original { get; set; }
[JsonProperty("id")]
[JsonConverter(typeof(ParseStringConverter))]
public long Id { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("aspect_ratio")]
public string AspectRatio { get; set; }
[JsonProperty("edge_color")]
public string EdgeColor { get; set; }
[JsonProperty("edge_color_set")]
public bool EdgeColorSet { get; set; }
}
public partial class Original
{
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("width")]
public object Width { get; set; }
[JsonProperty("height")]
public object Height { get; set; }
}
public partial class Pagination
{
[JsonProperty("object_count")]
public long ObjectCount { get; set; }
[JsonProperty("page_number")]
public long PageNumber { get; set; }
[JsonProperty("page_size")]
public long PageSize { get; set; }
[JsonProperty("page_count")]
public long PageCount { get; set; }
[JsonProperty("continuation")]
public string Continuation { get; set; }
[JsonProperty("has_more_items")]
public bool HasMoreItems { get; set; }
}
public partial class GetAllEventsResponse
{
public static GetAllEventsResponse FromJson(string json) => JsonConvert.DeserializeObject<GetAllEventsResponse>(json, Visage.Function.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this GetAllEventsResponse self) => JsonConvert.SerializeObject(self, Visage.Function.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
internal class ParseStringConverter : JsonConverter
{
public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);
public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) return null;
var value = serializer.Deserialize<string>(reader);
long l;
if (Int64.TryParse(value, out l))
{
return l;
}
throw new Exception("Cannot unmarshal type long");
}
public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
{
if (untypedValue == null)
{
serializer.Serialize(writer, null);
return;
}
var value = (long)untypedValue;
serializer.Serialize(writer, value.ToString());
return;
}
public static readonly ParseStringConverter Singleton = new ParseStringConverter();
}
}
| |
using System;
using System.IO;
using System.Reflection;
using System.Collections;
namespace Zeus
{
/// <summary>
/// Summary description for FileTools.
/// </summary>
public class FileTools
{
private const string ZEUSHOME_VAR = "ZEUSHOME";
private static string _rootFolder = null;
private static string _assemblyPath = null;
public static string MakeRelative(string pathToChange, string basePath)
{
if (pathToChange.StartsWith(".") || (basePath == string.Empty)) return pathToChange;
string newPath = pathToChange;
DirectoryInfo dirInfoTemplate = new DirectoryInfo( basePath );
DirectoryInfo dirInfoNew = Directory.GetParent( pathToChange );
string p1 = dirInfoTemplate.FullName;
string p2 = dirInfoNew.FullName;
if (p1.EndsWith("\\")) p1 = p1.Remove(p1.Length-1, 1);
if (p2.EndsWith("\\")) p2 = p2.Remove(p2.Length-1, 1);
if (p1 == p2)
{
newPath = "." + pathToChange.Substring( pathToChange.LastIndexOf("\\") );
}
else
{
string[] dirsOriginal = p1.Split('\\');
string[] dirsNew = p2.Split('\\');
int matches = 0;
for (int i = 0; i < dirsOriginal.Length; i++)
{
if (i < dirsNew.Length)
{
if (dirsNew[i] == dirsOriginal[i])
{
matches++;
}
else break;
}
else break;
}
if (matches == 0)
{
newPath = pathToChange;
}
else
{
newPath = string.Empty;
int diff = dirsOriginal.Length - matches;
if (diff == 0)
{
newPath = "." + pathToChange.Substring( pathToChange.LastIndexOf("\\") );
}
for (int i = 0; i < diff; i++)
{
newPath += "..\\";
}
for (int i = (matches); i < dirsNew.Length; i++)
{
newPath += dirsNew[i] + "\\";
}
newPath += pathToChange.Substring( pathToChange.LastIndexOf("\\") + 1 );
}
}
return newPath;
}
public static string MakeAbsolute(string pathToChange, string basePath)
{
string newPath = pathToChange;
DirectoryInfo dinfo = new DirectoryInfo(basePath);
string p1 = dinfo.FullName;
if (!p1.EndsWith("\\")) p1 += "\\";
if (dinfo.Exists)
{
if (pathToChange.StartsWith("\\"))
{
newPath = dinfo.Root + pathToChange;
}
else if ((pathToChange.StartsWith(".")) ||
(pathToChange.IndexOf(":") == -1))
{
newPath = p1 + pathToChange;
}
FileInfo finfo = new FileInfo(newPath);
if (finfo.Exists)
{
newPath = finfo.FullName;
}
else
{
finfo = new FileInfo(pathToChange);
if (finfo.Exists)
{
newPath = finfo.FullName;
}
}
}
return newPath;
}
public static string AssemblyPath
{
get
{
if (_assemblyPath == null)
{
_assemblyPath = Assembly.GetExecutingAssembly().Location;
_assemblyPath = _assemblyPath.Substring(0, _assemblyPath.LastIndexOf(@"\"));
}
return _assemblyPath;
}
}
public static string ApplicationPath
{
get
{
if (_rootFolder == null)
{
_rootFolder = Assembly.GetEntryAssembly().Location;
_rootFolder = _rootFolder.Substring(0, _rootFolder.LastIndexOf(@"\"));
}
return _rootFolder;
}
set
{
_rootFolder = value;
}
}
public static string ResolvePath(string path)
{
return ResolvePath(path, false);
}
public static string ResolvePath(string path, bool useAssemblyPath)
{
string[] items = path.Split('%');
string newpath = string.Empty;
for (int i = 0; i < items.Length; i++)
{
string item = items[i];
if ((i % 2) == 1)
{
if (item == ZEUSHOME_VAR)
{
if (useAssemblyPath)
{
newpath += AssemblyPath;
}
else
{
newpath += ApplicationPath;
}
}
else
{
newpath += Environment.GetEnvironmentVariable(item);
}
}
else
{
newpath += item;
}
}
return newpath;
}
public static ArrayList GetFilenamesRecursive(ArrayList rootPaths, ArrayList extensions)
{
ArrayList filenames = new ArrayList();
DirectoryInfo rootInfo;
if (rootPaths.Count == 0)
rootPaths.Add(Directory.GetCurrentDirectory());
foreach (string rootPath in rootPaths)
{
rootInfo = new DirectoryInfo(ResolvePath(rootPath));
if (rootInfo.Exists)
{
_BuildChildren(rootInfo, filenames, extensions);
}
}
return filenames;
}
private static void _BuildChildren(DirectoryInfo rootInfo, ArrayList filenames, ArrayList extensions)
{
string filename;
foreach (DirectoryInfo dirInfo in rootInfo.GetDirectories())
{
if (dirInfo.Attributes != (FileAttributes.System | dirInfo.Attributes))
{
_BuildChildren(dirInfo, filenames, extensions);
}
}
foreach (FileInfo fileInfo in rootInfo.GetFiles())
{
if (fileInfo.Attributes != (FileAttributes.System | fileInfo.Attributes))
{
if ( extensions.Contains(fileInfo.Extension) )
{
filename = fileInfo.FullName;
if (!filenames.Contains(filename))
{
filenames.Add(filename);
}
}
}
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the SysMedicamentoRubro class.
/// </summary>
[Serializable]
public partial class SysMedicamentoRubroCollection : ActiveList<SysMedicamentoRubro, SysMedicamentoRubroCollection>
{
public SysMedicamentoRubroCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysMedicamentoRubroCollection</returns>
public SysMedicamentoRubroCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysMedicamentoRubro o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Sys_MedicamentoRubro table.
/// </summary>
[Serializable]
public partial class SysMedicamentoRubro : ActiveRecord<SysMedicamentoRubro>, IActiveRecord
{
#region .ctors and Default Settings
public SysMedicamentoRubro()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysMedicamentoRubro(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysMedicamentoRubro(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysMedicamentoRubro(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Sys_MedicamentoRubro", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdMedicamentoRubro = new TableSchema.TableColumn(schema);
colvarIdMedicamentoRubro.ColumnName = "idMedicamentoRubro";
colvarIdMedicamentoRubro.DataType = DbType.Int32;
colvarIdMedicamentoRubro.MaxLength = 0;
colvarIdMedicamentoRubro.AutoIncrement = false;
colvarIdMedicamentoRubro.IsNullable = false;
colvarIdMedicamentoRubro.IsPrimaryKey = true;
colvarIdMedicamentoRubro.IsForeignKey = false;
colvarIdMedicamentoRubro.IsReadOnly = false;
colvarIdMedicamentoRubro.DefaultSetting = @"";
colvarIdMedicamentoRubro.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdMedicamentoRubro);
TableSchema.TableColumn colvarPadre = new TableSchema.TableColumn(schema);
colvarPadre.ColumnName = "padre";
colvarPadre.DataType = DbType.Int32;
colvarPadre.MaxLength = 0;
colvarPadre.AutoIncrement = false;
colvarPadre.IsNullable = true;
colvarPadre.IsPrimaryKey = false;
colvarPadre.IsForeignKey = false;
colvarPadre.IsReadOnly = false;
colvarPadre.DefaultSetting = @"";
colvarPadre.ForeignKeyTableName = "";
schema.Columns.Add(colvarPadre);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 255;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = true;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarRubroPrimerNivel = new TableSchema.TableColumn(schema);
colvarRubroPrimerNivel.ColumnName = "rubroPrimerNivel";
colvarRubroPrimerNivel.DataType = DbType.Int32;
colvarRubroPrimerNivel.MaxLength = 0;
colvarRubroPrimerNivel.AutoIncrement = false;
colvarRubroPrimerNivel.IsNullable = true;
colvarRubroPrimerNivel.IsPrimaryKey = false;
colvarRubroPrimerNivel.IsForeignKey = false;
colvarRubroPrimerNivel.IsReadOnly = false;
colvarRubroPrimerNivel.DefaultSetting = @"";
colvarRubroPrimerNivel.ForeignKeyTableName = "";
schema.Columns.Add(colvarRubroPrimerNivel);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Sys_MedicamentoRubro",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdMedicamentoRubro")]
[Bindable(true)]
public int IdMedicamentoRubro
{
get { return GetColumnValue<int>(Columns.IdMedicamentoRubro); }
set { SetColumnValue(Columns.IdMedicamentoRubro, value); }
}
[XmlAttribute("Padre")]
[Bindable(true)]
public int? Padre
{
get { return GetColumnValue<int?>(Columns.Padre); }
set { SetColumnValue(Columns.Padre, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("RubroPrimerNivel")]
[Bindable(true)]
public int? RubroPrimerNivel
{
get { return GetColumnValue<int?>(Columns.RubroPrimerNivel); }
set { SetColumnValue(Columns.RubroPrimerNivel, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.SysMedicamentoCollection colSysMedicamentoRecords;
public DalSic.SysMedicamentoCollection SysMedicamentoRecords
{
get
{
if(colSysMedicamentoRecords == null)
{
colSysMedicamentoRecords = new DalSic.SysMedicamentoCollection().Where(SysMedicamento.Columns.IdMedicamentoRubro, IdMedicamentoRubro).Load();
colSysMedicamentoRecords.ListChanged += new ListChangedEventHandler(colSysMedicamentoRecords_ListChanged);
}
return colSysMedicamentoRecords;
}
set
{
colSysMedicamentoRecords = value;
colSysMedicamentoRecords.ListChanged += new ListChangedEventHandler(colSysMedicamentoRecords_ListChanged);
}
}
void colSysMedicamentoRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colSysMedicamentoRecords[e.NewIndex].IdMedicamentoRubro = IdMedicamentoRubro;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdMedicamentoRubro,int? varPadre,string varNombre,int? varRubroPrimerNivel)
{
SysMedicamentoRubro item = new SysMedicamentoRubro();
item.IdMedicamentoRubro = varIdMedicamentoRubro;
item.Padre = varPadre;
item.Nombre = varNombre;
item.RubroPrimerNivel = varRubroPrimerNivel;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdMedicamentoRubro,int? varPadre,string varNombre,int? varRubroPrimerNivel)
{
SysMedicamentoRubro item = new SysMedicamentoRubro();
item.IdMedicamentoRubro = varIdMedicamentoRubro;
item.Padre = varPadre;
item.Nombre = varNombre;
item.RubroPrimerNivel = varRubroPrimerNivel;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdMedicamentoRubroColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn PadreColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn RubroPrimerNivelColumn
{
get { return Schema.Columns[3]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdMedicamentoRubro = @"idMedicamentoRubro";
public static string Padre = @"padre";
public static string Nombre = @"nombre";
public static string RubroPrimerNivel = @"rubroPrimerNivel";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colSysMedicamentoRecords != null)
{
foreach (DalSic.SysMedicamento item in colSysMedicamentoRecords)
{
if (item.IdMedicamentoRubro != IdMedicamentoRubro)
{
item.IdMedicamentoRubro = IdMedicamentoRubro;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colSysMedicamentoRecords != null)
{
colSysMedicamentoRecords.SaveAll();
}
}
#endregion
}
}
| |
using System;
using System.IO;
using MiscUtil.Checksum;
namespace MiscUtil.Compression.Vcdiff
{
/// <summary>
/// Decoder for VCDIFF (RFC 3284) streams.
/// </summary>
public sealed class VcdiffDecoder
{
#region Fields
/// <summary>
/// Reader containing original data, if any. May be null.
/// If non-null, will be readable and seekable.
/// </summary>
Stream original;
/// <summary>
/// Stream containing delta data. Will be readable.
/// </summary>
Stream delta;
/// <summary>
/// Stream containing target data. Will be readable,
/// writable and seekable.
/// </summary>
Stream output;
/// <summary>
/// Code table to use for decoding.
/// </summary>
CodeTable codeTable = CodeTable.Default;
/// <summary>
/// Address cache to use when decoding; must be reset before decoding each window.
/// Default to the default size.
/// </summary>
AddressCache cache = new AddressCache(4, 3);
#endregion
#region Constructor
/// <summary>
/// Sole constructor; private to prevent instantiation from
/// outside the class.
/// </summary>
VcdiffDecoder(Stream original, Stream delta, Stream output)
{
this.original = original;
this.delta = delta;
this.output = output;
}
#endregion
#region Public interface
/// <summary>
/// Decodes an original stream and a delta stream, writing to a target stream.
/// The original stream may be null, so long as the delta stream never
/// refers to it. The original and delta streams must be readable, and the
/// original stream (if any) and the target stream must be seekable.
/// The target stream must be writable and readable. The original and target
/// streams are rewound to their starts before any data is read; the relevant data
/// must occur at the beginning of the original stream, and any data already present
/// in the target stream may be overwritten. The delta data must begin
/// wherever the delta stream is currently positioned. The delta stream must end
/// after the last window. The streams are not disposed by this method.
/// </summary>
/// <param name="original">Stream containing delta. May be null.</param>
/// <param name="delta">Stream containing delta data.</param>
/// <param name="output">Stream to write resulting data to.</param>
public static void Decode (Stream original, Stream delta, Stream output)
{
#region Simple argument checking
if (original != null && (!original.CanRead || !original.CanSeek))
{
throw new ArgumentException ("Must be able to read and seek in original stream", "original");
}
if (delta==null)
{
throw new ArgumentNullException("delta");
}
if (!delta.CanRead)
{
throw new ArgumentException ("Unable to read from delta stream");
}
if (output==null)
{
throw new ArgumentNullException("output");
}
if (!output.CanWrite || !output.CanRead || !output.CanSeek)
{
throw new ArgumentException ("Must be able to read, write and seek in output stream", "output");
}
#endregion
// Now the arguments are checked, we construct an instance of the
// class and ask it to do the decoding.
VcdiffDecoder instance = new VcdiffDecoder(original, delta, output);
instance.Decode();
}
#endregion
#region Private methods
/// <summary>
/// Top-level decoding method. When this method exits, all decoding has been performed.
/// </summary>
void Decode()
{
ReadHeader();
while (DecodeWindow());
}
/// <summary>
/// Read the header, including any custom code table. The delta stream is left
/// positioned at the start of the first window.
/// </summary>
void ReadHeader()
{
byte[] header = IOHelper.CheckedReadBytes(delta, 4);
if (header[0] != 0xd6 ||
header[1] != 0xc3 ||
header[2] != 0xc4)
{
throw new VcdiffFormatException("Invalid VCDIFF header in delta stream");
}
if (header[3] != 0)
{
throw new VcdiffFormatException("VcdiffDecoder can only read delta streams of version 0");
}
// Load the header indicator
byte headerIndicator = IOHelper.CheckedReadByte(delta);
if ((headerIndicator&1) != 0)
{
throw new VcdiffFormatException
("VcdiffDecoder does not handle delta stream using secondary compressors");
}
bool customCodeTable = ((headerIndicator&2) != 0);
bool applicationHeader = ((headerIndicator&4) != 0);
if ((headerIndicator & 0xf8) != 0)
{
throw new VcdiffFormatException ("Invalid header indicator - bits 3-7 not all zero.");
}
// Load the custom code table, if there is one
if (customCodeTable)
{
ReadCodeTable();
}
// Ignore the application header if we have one. This tells xdelta3 what the right filenames are.
if (applicationHeader)
{
int appHeaderLength = IOHelper.ReadBigEndian7BitEncodedInt(delta);
IOHelper.CheckedReadBytes(delta, appHeaderLength);
}
}
/// <summary>
/// Reads the custom code table, if there is one
/// </summary>
void ReadCodeTable()
{
// The length given includes the nearSize and sameSize bytes
int compressedTableLength = IOHelper.ReadBigEndian7BitEncodedInt(delta)-2;
int nearSize = IOHelper.CheckedReadByte(delta);
int sameSize = IOHelper.CheckedReadByte(delta);
byte[] compressedTableData = IOHelper.CheckedReadBytes(delta, compressedTableLength);
byte[] defaultTableData = CodeTable.Default.GetBytes();
MemoryStream tableOriginal = new MemoryStream(defaultTableData, false);
MemoryStream tableDelta = new MemoryStream(compressedTableData, false);
byte[] decompressedTableData = new byte[1536];
MemoryStream tableOutput = new MemoryStream(decompressedTableData, true);
VcdiffDecoder.Decode(tableOriginal, tableDelta, tableOutput);
if (tableOutput.Position != 1536)
{
throw new VcdiffFormatException("Compressed code table was incorrect size");
}
codeTable = new CodeTable(decompressedTableData);
cache = new AddressCache(nearSize, sameSize);
}
/// <summary>
/// Reads and decodes a window, returning whether or not there was
/// any more data to read.
/// </summary>
/// <returns>
/// Whether or not the delta stream had reached the end of its data.
/// </returns>
bool DecodeWindow ()
{
int windowIndicator = delta.ReadByte();
// Have we finished?
if (windowIndicator==-1)
{
return false;
}
// The stream to load source data from for this window, if any
Stream sourceStream;
// Where to reposition the source stream to after reading from it, if anywhere
int sourceStreamPostReadSeek=-1;
// xdelta3 uses an undocumented extra bit which indicates that there are an extra
// 4 bytes at the end of the encoding for the window
bool hasAdler32Checksum = ((windowIndicator&4)==4);
// Get rid of the checksum bit for the rest
windowIndicator &= 0xfb;
// Work out what the source data is, and detect invalid window indicators
switch (windowIndicator&3)
{
// No source data used in this window
case 0:
sourceStream = null;
break;
// Source data comes from the original stream
case 1:
if (original==null)
{
throw new VcdiffFormatException
("Source stream requested by delta but not provided by caller.");
}
sourceStream = original;
break;
case 2:
sourceStream = output;
sourceStreamPostReadSeek = (int)output.Position;
break;
case 3:
throw new VcdiffFormatException
("Invalid window indicator - bits 0 and 1 both set.");
default:
throw new VcdiffFormatException("Invalid window indicator - bits 3-7 not all zero.");
}
// Read the source data, if any
byte[] sourceData = null;
int sourceLength = 0;
if (sourceStream != null)
{
sourceLength = IOHelper.ReadBigEndian7BitEncodedInt(delta);
int sourcePosition = IOHelper.ReadBigEndian7BitEncodedInt(delta);
sourceStream.Position = sourcePosition;
sourceData = IOHelper.CheckedReadBytes(sourceStream, sourceLength);
// Reposition the source stream if appropriate
if (sourceStreamPostReadSeek != -1)
{
sourceStream.Position = sourceStreamPostReadSeek;
}
}
// Read how long the delta encoding is - then ignore it
IOHelper.ReadBigEndian7BitEncodedInt(delta);
// Read how long the target window is
int targetLength = IOHelper.ReadBigEndian7BitEncodedInt(delta);
byte[] targetData = new byte[targetLength];
MemoryStream targetDataStream = new MemoryStream(targetData, true);
// Read the indicator and the lengths of the different data sections
byte deltaIndicator = IOHelper.CheckedReadByte(delta);
if (deltaIndicator != 0)
{
throw new VcdiffFormatException("VcdiffDecoder is unable to handle compressed delta sections.");
}
int addRunDataLength = IOHelper.ReadBigEndian7BitEncodedInt(delta);
int instructionsLength = IOHelper.ReadBigEndian7BitEncodedInt(delta);
int addressesLength = IOHelper.ReadBigEndian7BitEncodedInt(delta);
// If we've been given a checksum, we have to read it and we might as well
// use it to check the data.
int checksumInFile=0;
if (hasAdler32Checksum)
{
byte[] checksumBytes = IOHelper.CheckedReadBytes(delta, 4);
checksumInFile = (checksumBytes[0]<<24) |
(checksumBytes[1]<<16) |
(checksumBytes[2]<<8) |
checksumBytes[3];
}
// Read all the data for this window
byte[] addRunData = IOHelper.CheckedReadBytes(delta, addRunDataLength);
byte[] instructions = IOHelper.CheckedReadBytes(delta, instructionsLength);
byte[] addresses = IOHelper.CheckedReadBytes(delta, addressesLength);
int addRunDataIndex = 0;
MemoryStream instructionStream = new MemoryStream(instructions, false);
cache.Reset(addresses);
while (true)
{
int instructionIndex = instructionStream.ReadByte();
if (instructionIndex==-1)
{
break;
}
for (int i=0; i < 2; i++)
{
Instruction instruction = codeTable[instructionIndex, i];
int size = instruction.Size;
if (size==0 && instruction.Type != InstructionType.NoOp)
{
size = IOHelper.ReadBigEndian7BitEncodedInt(instructionStream);
}
switch (instruction.Type)
{
case InstructionType.NoOp:
break;
case InstructionType.Add:
targetDataStream.Write(addRunData, addRunDataIndex, size);
addRunDataIndex += size;
break;
case InstructionType.Copy:
int addr = cache.DecodeAddress((int)targetDataStream.Position+sourceLength, instruction.Mode);
if (sourceData != null && addr < sourceData.Length)
{
targetDataStream.Write(sourceData, addr, size);
}
else // Data is in target data
{
// Get rid of the offset
addr -= sourceLength;
// Can we just ignore overlap issues?
if (addr + size < targetDataStream.Position)
{
targetDataStream.Write(targetData, addr, size);
}
else
{
for (int j=0; j < size; j++)
{
targetDataStream.WriteByte(targetData[addr++]);
}
}
}
break;
case InstructionType.Run:
byte data = addRunData[addRunDataIndex++];
for (int j=0; j < size; j++)
{
targetDataStream.WriteByte(data);
}
break;
default:
throw new VcdiffFormatException("Invalid instruction type found.");
}
}
}
output.Write(targetData, 0, targetLength);
if (hasAdler32Checksum)
{
int actualChecksum = Adler32.ComputeChecksum(1, targetData);
if (actualChecksum != checksumInFile)
{
throw new VcdiffFormatException("Invalid checksum after decoding window");
}
}
return true;
}
#endregion
}
}
| |
namespace AngleSharp.Core.Tests.Library
{
using AngleSharp.Browser;
using AngleSharp.Core.Tests.Mocks;
using AngleSharp.Dom;
using NUnit.Framework;
using System;
using System.Linq;
using System.Threading.Tasks;
[TestFixture]
public class MutationObserverTests
{
private static IDocument Html(String code, Boolean defer = false)
{
var config = Configuration.Default;
if (defer)
{
config = config.With<IEventLoop>(ctx => new StandingEventLoop());
}
return code.ToHtmlDocument(config);
}
[Test]
public void ConnectMutationObserverChildNodesTriggerManually()
{
var called = false;
var observer = new MutationObserver((mut, obs) =>
{
called = true;
Assert.AreEqual(1, mut.Length);
var record = mut[0];
Assert.IsNotNull(record.Added);
Assert.AreEqual(1, record.Added.Length);
});
var document = Html("");
observer.Connect(document.Body, childList: true);
document.Body.AppendChild(document.CreateElement("span"));
Assert.IsTrue(called);
}
[Test]
public void ConnectMutationObserverChildNodesTriggerManuallyFromDocument()
{
var called = false;
var observer = new MutationObserver((mut, obs) =>
{
called = true;
Assert.AreEqual(1, mut.Length);
var record = mut[0];
Assert.IsNotNull(record.Added);
Assert.AreEqual(1, record.Added.Length);
});
var document = Html("");
observer.Connect(document, childList: true, subtree: true);
document.Body.AppendChild(document.CreateElement("span"));
Assert.IsTrue(called);
}
[Test]
public void ConnectMutationObserverAttributesTriggerManually()
{
var called = false;
var attrName = "something";
var attrValue = "test";
var observer = new MutationObserver((mut, obs) =>
{
called = true;
Assert.AreEqual(1, mut.Length);
Assert.AreEqual(attrName, mut[0].AttributeName);
Assert.IsNull(mut[0].PreviousValue);
});
var document = Html("");
observer.Connect(document.Body, attributes: true);
document.Body.SetAttribute(attrName, attrValue);
Assert.IsTrue(called);
}
[Test]
public void ConnectMutationObserverAttributesTriggerManuallyFromDocument()
{
var called = false;
var attrName = "something";
var attrValue = "test";
var observer = new MutationObserver((mut, obs) =>
{
called = true;
Assert.AreEqual(1, mut.Length);
Assert.AreEqual(attrName, mut[0].AttributeName);
Assert.IsNull(mut[0].PreviousValue);
});
var document = Html("");
observer.Connect(document, attributes: true, subtree: true);
document.Body.SetAttribute(attrName, attrValue);
Assert.IsTrue(called);
}
[Test]
public void ConnectMutationObserverMultipleAttributesDescendentTriggerManually()
{
var called1 = false;
var called2 = false;
var called3 = false;
var attrName = "something";
var attrValue = "test";
var document = Html("");
var observer1 = new MutationObserver((mut, obs) =>
{
called1 = true;
Assert.AreEqual(1, mut.Length);
});
observer1.Connect(document.DocumentElement, attributes: true, subtree: true);
var observer2 = new MutationObserver((mut, obs) =>
{
called2 = true;
Assert.AreEqual(0, mut.Length);
});
observer2.Connect(document.DocumentElement, attributes: true, subtree: false);
var observer3 = new MutationObserver((mut, obs) =>
{
called3 = true;
Assert.AreEqual(1, mut.Length);
});
observer3.Connect(document.Body, attributes: true);
document.Body.SetAttribute(attrName, attrValue);
Assert.IsTrue(called1);
Assert.IsFalse(called2);
Assert.IsTrue(called3);
}
[Test]
public void ConnectMutationObserverTextWithDescendentsAndClearOldValueTriggerManually()
{
var called = false;
var text = "something";
var replaced = "different";
var observer = new MutationObserver((mut, obs) =>
{
called = true;
Assert.AreEqual(1, mut.Length);
Assert.IsNull(mut[0].PreviousValue);
var tn = mut[0].Target as TextNode;
Assert.IsNotNull(tn);
Assert.AreEqual(text + replaced, tn.TextContent);
});
var document = Html("");
observer.Connect(document.Body, characterData: true, subtree: true, characterDataOldValue: false);
document.Body.TextContent = text;
var textNode = document.Body.ChildNodes[0] as TextNode;
textNode.Replace(text.Length, 0, replaced);
Assert.IsTrue(called);
}
[Test]
public void ConnectMutationObserverTextWithDescendentsAndExaminingOldValueTriggerManually()
{
var called = false;
var text = "something";
var replaced = "different";
var observer = new MutationObserver((mut, obs) =>
{
called = true;
Assert.AreEqual(1, mut.Length);
Assert.AreEqual(text, mut[0].PreviousValue);
var tn = mut[0].Target as TextNode;
Assert.IsNotNull(tn);
Assert.AreEqual(text + replaced, tn.TextContent);
});
var document = Html("");
observer.Connect(document.Body, characterData: true, subtree: true, characterDataOldValue: true);
document.Body.TextContent = text;
var textNode = document.Body.ChildNodes[0] as TextNode;
textNode.Replace(text.Length, 0, replaced);
Assert.IsTrue(called);
}
[Test]
public void ConnectMutationObserverTextNoDescendentsTriggerManually()
{
var called = false;
var text = "something";
var replaced = "different";
var observer = new MutationObserver((mut, obs) =>
{
called = true;
Assert.AreEqual(0, mut.Length);
});
var document = Html("");
observer.Connect(document.Body, characterData: true, subtree: false);
document.Body.TextContent = text;
var textNode = document.Body.ChildNodes[0] as TextNode;
textNode.Replace(text.Length, 0, replaced);
Assert.IsFalse(called);
}
[Test]
public void ConnectMutationObserverTextNoDescendentsButCreatedTriggerManually()
{
var called = false;
var text = "something";
var observer = new MutationObserver((mut, obs) =>
{
called = true;
Assert.AreEqual(1, mut.Length);
Assert.AreEqual(1, mut[0].Added.Length);
Assert.AreEqual(text, mut[0].Added[0].TextContent);
});
var document = Html("");
observer.Connect(document.Body, subtree: false, childList: true);
document.Body.TextContent = text;
Assert.IsTrue(called);
}
[Test]
public void MutationObserverAttr()
{
var document = Html("", true);
var div = document.CreateElement("div");
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, attributes: true);
div.SetAttribute("a", "A");
div.SetAttribute("a", "B");
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a",
AttributeNamespace = null
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a",
AttributeNamespace = null
});
}
[Test]
public void MutationObserverAttrWithOldvalue()
{
var document = Html("", true);
var div = document.CreateElement("div");
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, attributes: true, attributeOldValue: true);
div.SetAttribute("a", "A");
div.SetAttribute("a", "B");
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a",
AttributeNamespace = null,
PreviousValue = null
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a",
AttributeNamespace = null,
PreviousValue = "A"
});
}
[Test]
public void MutationObserverAttrChangeInSubtreeShouldNotGenereateARecord()
{
var document = Html("");
var div = document.CreateElement("div");
var child = document.CreateElement("div");
div.AppendChild(child);
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, attributes: true);
child.SetAttribute("a", "A");
child.SetAttribute("a", "B");
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 0);
}
[Test]
public void MutationObserverAttrChangeSubtree()
{
var document = Html("", true);
var div = document.CreateElement("div");
var child = document.CreateElement("div");
div.AppendChild(child);
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, attributes: true, subtree: true);
child.SetAttribute("a", "A");
child.SetAttribute("a", "B");
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = child,
AttributeName = "a"
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "attributes",
Target = child,
AttributeName = "a"
});
}
[Test]
public void MutationObserverMultipleObserversOnSameTarget()
{
var document = Html("", true);
var div = document.CreateElement("div");
var observer1 = new MutationObserver((obs, mut) => { });
observer1.Connect(div, attributes: true, attributeOldValue: true);
var observer2 = new MutationObserver((obs, mut) => { });
observer2.Connect(div, attributes: true, attributeFilter: new []{ "b" });
div.SetAttribute("a", "A");
div.SetAttribute("a", "A2");
div.SetAttribute("b", "B");
var records = observer1.Flush().ToArray();
Assert.AreEqual(records.Count(), 3);
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a"
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a",
PreviousValue = "A"
});
AssertRecord(records[2], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "b"
});
records = observer2.Flush().ToArray();
Assert.AreEqual(1, records.Count());
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "b"
});
}
[Test]
public void MutationObserverObserverObservesOnDifferentTarget()
{
var document = Html("", true);
var div = document.CreateElement("div");
var child = document.CreateElement("div");
div.AppendChild(child);
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(child, attributes: true);
observer.Connect(div, attributes: true, subtree: true, attributeOldValue: true);
child.SetAttribute("a", "A");
child.SetAttribute("a", "A2");
child.SetAttribute("b", "B");
var records = observer.Flush().ToArray();
Assert.AreEqual(3, records.Count());
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = child,
AttributeName = "a"
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "attributes",
Target = child,
AttributeName = "a",
PreviousValue = "A"
});
AssertRecord(records[2], new TestMutationRecord
{
Type = "attributes",
Target = child,
AttributeName = "b"
});
}
[Test]
public void MutationObserverObservingOnTheSameNodeShouldUpdateTheOptions()
{
var document = Html("", true);
var div = document.CreateElement("div");
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, attributes: true, attributeFilter: new[] { "a" });
observer.Connect(div, attributes: true, attributeFilter: new[] { "b" });
div.SetAttribute("a", "A");
div.SetAttribute("b", "B");
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 1);
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "b"
});
}
[Test]
public void MutationObserverDisconnectShouldStopAllEventsAndEmptyTheRecords()
{
var document = Html("");
var div = document.CreateElement("div");
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, attributes: true);
div.SetAttribute("a", "A");
observer.Disconnect();
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 0);
div.SetAttribute("b", "B");
records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 0);
}
[Test]
public void MutationObserverDisconnectShouldNotAffectOtherObservers()
{
var document = Html("", true);
var div = document.CreateElement("div");
var observer1 = new MutationObserver((obs, mut) => { });
observer1.Connect(div, attributes: true);
var observer2 = new MutationObserver((obs, mut) => { });
observer2.Connect(div, attributes: true);
div.SetAttribute("a", "A");
observer1.Disconnect();
var records1 = observer1.Flush().ToArray();
Assert.AreEqual(records1.Count(), 0);
var records2 = observer2.Flush().ToArray();
Assert.AreEqual(records2.Count(), 1);
AssertRecord(records2[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a"
});
div.SetAttribute("b", "B");
records1 = observer1.Flush().ToArray();
Assert.AreEqual(records1.Count(), 0);
records2 = observer2.Flush().ToArray();
Assert.AreEqual(records2.Count(), 1);
AssertRecord(records2[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "b"
});
}
[Test]
public async Task MutationObserverOneObserverTwoAttributeChanges()
{
var document = Html("", true);
var div = document.CreateElement("div");
var tcs = new TaskCompletionSource<Boolean>();
var observer = new MutationObserver((records, obs) =>
{
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a",
AttributeNamespace = null
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a",
AttributeNamespace = null
});
tcs.SetResult(true);
});
observer.Connect(div, attributes: true);
div.SetAttribute("a", "A");
div.SetAttribute("a", "B");
await tcs.Task.ConfigureAwait(false);
}
[Test]
public async Task MutationObserverNestedChanges()
{
var document = Html("", true);
var div = document.CreateElement("div");
var fresh = true;
var tcs = new TaskCompletionSource<Boolean>();
var observer = new MutationObserver((records, obs) =>
{
Assert.AreEqual(records.Count(), 1);
if (fresh)
{
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a",
AttributeNamespace = null
});
div.SetAttribute("b", "B");
fresh = false;
}
else
{
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "b",
AttributeNamespace = null
});
tcs.SetResult(true);
}
});
observer.Connect(div, attributes: true);
div.SetAttribute("a", "A");
await tcs.Task.ConfigureAwait(false);
}
[Test]
public void MutationObserverCharacterdata()
{
var document = Html("", true);
var text = document.CreateTextNode("abc");
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(text, characterData: true);
text.TextContent = "def";
text.TextContent = "ghi";
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "characterData",
Target = text
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "characterData",
Target = text
});
}
[Test]
public void MutationObserverCharacterdataWithOldValue()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var text = testDiv.AppendChild(document.CreateTextNode("abc"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(text, characterData: true, characterDataOldValue: true);
text.TextContent = "def";
text.TextContent = "ghi";
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "characterData",
Target = text,
PreviousValue = "abc"
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "characterData",
Target = text,
PreviousValue = "def"
});
}
[Test]
public void MutationObserverCharacterdataChangeInSubtreeShouldNotGenerateARecord()
{
var document = Html("", true);
var div = document.CreateElement("div");
var text = div.AppendChild(document.CreateTextNode("abc"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, characterData: true);
text.TextContent = "def";
text.TextContent = "ghi";
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 0);
}
[Test]
public void MutationObserverCharacterdataChangeInSubtree()
{
var document = Html("", true);
var div = document.CreateElement("div");
var text = div.AppendChild(document.CreateTextNode("abc"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, characterData: true, subtree: true);
text.TextContent = "def";
text.TextContent = "ghi";
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "characterData",
Target = text
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "characterData",
Target = text
});
}
[Test]
public void MutationObserverAppendChild()
{
var document = Html("", true);
var div = document.CreateElement("div");
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, childList: true);
var a = document.CreateElement("a");
var b = document.CreateElement("b");
div.AppendChild(a);
div.AppendChild(b);
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "childList",
Target = div,
Added = ToNodeList(a)
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "childList",
Target = div,
Added = ToNodeList(b),
PreviousSibling = a
});
}
[Test]
public void MutationObserverInsertBefore()
{
var document = Html("", true);
var div = document.CreateElement("div");
var a = document.CreateElement("a");
var b = document.CreateElement("b");
var c = document.CreateElement("c");
div.AppendChild(a);
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, childList: true);
div.InsertBefore(b, a);
div.InsertBefore(c, a);
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "childList",
Target = div,
Added = ToNodeList(b),
NextSibling = a
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "childList",
Target = div,
Added = ToNodeList(c),
NextSibling = a,
PreviousSibling = b
});
}
[Test]
public void MutationObserverRemovechild()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = testDiv.AppendChild(document.CreateElement("div"));
var a = div.AppendChild(document.CreateElement("a"));
var b = div.AppendChild(document.CreateElement("b"));
var c = div.AppendChild(document.CreateElement("c"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, childList: true);
div.RemoveChild(b);
div.RemoveChild(a);
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "childList",
Target = div,
Removed = ToNodeList(b),
NextSibling = c,
PreviousSibling = a
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "childList",
Target = div,
Removed = ToNodeList(a),
NextSibling = c
});
}
[Test]
public void MutationObserverDirectChildren()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = testDiv.AppendChild(document.CreateElement("div"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, childList: true);
var a = document.CreateElement("a");
var b = document.CreateElement("b");
div.AppendChild(a);
div.InsertBefore(b, a);
div.RemoveChild(b);
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 3);
AssertRecord(records[0], new TestMutationRecord
{
Type = "childList",
Target = div,
Added = ToNodeList(a)
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "childList",
Target = div,
NextSibling = a,
Added = ToNodeList(b)
});
AssertRecord(records[2], new TestMutationRecord
{
Type = "childList",
Target = div,
NextSibling = a,
Removed = ToNodeList(b)
});
}
[Test]
public void MutationObserverSubtree()
{
var document = Html("", true);
var div = document.CreateElement("div");
var child = div.AppendChild(document.CreateElement("div"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(child, childList: true);
var a = document.CreateTextNode("a");
var b = document.CreateTextNode("b");
child.AppendChild(a);
child.InsertBefore(b, a);
child.RemoveChild(b);
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 3);
AssertRecord(records[0], new TestMutationRecord
{
Type = "childList",
Target = child,
Added = ToNodeList(a)
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "childList",
Target = child,
NextSibling = a,
Added = ToNodeList(b)
});
AssertRecord(records[2], new TestMutationRecord
{
Type = "childList",
Target = child,
NextSibling = a,
Removed = ToNodeList(b)
});
}
[Test]
public void MutationObserverBothDirectAndSubtree()
{
var document = Html("", true);
var div = document.CreateElement("div");
var child = div.AppendChild(document.CreateElement("div"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, childList: true, subtree: true);
observer.Connect(child, childList: true);
var a = document.CreateTextNode("a");
var b = document.CreateTextNode("b");
child.AppendChild(a);
div.AppendChild(b);
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "childList",
Target = child,
Added = ToNodeList(a)
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "childList",
Target = div,
Added = ToNodeList(b),
PreviousSibling = child
});
}
[Test]
public void MutationObserverAppendMultipleAtOnceAtTheEnd()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = testDiv.AppendChild(document.CreateElement("div"));
div.AppendChild(document.CreateTextNode("a"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, childList: true);
var df = document.CreateDocumentFragment();
var b = df.AppendChild(document.CreateTextNode("b"));
var c = df.AppendChild(document.CreateTextNode("c"));
var d = df.AppendChild(document.CreateTextNode("d"));
div.AppendChild(df);
var records = observer.Flush().ToArray();
var merged = MergeRecords(records);
AssertArrayEqual(merged.Item1, ToNodeList(b, c, d));
AssertArrayEqual(merged.Item2, ToNodeList());
AssertAll(records, new TestMutationRecord
{
Type = "childList",
Target = div
});
}
[Test]
public void MutationObserverAppendMultipleAtOnceAtTheFront()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = testDiv.AppendChild(document.CreateElement("div"));
var a = div.AppendChild(document.CreateTextNode("a"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, childList: true);
var df = document.CreateDocumentFragment();
var b = df.AppendChild(document.CreateTextNode("b"));
var c = df.AppendChild(document.CreateTextNode("c"));
var d = df.AppendChild(document.CreateTextNode("d"));
div.InsertBefore(df, a);
var records = observer.Flush().ToArray();
var merged = MergeRecords(records);
AssertArrayEqual(merged.Item1, ToNodeList(b, c, d));
AssertArrayEqual(merged.Item2, ToNodeList());
AssertAll(records, new TestMutationRecord
{
Type = "childList",
Target = div
});
}
[Test]
public void MutationObserverAppendMultipleAtOnceInTheMiddle()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = document.CreateElement("div");
testDiv.AppendChild(div);
div.AppendChild(document.CreateTextNode("a"));
var b = div.AppendChild(document.CreateTextNode("b"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, childList: true);
var df = document.CreateDocumentFragment();
var c = df.AppendChild(document.CreateTextNode("c"));
var d = df.AppendChild(document.CreateTextNode("d"));
div.InsertBefore(df, b);
var records = observer.Flush().ToArray();
var merged = MergeRecords(records);
AssertArrayEqual(merged.Item1, ToNodeList(c, d));
AssertArrayEqual(merged.Item2, ToNodeList());
AssertAll(records, new TestMutationRecord
{
Type = "childList",
Target = div
});
}
[Test]
public void MutationObserverRemoveAllChildren()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = document.CreateElement("div");
testDiv.AppendChild(div);
var a = div.AppendChild(document.CreateTextNode("a"));
var b = div.AppendChild(document.CreateTextNode("b"));
var c = div.AppendChild(document.CreateTextNode("c"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, childList: true);
div.InnerHtml = "";
var records = observer.Flush().ToArray();
var merged = MergeRecords(records);
AssertArrayEqual(merged.Item1, ToNodeList());
AssertArrayEqual(merged.Item2, ToNodeList(a, b, c));
AssertAll(records, new TestMutationRecord
{
Type = "childList",
Target = div
});
}
[Test]
public void MutationObserverReplaceAllChildrenUsingInnerhtml()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = document.CreateElement("div");
testDiv.AppendChild(div);
var a = div.AppendChild(document.CreateTextNode("a"));
var b = div.AppendChild(document.CreateTextNode("b"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, childList: true);
div.InnerHtml = "<c></c><d></d>";
var c = div.FirstChild;
var d = div.LastChild;
var records = observer.Flush().ToArray();
var merged = MergeRecords(records);
AssertArrayEqual(merged.Item1, ToNodeList(c, d));
AssertArrayEqual(merged.Item2, ToNodeList(a, b));
AssertAll(records, new TestMutationRecord
{
Type = "childList",
Target = div
});
}
[Test]
public void MutationObserverAttrAndCharacterdata()
{
var document = Html("", true);
var div = document.CreateElement("div");
div.AppendChild(document.CreateTextNode("text"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, attributes: true, subtree: true, characterData: true);
div.SetAttribute("a", "A");
div.FirstChild.TextContent = "changed";
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = div,
AttributeName = "a",
AttributeNamespace = null
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "characterData",
Target = div.FirstChild
});
}
[Test]
public void MutationObserverAttrChanged()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = testDiv.AppendChild(document.CreateElement("div"));
var child = document.CreateElement("div");
div.AppendChild(child);
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, attributes: true, subtree: true);
div.RemoveChild(child);
child.SetAttribute("a", "A");
var records = observer.Flush().ToArray();
Assert.AreEqual(1, records.Count());
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = child,
AttributeName = "a",
AttributeNamespace = null
});
child.SetAttribute("b", "B");
records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 1);
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = child,
AttributeName = "b",
AttributeNamespace = null
});
}
[Test]
public void MutationObserverAttrCallback()
{
var document = Html("");
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = testDiv.AppendChild(document.CreateElement("div"));
var child = document.CreateElement("div");
div.AppendChild(child);
var i = 0;
var observer = new MutationObserver((records, obs) =>
{
Assert.LessOrEqual(++i, 2);
Assert.AreEqual(1, records.Count());
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = child,
AttributeName = "a",
AttributeNamespace = null
});
// The transient observers are removed before the callback is called.
child.SetAttribute("b", "B");
records = obs.Flush().ToArray();
Assert.AreEqual(0, records.Count());
});
observer.Connect(div, attributes: true, subtree: true);
div.RemoveChild(child);
child.SetAttribute("a", "A");
observer.Trigger();
}
[Test]
public void MutationObserverAttrMakeSureTransientGetsRemoved()
{
var document = Html("");
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = testDiv.AppendChild(document.CreateElement("div"));
var child = document.CreateElement("div");
div.AppendChild(child);
var i = 0;
var observer = new MutationObserver((records, obs) =>
{
Assert.AreNotEqual(2, ++i);
Assert.AreEqual(records.Count(), 1);
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = child,
AttributeName = "a",
AttributeNamespace = null
});
});
observer.Connect(div, subtree: true, attributes: true);
div.RemoveChild(child);
child.SetAttribute("a", "A");
observer.Trigger();
var div2 = document.CreateElement("div");
var observer2 = new MutationObserver((records, obs) =>
{
Assert.LessOrEqual(++i, 3);
Assert.AreEqual(records.Count(), 1);
AssertRecord(records[0], new TestMutationRecord
{
Type = "attributes",
Target = child,
AttributeName = "b",
AttributeNamespace = null
});
});
observer2.Connect(div2, attributes: true, subtree: true);
div2.AppendChild(child);
child.SetAttribute("b", "B");
observer2.Trigger();
}
[Test]
public void MutationObserverChildListCharacterdata()
{
var document = Html("", true);
var div = document.CreateElement("div");
var child = div.AppendChild(document.CreateTextNode("text"));
var observer = new MutationObserver((obs, mut) => { });
observer.Connect(div, characterData: true, subtree: true);
div.RemoveChild(child);
child.TextContent = "changed";
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 1);
AssertRecord(records[0], new TestMutationRecord
{
Type = "characterData",
Target = child
});
child.TextContent += " again";
records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 1);
AssertRecord(records[0], new TestMutationRecord
{
Type = "characterData",
Target = child
});
}
[Test]
public void MutationObserverCharacterdataCallback()
{
var document = Html("");
var div = document.CreateElement("div");
var child = div.AppendChild(document.CreateTextNode("text"));
var i = 0;
var observer = new MutationObserver((records, obs) =>
{
Assert.LessOrEqual(++i, 2);
Assert.AreEqual(1, records.Count());
AssertRecord(records[0], new TestMutationRecord
{
Type = "characterData",
Target = child
});
// The transient observers are removed before the callback is called.
child.TextContent += " again";
records = obs.Flush().ToArray();
Assert.AreEqual(0, records.Count());
});
observer.Connect(div, characterData: true, subtree: true);
div.RemoveChild(child);
child.TextContent = "changed";
observer.Trigger();
}
[Test]
public void MutationObserverChildlist()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = testDiv.AppendChild(document.CreateElement("div"));
var child = div.AppendChild(document.CreateElement("div"));
var observer = new MutationObserver((mut, obs) => { });
observer.Connect(div, childList: true, subtree: true);
div.RemoveChild(child);
var grandChild = child.AppendChild(document.CreateElement("span"));
var records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 2);
AssertRecord(records[0], new TestMutationRecord
{
Type = "childList",
Target = div,
Removed = ToNodeList(child)
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "childList",
Target = child,
Added = ToNodeList(grandChild)
});
child.RemoveChild(grandChild);
records = observer.Flush().ToArray();
Assert.AreEqual(records.Count(), 1);
AssertRecord(records[0], new TestMutationRecord
{
Type = "childList",
Target = child,
Removed = ToNodeList(grandChild)
});
}
[Test]
public async Task MutationObserverChildlistCallback()
{
var document = Html("", true);
var testDiv = document.Body.AppendChild(document.CreateElement("div"));
var div = testDiv.AppendChild(document.CreateElement("div"));
var child = div.AppendChild(document.CreateElement("div"));
var grandChild = document.CreateElement("span");
var i = 0;
var tcs = new TaskCompletionSource<Boolean>();
var observer = new MutationObserver((records, obs) =>
{
Assert.LessOrEqual(++i, 2);
Assert.AreEqual(2, records.Count());
AssertRecord(records[0], new TestMutationRecord
{
Type = "childList",
Target = div,
Removed = ToNodeList(child)
});
AssertRecord(records[1], new TestMutationRecord
{
Type = "childList",
Target = child,
Added = ToNodeList(grandChild)
});
// The transient observers are removed before the callback is called.
child.RemoveChild(grandChild);
records = obs.Flush().ToArray();
Assert.AreEqual(0, records.Count());
tcs.SetResult(true);
});
observer.Connect(div, childList: true, subtree: true);
div.RemoveChild(child);
child.AppendChild(grandChild);
observer.Trigger();
await tcs.Task.ConfigureAwait(false);
}
private static Tuple<NodeList, NodeList> MergeRecords(IMutationRecord[] records)
{
var added = new NodeList();
var removed = new NodeList();
foreach (var record in records)
{
if (record.Added != null)
{
added.AddRange((NodeList)record.Added);
}
if (record.Removed != null)
{
removed.AddRange((NodeList)record.Removed);
}
}
return Tuple.Create(added, removed);
}
private static void AssertArrayEqual(INodeList actual, INodeList expected)
{
Assert.AreEqual(expected.Length, actual.Length);
for (int i = 0; i < expected.Length; i++)
{
Assert.AreSame(expected[i], actual[i]);
}
}
private static void AssertAll(IMutationRecord[] actualRecords, TestMutationRecord expected)
{
foreach (var actualRecord in actualRecords)
{
Assert.AreEqual(expected.Type, actualRecord.Type);
Assert.AreEqual(expected.Target, actualRecord.Target);
}
}
private static void AssertRecord(IMutationRecord actual, TestMutationRecord expected)
{
Assert.AreEqual(expected.AttributeName, actual.AttributeName);
Assert.AreEqual(expected.AttributeNamespace, actual.AttributeNamespace);
Assert.AreEqual(expected.NextSibling, actual.NextSibling);
Assert.AreEqual(expected.PreviousSibling, actual.PreviousSibling);
Assert.AreEqual(expected.PreviousValue, actual.PreviousValue);
Assert.AreEqual(expected.Type, actual.Type);
Assert.AreEqual(expected.Target, actual.Target);
}
private static INodeList ToNodeList(params INode[] nodes)
{
var list = new NodeList();
foreach (var node in nodes)
{
list.Add((Node)node);
}
return list;
}
private class TestMutationRecord : IMutationRecord
{
public INodeList Added
{
get;
set;
}
public string AttributeName
{
get;
set;
}
public string AttributeNamespace
{
get;
set;
}
public INode NextSibling
{
get;
set;
}
public INode PreviousSibling
{
get;
set;
}
public string PreviousValue
{
get;
set;
}
public INodeList Removed
{
get;
set;
}
public INode Target
{
get;
set;
}
public string Type
{
get;
set;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// Helper class for launching external processes inside of the unity editor.
/// </summary>
public class ExternalProcess : IDisposable
{
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExternalProcessAPI_CreateProcess([MarshalAs(UnmanagedType.LPStr)] string cmdline);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExternalProcessAPI_IsRunning(IntPtr handle);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern void ExternalProcessAPI_SendLine(IntPtr handle, [MarshalAs(UnmanagedType.LPStr)] string line);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExternalProcessAPI_GetLine(IntPtr handle);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern void ExternalProcessAPI_DestroyProcess(IntPtr handle);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
public static extern void ExternalProcessAPI_ConfirmOrBeginProcess([MarshalAs(UnmanagedType.LPStr)] string processName);
private IntPtr mHandle;
/// <summary>
/// First some static utility functions, used by some other code as well.
/// They are related to "external processes" so they appear here.
/// </summary>
private static string sAppDataPath;
public static void Launch(string appName)
{
// Full or relative paths only. Currently unused.
if (!appName.StartsWith(@"\"))
{
appName += @"\";
}
string appPath = AppDataPath + appName;
string appDir = Path.GetDirectoryName(appPath);
Process pr = new Process();
pr.StartInfo.FileName = appPath;
pr.StartInfo.WorkingDirectory = appDir;
pr.Start();
}
private static string AppDataPath
{
get
{
if (string.IsNullOrEmpty(sAppDataPath))
{
sAppDataPath = Application.dataPath.Replace("/", @"\");
}
return sAppDataPath;
}
}
public static bool FindAndLaunch(string appName)
{
return FindAndLaunch(appName, null);
}
public static bool FindAndLaunch(string appName, string args)
{
// Start at working directory, append appName (should read "appRelativePath"), see if it exists.
// If not go up to parent and try again till drive level reached.
string appPath = FindPathToExecutable(appName);
if (appPath == null)
{
return false;
}
string appDir = Path.GetDirectoryName(appPath);
Process pr = new Process();
pr.StartInfo.FileName = appPath;
pr.StartInfo.WorkingDirectory = appDir;
pr.StartInfo.Arguments = args;
return pr.Start();
}
public static string FindPathToExecutable(string appName)
{
// Start at working directory, append appName (should read "appRelativePath"), see if it exists.
// If not go up to parent and try again till drive level reached.
if (!appName.StartsWith(@"\"))
{
appName = @"\" + appName;
}
string searchDir = AppDataPath;
while (searchDir.Length > 3)
{
string appPath = searchDir + appName;
if (File.Exists(appPath))
{
return appPath;
}
searchDir = Path.GetDirectoryName(searchDir);
}
return null;
}
public static string MakeRelativePath(string path1, string path2)
{
// TBD- doesn't really belong in ExternalProcess.
path1 = path1.Replace('\\', '/');
path2 = path2.Replace('\\', '/');
path1 = path1.Replace("\"", "");
path2 = path2.Replace("\"", "");
Uri uri1 = new Uri(path1);
Uri uri2 = new Uri(path2);
Uri relativePath = uri1.MakeRelativeUri(uri2);
return relativePath.OriginalString;
}
/// <summary>
/// The actual ExternalProcess class.
/// </summary>
/// <param name="appName"></param>
/// <returns></returns>
public static ExternalProcess CreateExternalProcess(string appName)
{
return CreateExternalProcess(appName, null);
}
public static ExternalProcess CreateExternalProcess(string appName, string args)
{
// Seems like it would be safer and more informative to call this static method and test for null after.
try
{
return new ExternalProcess(appName, args);
}
catch (Exception ex)
{
UnityEngine.Debug.LogError("Unable to start process " + appName + ", " + ex.Message + ".");
}
return null;
}
private ExternalProcess(string appName, string args)
{
appName = appName.Replace("/", @"\");
string appPath = appName;
if (!File.Exists(appPath))
{
appPath = FindPathToExecutable(appName);
}
if (appPath == null)
{
throw new ArgumentException("Unable to find app " + appPath);
}
// This may throw, calling code should catch the exception.
string launchString = args == null ? appPath : appPath + " " + args;
mHandle = ExternalProcessAPI_CreateProcess(launchString);
}
~ExternalProcess()
{
Dispose(false);
}
public bool IsRunning()
{
try
{
if (mHandle != IntPtr.Zero)
{
return ExternalProcessAPI_IsRunning(mHandle);
}
}
catch
{
Terminate();
}
return false;
}
public bool WaitForStart(float seconds)
{
return WaitFor(seconds, () => { return ExternalProcessAPI_IsRunning(mHandle); });
}
public bool WaitForShutdown(float seconds)
{
return WaitFor(seconds, () => { return !ExternalProcessAPI_IsRunning(mHandle); });
}
public bool WaitFor(float seconds, Func<bool> func)
{
if (seconds <= 0.0f)
seconds = 5.0f;
float end = Time.realtimeSinceStartup + seconds;
bool hasHappened = false;
while (Time.realtimeSinceStartup < end)
{
hasHappened = func();
if (hasHappened)
{
break;
}
Thread.Sleep(Math.Min(500, (int)(seconds * 1000)));
}
return hasHappened;
}
public void SendLine(string line)
{
try
{
if (mHandle != IntPtr.Zero)
{
ExternalProcessAPI_SendLine(mHandle, line);
}
}
catch
{
Terminate();
}
}
public string GetLine()
{
try
{
if (mHandle != IntPtr.Zero)
{
return Marshal.PtrToStringAnsi(ExternalProcessAPI_GetLine(mHandle));
}
}
catch
{
Terminate();
}
return null;
}
public void Terminate()
{
try
{
if (mHandle != IntPtr.Zero)
{
ExternalProcessAPI_DestroyProcess(mHandle);
}
}
catch
{
// TODO: Should we be catching something here?
}
mHandle = IntPtr.Zero;
}
// IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
Terminate();
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.Edm.Expressions;
namespace Microsoft.Data.Edm
{
/// <summary>
/// Contains IsEquivalentTo() extension methods.
/// </summary>
public static class EdmElementComparer
{
/// <summary>
/// Returns true if the compared type is semantically equivalent to this type.
/// Schema types (<see cref="IEdmSchemaType"/>) are compared by their object refs.
/// </summary>
/// <param name="thisType">Type being compared.</param>
/// <param name="otherType">Type being compared to.</param>
/// <returns>Equivalence of the two types.</returns>
public static bool IsEquivalentTo(this IEdmType thisType, IEdmType otherType)
{
if (thisType == otherType)
{
return true;
}
if (thisType == null || otherType == null)
{
return false;
}
if (thisType.TypeKind != otherType.TypeKind)
{
return false;
}
switch (thisType.TypeKind)
{
case EdmTypeKind.Primitive:
return ((IEdmPrimitiveType)thisType).IsEquivalentTo((IEdmPrimitiveType)otherType);
case EdmTypeKind.Complex:
case EdmTypeKind.Entity:
case EdmTypeKind.Enum:
return ((IEdmSchemaType)thisType).IsEquivalentTo((IEdmSchemaType)otherType);
case EdmTypeKind.Collection:
return ((IEdmCollectionType)thisType).IsEquivalentTo((IEdmCollectionType)otherType);
case EdmTypeKind.EntityReference:
return ((IEdmEntityReferenceType)thisType).IsEquivalentTo((IEdmEntityReferenceType)otherType);
case EdmTypeKind.Row:
return ((IEdmRowType)thisType).IsEquivalentTo((IEdmRowType)otherType);
case EdmTypeKind.None:
return otherType.TypeKind == EdmTypeKind.None;
default:
throw new InvalidOperationException(Edm.Strings.UnknownEnumVal_TypeKind(thisType.TypeKind));
}
}
/// <summary>
/// Returns true if the compared type reference is semantically equivalent to this type reference.
/// Schema types (<see cref="IEdmSchemaType"/>) are compared by their object refs.
/// </summary>
/// <param name="thisType">Type reference being compared.</param>
/// <param name="otherType">Type referenced being compared to.</param>
/// <returns>Equivalence of the two type references.</returns>
public static bool IsEquivalentTo(this IEdmTypeReference thisType, IEdmTypeReference otherType)
{
if (thisType == otherType)
{
return true;
}
if (thisType == null || otherType == null)
{
return false;
}
EdmTypeKind typeKind = thisType.TypeKind();
if (typeKind != otherType.TypeKind())
{
return false;
}
if (typeKind == EdmTypeKind.Primitive)
{
return ((IEdmPrimitiveTypeReference)thisType).IsEquivalentTo((IEdmPrimitiveTypeReference)otherType);
}
else
{
return thisType.IsNullable == otherType.IsNullable &&
thisType.Definition.IsEquivalentTo(otherType.Definition);
}
}
/// <summary>
/// Returns true if function signatures are semantically equivalent.
/// Signature includes function name (<see cref="IEdmNamedElement"/>) and its parameter types.
/// </summary>
/// <param name="thisFunction">Reference to the calling object.</param>
/// <param name="otherFunction">Function being compared to.</param>
/// <returns>Equivalence of signatures of the two functions.</returns>
internal static bool IsFunctionSignatureEquivalentTo(this IEdmFunctionBase thisFunction, IEdmFunctionBase otherFunction)
{
if (thisFunction == otherFunction)
{
return true;
}
if (thisFunction.Name != otherFunction.Name)
{
return false;
}
if (!thisFunction.ReturnType.IsEquivalentTo(otherFunction.ReturnType))
{
return false;
}
IEnumerator<IEdmFunctionParameter> otherFunctionParameterEnumerator = otherFunction.Parameters.GetEnumerator();
foreach (IEdmFunctionParameter parameter in thisFunction.Parameters)
{
otherFunctionParameterEnumerator.MoveNext();
if (!parameter.IsEquivalentTo(otherFunctionParameterEnumerator.Current))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns true if the compared function parameter is semantically equivalent to this function parameter.
/// </summary>
/// <param name="thisParameter">Reference to the calling object.</param>
/// <param name="otherParameter">Function parameter being compared to.</param>
/// <returns>Equivalence of the two function parameters.</returns>
private static bool IsEquivalentTo(this IEdmFunctionParameter thisParameter, IEdmFunctionParameter otherParameter)
{
if (thisParameter == otherParameter)
{
return true;
}
if (thisParameter == null || otherParameter == null)
{
return false;
}
return thisParameter.Name == otherParameter.Name &&
thisParameter.Mode == otherParameter.Mode &&
thisParameter.Type.IsEquivalentTo(otherParameter.Type);
}
private static bool IsEquivalentTo(this IEdmPrimitiveType thisType, IEdmPrimitiveType otherType)
{
// ODataLib creates one-off instances of primitive type definitions that match by name and kind, but have different object refs.
// So we can't use object ref comparison here like for other IEdmSchemaType objects.
// See "src\DataWeb\Client\System\Data\Services\Client\Serialization\PrimitiveType.cs:CreateEdmPrimitiveType()" for more info.
return thisType.PrimitiveKind == otherType.PrimitiveKind &&
thisType.FullName() == otherType.FullName();
}
private static bool IsEquivalentTo(this IEdmSchemaType thisType, IEdmSchemaType otherType)
{
return Object.ReferenceEquals(thisType, otherType);
}
private static bool IsEquivalentTo(this IEdmCollectionType thisType, IEdmCollectionType otherType)
{
return thisType.ElementType.IsEquivalentTo(otherType.ElementType);
}
private static bool IsEquivalentTo(this IEdmEntityReferenceType thisType, IEdmEntityReferenceType otherType)
{
return thisType.EntityType.IsEquivalentTo(otherType.EntityType);
}
private static bool IsEquivalentTo(this IEdmRowType thisType, IEdmRowType otherType)
{
if (thisType.DeclaredProperties.Count() != otherType.DeclaredProperties.Count())
{
return false;
}
IEnumerator<IEdmProperty> thisTypePropertyEnumerator = thisType.DeclaredProperties.GetEnumerator();
foreach (IEdmProperty otherTypeProperty in otherType.DeclaredProperties)
{
thisTypePropertyEnumerator.MoveNext();
if (!((IEdmStructuralProperty)thisTypePropertyEnumerator.Current).IsEquivalentTo((IEdmStructuralProperty)otherTypeProperty))
{
return false;
}
}
return true;
}
private static bool IsEquivalentTo(this IEdmStructuralProperty thisProp, IEdmStructuralProperty otherProp)
{
if (thisProp == otherProp)
{
return true;
}
if (thisProp == null || otherProp == null)
{
return false;
}
return thisProp.Name == otherProp.Name &&
thisProp.Type.IsEquivalentTo(otherProp.Type);
}
private static bool IsEquivalentTo(this IEdmPrimitiveTypeReference thisType, IEdmPrimitiveTypeReference otherType)
{
EdmPrimitiveTypeKind thisTypePrimitiveKind = thisType.PrimitiveKind();
if (thisTypePrimitiveKind != otherType.PrimitiveKind())
{
return false;
}
switch (thisTypePrimitiveKind)
{
case EdmPrimitiveTypeKind.Binary:
return ((IEdmBinaryTypeReference)thisType).IsEquivalentTo((IEdmBinaryTypeReference)otherType);
case EdmPrimitiveTypeKind.Decimal:
return ((IEdmDecimalTypeReference)thisType).IsEquivalentTo((IEdmDecimalTypeReference)otherType);
case EdmPrimitiveTypeKind.String:
return ((IEdmStringTypeReference)thisType).IsEquivalentTo((IEdmStringTypeReference)otherType);
case EdmPrimitiveTypeKind.Time:
case EdmPrimitiveTypeKind.DateTime:
case EdmPrimitiveTypeKind.DateTimeOffset:
return ((IEdmTemporalTypeReference)thisType).IsEquivalentTo((IEdmTemporalTypeReference)otherType);
default:
if (thisTypePrimitiveKind.IsSpatial())
{
return ((IEdmSpatialTypeReference)thisType).IsEquivalentTo((IEdmSpatialTypeReference)otherType);
}
else
{
return thisType.IsNullable == otherType.IsNullable &&
thisType.Definition.IsEquivalentTo(otherType.Definition);
}
}
}
private static bool IsEquivalentTo(this IEdmBinaryTypeReference thisType, IEdmBinaryTypeReference otherType)
{
return thisType.IsNullable == otherType.IsNullable &&
thisType.IsFixedLength == otherType.IsFixedLength &&
thisType.IsUnbounded == otherType.IsUnbounded &&
thisType.MaxLength == otherType.MaxLength;
}
private static bool IsEquivalentTo(this IEdmDecimalTypeReference thisType, IEdmDecimalTypeReference otherType)
{
return thisType.IsNullable == otherType.IsNullable &&
thisType.Precision == otherType.Precision &&
thisType.Scale == otherType.Scale;
}
private static bool IsEquivalentTo(this IEdmTemporalTypeReference thisType, IEdmTemporalTypeReference otherType)
{
return thisType.TypeKind() == otherType.TypeKind() &&
thisType.IsNullable == otherType.IsNullable &&
thisType.Precision == otherType.Precision;
}
private static bool IsEquivalentTo(this IEdmStringTypeReference thisType, IEdmStringTypeReference otherType)
{
return thisType.IsNullable == otherType.IsNullable &&
thisType.IsFixedLength == otherType.IsFixedLength &&
thisType.IsUnbounded == otherType.IsUnbounded &&
thisType.MaxLength == otherType.MaxLength &&
thisType.IsUnicode == otherType.IsUnicode &&
thisType.Collation == otherType.Collation;
}
private static bool IsEquivalentTo(this IEdmSpatialTypeReference thisType, IEdmSpatialTypeReference otherType)
{
return thisType.IsNullable == otherType.IsNullable &&
thisType.SpatialReferenceIdentifier == otherType.SpatialReferenceIdentifier;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using ME;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI.Windows.Plugins.Flow;
using System.Text.RegularExpressions;
using FD = UnityEngine.UI.Windows.Plugins.Flow.Data;
using System.Collections;
using UnityEngine.UI.Windows.Plugins.Flow.Data;
using UnityEditor.UI.Windows.Plugins.Flow;
namespace UnityEngine.UI.Windows.Plugins.FlowCompiler {
public static class Tpl {
public class Info {
public string baseNamespace;
public string classname;
public string baseClassname;
public string screenName;
public string containerName;
public string classnameFile {
get {
return string.Format("{0}.cs", this.classname);
}
}
public string baseClassnameFile {
get {
return string.Format("{0}.cs", this.baseClassname);
}
}
public string classnameWithNamespace {
get {
return string.Format("{0}.{1}", this.baseNamespace, this.screenName);
}
}
public string containerClassName {
get {
return this.containerName;
}
}
public Info(FD.FlowWindow window) {
this.baseNamespace = window.compiledNamespace;
this.classname = window.compiledDerivedClassName;
this.baseClassname = window.compiledBaseClassName;
this.screenName = window.directory;
this.containerName = Tpl.GetContainerClassName(window);
}
public Info(string baseNamespace, string classname, string baseClassname, string containerName, string screenName) {
this.baseNamespace = baseNamespace;
this.classname = classname;
this.baseClassname = baseClassname;
this.screenName = screenName;
this.containerName = containerName;
}
public string Replace(string replace, System.Func<string, string> predicate = null) {
replace = replace.Replace("{CLASS_NAME}", this.classname);
replace = replace.Replace("{BASE_CLASS_NAME}", this.baseClassname);
replace = replace.Replace("{NAMESPACE_NAME}", this.baseNamespace);
replace = replace.Replace("{CLASS_NAME_WITH_NAMESPACE}", this.classnameWithNamespace);
if (predicate != null) replace = predicate(replace);
return replace;
}
}
public static string ReplaceText(string text, Info oldInfo, Info newInfo) {
return TemplateGenerator.ReplaceText(text, oldInfo, newInfo);
}
public static string GetNamespace() {
return CompilerSystem.currentNamespace;
}
public static string GetContainerClassName(FD.FlowWindow flowWindow) {
var container = flowWindow.GetParentContainer();
if (container == null) {
return "Container";
}
return Tpl.GetDerivedClassName(container);
}
public static string GetBaseClassName(FD.FlowWindow flowWindow) {
if (flowWindow.IsContainer() == true) {
return string.Format("{0}ContainerBase", flowWindow.directory.UppercaseFirst());
}
return string.Format("{0}ScreenBase", flowWindow.directory.UppercaseFirst());
}
public static string GetDerivedClassName(FD.FlowWindow flowWindow) {
if (flowWindow.IsContainer() == true) {
return string.Format("{0}Container", flowWindow.directory.UppercaseFirst());
}
return string.Format("{0}Screen", flowWindow.directory.UppercaseFirst());
}
public static string GetNamespace(FD.FlowWindow window) {
return string.Format("{0}{1}", Tpl.GetNamespace(), IO.GetRelativePath(window, "."));
}
public static string GetClassNameWithNamespace(FD.FlowWindow window) {
return string.Format("{0}.{1}", Tpl.GetNamespace(window), Tpl.GetDerivedClassName(window));
}
public static string GenerateTransitionMethods(FD.FlowWindow window) {
var flowData = FlowSystem.GetData();
var result = string.Empty;
var transitions = new List<FlowWindow>();
if (window.IsContainer() == true) {
foreach (var attachItem in window.attachItems) {
var attachWindow = flowData.GetWindow(attachItem.targetId);
if (attachWindow.IsContainer() == true) continue;
var items = attachWindow.attachItems.Where(x => { var w = flowData.GetWindow(x.targetId); return w.IsContainer() == false; }).Select(x => flowData.GetWindow(x.targetId));
foreach (var item in items) {
if (transitions.Any(x => x.id == item.id) == false) transitions.Add(item);
}
}
} else {
transitions = flowData.windowAssets.Where(w => window.attachItems.Any((item) => item.targetId == w.id) && !w.IsContainer()).ToList();
}
if (transitions == null) {
return result;
}
foreach (var each in transitions) {
var className = each.directory;
var classNameWithNamespace = Tpl.GetNamespace(each) + "." + Tpl.GetDerivedClassName(each);
if (each.IsShowDefault() == true) {
// Collect all default windows
foreach (var defaultWindowId in FlowSystem.GetDefaultWindows()) {
var defaultWindow = FlowSystem.GetWindow(defaultWindowId);
className = defaultWindow.directory;
classNameWithNamespace = Tpl.GetNamespace(defaultWindow) + "." + Tpl.GetDerivedClassName(defaultWindow);
result += TemplateGenerator.GenerateWindowLayoutTransitionMethod(window, each, className, classNameWithNamespace);
FlowEditorUtilities.CollectCallVariations(each.GetScreen().Load<WindowBase>(), (listTypes, listNames) => {
result += TemplateGenerator.GenerateWindowLayoutTransitionTypedMethod(window, each, className, classNameWithNamespace, listTypes, listNames);
});
}
continue;
} else {
if (each.CanCompiled() == false) continue;
}
result += TemplateGenerator.GenerateWindowLayoutTransitionMethod(window, each, className, classNameWithNamespace);
FlowEditorUtilities.CollectCallVariations(each.GetScreen().Load<WindowBase>(), (listTypes, listNames) => {
result += TemplateGenerator.GenerateWindowLayoutTransitionTypedMethod(window, each, className, classNameWithNamespace, listTypes, listNames);
});
}
var c = 0;
var everyPlatformHasUniqueName = false;
foreach (var attachItem in window.attachItems) {
var attachId = attachItem.targetId;
var attachedWindow = FlowSystem.GetWindow(attachId);
var tmp = UnityEditor.UI.Windows.Plugins.Flow.Flow.IsCompilerTransitionAttachedGeneration(window, attachedWindow);
if (tmp == true) ++c;
}
everyPlatformHasUniqueName = c > 1;
foreach (var attachItem in window.attachItems) {
var attachId = attachItem.targetId;
var attachedWindow = FlowSystem.GetWindow(attachId);
if (attachedWindow.IsShowDefault() == true) {
// Collect all default windows
foreach (var defaultWindowId in FlowSystem.GetDefaultWindows()) {
var defaultWindow = FlowSystem.GetWindow(defaultWindowId);
result += UnityEditor.UI.Windows.Plugins.Flow.Flow.OnCompilerTransitionAttachedGeneration(window, defaultWindow, everyPlatformHasUniqueName);
FlowEditorUtilities.CollectCallVariations(attachedWindow.GetScreen().Load<WindowBase>(), (listTypes, listNames) => {
result += UnityEditor.UI.Windows.Plugins.Flow.Flow.OnCompilerTransitionTypedAttachedGeneration(window, defaultWindow, everyPlatformHasUniqueName, listTypes, listNames);
});
}
result += TemplateGenerator.GenerateWindowLayoutTransitionMethodDefault();
}
/*if (withFunctionRoot == true) {
var functionId = attachedWindow.GetFunctionId();
var functionContainer = flowData.GetWindow(functionId);
if (functionContainer != null) {
var root = flowData.GetWindow(functionContainer.functionRootId);
if (root != null) {
attachedWindow = root;
}
}
}*/
result += UnityEditor.UI.Windows.Plugins.Flow.Flow.OnCompilerTransitionAttachedGeneration(window, attachedWindow, everyPlatformHasUniqueName);
FlowEditorUtilities.CollectCallVariations(attachedWindow.GetScreen().Load<WindowBase>(), (listTypes, listNames) => {
result += UnityEditor.UI.Windows.Plugins.Flow.Flow.OnCompilerTransitionTypedAttachedGeneration(window, attachedWindow, everyPlatformHasUniqueName, listTypes, listNames);
});
}
// Run addons transition logic
result += UnityEditor.UI.Windows.Plugins.Flow.Flow.OnCompilerTransitionGeneration(window);
return result;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm tests the order processing of the backtesting brokerage.
/// We open an equity position that should fill in two parts, on two different bars.
/// We open a long option position and let it expire so we can exercise the position.
/// To check the orders we use OnOrderEvent and throw exceptions if verification fails.
/// </summary>
/// <meta name="tag" content="backtesting brokerage" />
/// <meta name="tag" content="regression test" />
/// <meta name="tag" content="options" />
class BacktestingBrokerageRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Security _security;
private Symbol _spy;
private OrderTicket _equityBuy;
private Option _option;
private Symbol _optionSymbol;
private OrderTicket _optionBuy;
private bool _optionBought = false;
private bool _equityBought = false;
private decimal _optionStrikePrice;
/// <summary>
/// Initialize the algorithm
/// </summary>
public override void Initialize()
{
SetCash(100000);
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 28);
// Get our equity
_security = AddEquity("SPY", Resolution.Hour);
_security.SetFillModel(new PartialMarketFillModel(2));
_spy = _security.Symbol;
// Get our option
_option = AddOption("GOOG");
_option.SetFilter(u => u.IncludeWeeklys()
.Strikes(-2, +2)
.Expiration(TimeSpan.Zero, TimeSpan.FromDays(10)));
_optionSymbol = _option.Symbol;
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!_equityBought && data.ContainsKey(_spy))
{
//Buy our Equity.
//Quantity is rounded down to an even number since it will be split in two equal halves
var quantity = Math.Floor(CalculateOrderQuantity(_spy, .1m) / 2) * 2;
_equityBuy = MarketOrder(_spy, quantity, asynchronous: true);
_equityBought = true;
}
if (!_optionBought)
{
// Buy our option
OptionChain chain;
if (data.OptionChains.TryGetValue(_optionSymbol, out chain))
{
// Find the second call strike under market price expiring today
var contracts = (
from optionContract in chain.OrderByDescending(x => x.Strike)
where optionContract.Right == OptionRight.Call
where optionContract.Expiry == Time.Date
where optionContract.Strike < chain.Underlying.Price
select optionContract
).Take(2);
if (contracts.Any())
{
var optionToBuy = contracts.FirstOrDefault();
_optionStrikePrice = optionToBuy.Strike;
_optionBuy = MarketOrder(optionToBuy.Symbol, 1);
_optionBought = true;
}
}
}
}
/// <summary>
/// All order events get pushed through this function
/// </summary>
/// <param name="orderEvent">OrderEvent object that contains all the information about the event</param>
public override void OnOrderEvent(OrderEvent orderEvent)
{
// Get the order from our transactions
var order = Transactions.GetOrderById(orderEvent.OrderId);
// Based on the type verify the order
switch (order.Type)
{
case OrderType.Market:
VerifyMarketOrder(order, orderEvent);
break;
case OrderType.OptionExercise:
VerifyOptionExercise(order, orderEvent);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// To verify Market orders is process correctly
/// </summary>
/// <param name="order">Order object to analyze</param>
public void VerifyMarketOrder(Order order, OrderEvent orderEvent)
{
switch (order.Status)
{
case OrderStatus.Submitted:
break;
// All PartiallyFilled orders should have a LastFillTime
case OrderStatus.PartiallyFilled:
if (order.LastFillTime == null)
{
throw new Exception("LastFillTime should not be null");
}
if (order.Quantity / 2 != orderEvent.FillQuantity)
{
throw new Exception("Order size should be half");
}
break;
// All filled equity orders should have filled after creation because of our fill model!
case OrderStatus.Filled:
if (order.SecurityType == SecurityType.Equity && order.CreatedTime == order.LastFillTime)
{
throw new Exception("Order should not finish during the CreatedTime bar");
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// To verify OptionExercise orders is process correctly
/// </summary>
/// <param name="order">Order object to analyze</param>
public void VerifyOptionExercise(Order order, OrderEvent orderEvent)
{
// If the option price isn't the same as the strike price, its incorrect
if (order.Price != _optionStrikePrice)
{
throw new Exception("OptionExercise order price should be strike price!!");
}
if (orderEvent.Quantity != -1)
{
throw new Exception("OrderEvent Quantity should be -1");
}
}
/// <summary>
/// Runs after algorithm, used to check our portfolio and orders
/// </summary>
public override void OnEndOfAlgorithm()
{
if (!Portfolio.ContainsKey(_optionBuy.Symbol) || !Portfolio.ContainsKey(_optionBuy.Symbol.Underlying) || !Portfolio.ContainsKey(_equityBuy.Symbol))
{
throw new Exception("Portfolio does not contain the Symbols we purchased");
}
//Check option holding, should not be invested since it expired, profit should be -400
var optionHolding = Portfolio[_optionBuy.Symbol];
if (optionHolding.Invested || optionHolding.Profit != -400)
{
throw new Exception("Options holding does not match expected outcome");
}
//Check the option underlying symbol since we should have bought it at exercise
//Quantity should be 100, AveragePrice should be option strike price
var optionExerciseHolding = Portfolio[_optionBuy.Symbol.Underlying];
if (!optionExerciseHolding.Invested || optionExerciseHolding.Quantity != 100 || optionExerciseHolding.AveragePrice != _optionBuy.Symbol.ID.StrikePrice)
{
throw new Exception("Equity holding for exercised option does not match expected outcome");
}
//Check equity holding, should be invested, profit should be
//Quantity should be 52, AveragePrice should be ticket AverageFillPrice
var equityHolding = Portfolio[_equityBuy.Symbol];
if (!equityHolding.Invested || equityHolding.Quantity != 52 || equityHolding.AveragePrice != _equityBuy.AverageFillPrice)
{
throw new Exception("Equity holding does not match expected outcome");
}
}
/// <summary>
/// PartialMarketFillModel that allows the user to set the number of fills and restricts
/// the fill to only one per bar.
/// </summary>
private class PartialMarketFillModel : ImmediateFillModel
{
private readonly decimal _percent;
private readonly Dictionary<long, decimal> _absoluteRemainingByOrderId = new Dictionary<long, decimal>();
/// <param name="numberOfFills"></param>
public PartialMarketFillModel(int numberOfFills = 1)
{
_percent = 1m / numberOfFills;
}
/// <summary>
/// Performs partial market fills once per time step
/// </summary>
/// <param name="asset">The security being ordered</param>
/// <param name="order">The order</param>
/// <returns>The order fill</returns>
public override OrderEvent MarketFill(Security asset, MarketOrder order)
{
var currentUtcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
// Only fill once a time slice
if (order.LastFillTime != null && currentUtcTime <= order.LastFillTime)
{
return new OrderEvent(order, currentUtcTime, OrderFee.Zero);
}
decimal absoluteRemaining;
if (!_absoluteRemainingByOrderId.TryGetValue(order.Id, out absoluteRemaining))
{
absoluteRemaining = order.AbsoluteQuantity;
_absoluteRemainingByOrderId.Add(order.Id, order.AbsoluteQuantity);
}
var fill = base.MarketFill(asset, order);
var absoluteFillQuantity = (int)(Math.Min(absoluteRemaining, (int)(_percent * order.Quantity)));
fill.FillQuantity = Math.Sign(order.Quantity) * absoluteFillQuantity;
if (absoluteRemaining == absoluteFillQuantity)
{
fill.Status = OrderStatus.Filled;
_absoluteRemainingByOrderId.Remove(order.Id);
}
else
{
absoluteRemaining = absoluteRemaining - absoluteFillQuantity;
_absoluteRemainingByOrderId[order.Id] = absoluteRemaining;
fill.Status = OrderStatus.PartiallyFilled;
}
return fill;
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "-22.717%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.329%"},
{"Sharpe Ratio", "-7.887"},
{"Probabilistic Sharpe Ratio", "1.216%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.001"},
{"Beta", "0.097"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "7.39"},
{"Tracking Error", "0.015"},
{"Treynor Ratio", "-0.131"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0.212"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-73.334"},
{"Portfolio Turnover", "0.425"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "f67306bc706a2cf66288f1cadf6148ed"}
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using Xunit;
public static unsafe class MulticastDelegateTests
{
[Fact]
public static void TestGetInvocationList()
{
DFoo dfoo = new C().Foo;
Delegate[] delegates = dfoo.GetInvocationList();
Assert.NotNull(delegates);
Assert.Equal(delegates.Length, 1);
Assert.True(dfoo.Equals(delegates[0]));
}
[Fact]
public static void TestEquals()
{
C c = new C();
DFoo d1 = c.Foo;
DFoo d2 = c.Foo;
Assert.False(RuntimeHelpers.ReferenceEquals(d1, d2));
bool b;
b = d1.Equals(d2);
Assert.True(b);
Assert.True(d1 == d2);
Assert.False(d1 != d2);
d1 = c.Foo;
d2 = c.Goo;
b = d1.Equals(d2);
Assert.False(b);
Assert.False(d1 == d2);
Assert.True(d1 != d2);
d1 = new C().Foo;
d2 = new C().Foo;
b = d1.Equals(d2);
Assert.False(b);
Assert.False(d1 == d2);
Assert.True(d1 != d2);
DGoo dgoo = c.Foo;
d1 = c.Foo;
b = d1.Equals(dgoo);
Assert.False(b);
int h = d1.GetHashCode();
int h2 = d1.GetHashCode();
Assert.Equal(h, h2);
}
[Fact]
public static void TestCombineReturn()
{
Tracker t = new Tracker();
DRet dret1 = new DRet(t.ARet);
DRet dret2 = new DRet(t.BRet);
DRet dret12 = (DRet)Delegate.Combine(dret1, dret2);
string s = dret12(4);
Assert.Equal(s, "BRet4");
Assert.Equal(t.S, "ARet4BRet4");
return;
}
[Fact]
public static void TestCombine()
{
Tracker t1 = new Tracker();
D a = new D(t1.A);
D b = new D(t1.B);
D c = new D(t1.C);
D d = new D(t1.D);
D nothing = (D)(Delegate.Combine());
Assert.Null(nothing);
D one = (D)(Delegate.Combine(a));
t1.Clear();
one(5);
Assert.Equal(t1.S, "A5");
CheckInvokeList(new D[] { a }, one, t1);
D ab = (D)(Delegate.Combine(a, b));
t1.Clear();
ab(5);
Assert.Equal(t1.S, "A5B5");
CheckInvokeList(new D[] { a, b }, ab, t1);
D abc = (D)(Delegate.Combine(a, b, c));
t1.Clear();
abc(5);
Assert.Equal(t1.S, "A5B5C5");
CheckInvokeList(new D[] { a, b, c }, abc, t1);
D abcdabc = (D)(Delegate.Combine(abc, d, abc));
t1.Clear();
abcdabc(9);
Assert.Equal(t1.S, "A9B9C9D9A9B9C9");
CheckInvokeList(new D[] { a, b, c, d, a, b, c }, abcdabc, t1);
return;
}
[Fact]
public static void TestRemove()
{
Tracker t1 = new Tracker();
D a = new D(t1.A);
D b = new D(t1.B);
D c = new D(t1.C);
D d = new D(t1.D);
D e = new D(t1.E);
D abc = (D)(Delegate.Combine(a, b, c));
D abcdabc = (D)(Delegate.Combine(abc, d, abc));
D ab = (D)(Delegate.Combine(a, b));
D dab = (D)(Delegate.Combine(d, ab));
D abcc = (D)(Delegate.Remove(abcdabc, dab));
t1.Clear();
abcc(9);
string s = t1.S;
Assert.Equal(s, "A9B9C9C9");
CheckInvokeList(new D[] { a, b, c, c }, abcc, t1);
// Pattern-match is based on structural equivalence, not reference equality.
D acopy = new D(t1.A);
D bbba = (D)(Delegate.Combine(b, b, b, acopy));
D bbb = (D)(Delegate.Remove(bbba, a));
t1.Clear();
bbb(9);
Assert.Equal(t1.S, "B9B9B9");
CheckInvokeList(new D[] { b, b, b }, bbb, t1);
// In the case of multiple occurrences, Remove() must remove the last one.
D abcd = (D)(Delegate.Remove(abcdabc, abc));
t1.Clear();
abcd(9);
Assert.Equal(t1.S, "A9B9C9D9");
CheckInvokeList(new D[] { a, b, c, d }, abcd, t1);
D d1 = (D)(Delegate.RemoveAll(abcdabc, abc));
t1.Clear();
d1(9);
s = t1.S;
Assert.Equal(t1.S, "D9");
CheckInvokeList(new D[] { d }, d1, t1);
D nothing = (D)(Delegate.Remove(d1, d1));
Assert.Null(nothing);
// The pattern-not-found case.
D abcd1 = (D)(Delegate.Remove(abcd, null));
t1.Clear();
abcd1(9);
Assert.Equal(t1.S, "A9B9C9D9");
CheckInvokeList(new D[] { a, b, c, d }, abcd1, t1);
// The pattern-not-found case.
D abcd2 = (D)(Delegate.Remove(abcd, e));
t1.Clear();
abcd2(9);
Assert.Equal(t1.S, "A9B9C9D9");
CheckInvokeList(new D[] { a, b, c, d }, abcd2, t1);
// The pattern-not-found case.
D abcd3 = (D)(Delegate.RemoveAll(abcd, null));
t1.Clear();
abcd3(9);
Assert.Equal(t1.S, "A9B9C9D9");
CheckInvokeList(new D[] { a, b, c, d }, abcd3, t1);
// The pattern-not-found case.
D abcd4 = (D)(Delegate.RemoveAll(abcd, e));
t1.Clear();
abcd4(9);
Assert.Equal(t1.S, "A9B9C9D9");
CheckInvokeList(new D[] { a, b, c, d }, abcd4, t1);
return;
}
private static void CheckInvokeList(D[] expected, D combo, Tracker target)
{
Delegate[] invokeList = combo.GetInvocationList();
Assert.Equal(invokeList.Length, expected.Length);
for (int i = 0; i < expected.Length; i++)
{
CheckIsSingletonDelegate((D)(expected[i]), (D)(invokeList[i]), target);
}
Assert.True(Object.ReferenceEquals(combo.Target, expected[expected.Length - 1].Target));
Assert.True(Object.ReferenceEquals(combo.Target, target));
}
private static void CheckIsSingletonDelegate(D expected, D actual, Tracker target)
{
Assert.True(expected.Equals(actual));
Delegate[] invokeList = actual.GetInvocationList();
Assert.Equal(invokeList.Length, 1);
bool b = actual.Equals(invokeList[0]);
Assert.True(b);
target.Clear();
expected(9);
string sExpected = target.S;
target.Clear();
actual(9);
string sActual = target.S;
Assert.Equal(sExpected, sActual);
Assert.True(Object.ReferenceEquals(target, actual.Target));
}
private class Tracker
{
public Tracker()
{
S = "";
}
public string S;
public void Clear()
{
S = "";
}
public void A(int x)
{
S = S + "A" + x;
}
public string ARet(int x)
{
S = S + "ARet" + x;
return "ARet" + x;
}
public void B(int x)
{
S = S + "B" + x;
}
public string BRet(int x)
{
S = S + "BRet" + x;
return "BRet" + x;
}
public void C(int x)
{
S = S + "C" + x;
}
public void D(int x)
{
S = S + "D" + x;
}
public void E(int x)
{
S = S + "E" + x;
}
public void F(int x)
{
S = S + "F" + x;
}
}
private delegate void D(int x);
private delegate string DRet(int x);
private delegate string DFoo(int x);
private delegate string DGoo(int x);
private class C
{
public string Foo(int x)
{
return new string('A', x);
}
public string Goo(int x)
{
return new string('A', x);
}
}
}
| |
/* generated by servant-csharp */
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
#region type alias
using Postcode = System.String;
using Tel = System.String;
using Fax = System.String;
using Emailaddress = System.String;
using ISBN = System.String;
using AddressId = System.Int64;
using AuthorId = System.Int64;
using PublisherId = System.Int64;
using AuthorName = System.String;
using PublisherName = System.String;
using BookId = System.Int64;
#endregion
namespace ServantClientBook
{
#region Address
[JsonObject("Address")]
public class Address
{
[JsonProperty(PropertyName = "addressId")]
public Nullable<AddressId> addressId { get; set; }
[JsonProperty(PropertyName = "postcode")]
public Postcode postcode { get; set; }
[JsonProperty(PropertyName = "prefecture")]
[JsonConverter(typeof(StringEnumConverter))]
public Prefecture prefecture { get; set; }
[JsonProperty(PropertyName = "address")]
public string address { get; set; }
[JsonProperty(PropertyName = "building")]
public string building { get; set; }
[JsonProperty(PropertyName = "tel")]
public Tel tel { get; set; }
[JsonProperty(PropertyName = "fax")]
public Fax fax { get; set; }
[JsonProperty(PropertyName = "email")]
public Emailaddress email { get; set; }
[JsonProperty(PropertyName = "createdAt")]
public DateTime createdAt { get; set; }
[JsonProperty(PropertyName = "updatedAt")]
public DateTime updatedAt { get; set; }
}
#endregion
#region AddressQueryCondition
[JsonObject("AddressQueryCondition")]
public class AddressQueryCondition
{
[JsonProperty(PropertyName = "postCodeLike")]
public string postCodeLike { get; set; }
[JsonProperty(PropertyName = "telLike")]
public string telLike { get; set; }
[JsonProperty(PropertyName = "faxLike")]
public string faxLike { get; set; }
[JsonProperty(PropertyName = "emailLike")]
public string emailLike { get; set; }
}
#endregion
#region AddressList
[JsonObject("AddressList")]
public class AddressList
{
[JsonProperty(PropertyName = "hits")]
public int hits { get; set; }
[JsonProperty(PropertyName = "page")]
public int page { get; set; }
[JsonProperty(PropertyName = "per_page")]
public int per_page { get; set; }
[JsonProperty(PropertyName = "result")]
public List<Address> result { get; set; }
}
#endregion
#region Author
[JsonObject("Author")]
public class Author
{
[JsonProperty(PropertyName = "authorId")]
public Nullable<AuthorId> authorId { get; set; }
[JsonProperty(PropertyName = "name")]
public string name { get; set; }
[JsonProperty(PropertyName = "gender")]
[JsonConverter(typeof(StringEnumConverter))]
public Gender gender { get; set; }
[JsonProperty(PropertyName = "birth")]
[JsonConverter(typeof(DayConverter))]
public DateTime birth { get; set; }
[JsonProperty(PropertyName = "age")]
public int age { get; set; }
[JsonProperty(PropertyName = "address")]
public Address address { get; set; }
[JsonProperty(PropertyName = "createdAt")]
public DateTime createdAt { get; set; }
[JsonProperty(PropertyName = "updatedAt")]
public DateTime updatedAt { get; set; }
}
#endregion
#region AuthorQueryCondition
[JsonObject("AuthorQueryCondition")]
public class AuthorQueryCondition
{
[JsonProperty(PropertyName = "authorNameLike")]
public string authorNameLike { get; set; }
[JsonProperty(PropertyName = "genderEq")]
[JsonConverter(typeof(StringEnumConverter))]
public Gender? genderEq { get; set; }
[JsonProperty(PropertyName = "ageFrom")]
public int? ageFrom { get; set; }
[JsonProperty(PropertyName = "ageTo")]
public int? ageTo { get; set; }
[JsonProperty(PropertyName = "prefectureIn", ItemConverterType = typeof(StringEnumConverter))]
public List<Prefecture> prefectureIn { get; set; }
}
#endregion
#region AuthorList
[JsonObject("AuthorList")]
public class AuthorList
{
[JsonProperty(PropertyName = "hits")]
public int hits { get; set; }
[JsonProperty(PropertyName = "page")]
public int page { get; set; }
[JsonProperty(PropertyName = "per_page")]
public int per_page { get; set; }
[JsonProperty(PropertyName = "result")]
public List<Author> result { get; set; }
}
#endregion
#region Publisher
[JsonObject("Publisher")]
public class Publisher
{
[JsonProperty(PropertyName = "publisherId")]
public Nullable<PublisherId> publisherId { get; set; }
[JsonProperty(PropertyName = "name")]
public string name { get; set; }
[JsonProperty(PropertyName = "companyType")]
[JsonConverter(typeof(StringEnumConverter))]
public CompanyType companyType { get; set; }
[JsonProperty(PropertyName = "address")]
public Address address { get; set; }
[JsonProperty(PropertyName = "createdAt")]
public DateTime createdAt { get; set; }
[JsonProperty(PropertyName = "updatedAt")]
public DateTime updatedAt { get; set; }
}
#endregion
#region PublisherQueryCondition
[JsonObject("PublisherQueryCondition")]
public class PublisherQueryCondition
{
[JsonProperty(PropertyName = "publisherNameLike")]
public string publisherNameLike { get; set; }
[JsonProperty(PropertyName = "companyTypeIn", ItemConverterType = typeof(StringEnumConverter))]
public List<CompanyType> companyTypeIn { get; set; }
[JsonProperty(PropertyName = "prefectureIn", ItemConverterType = typeof(StringEnumConverter))]
public List<Prefecture> prefectureIn { get; set; }
}
#endregion
#region PublisherList
[JsonObject("PublisherList")]
public class PublisherList
{
[JsonProperty(PropertyName = "hits")]
public int hits { get; set; }
[JsonProperty(PropertyName = "page")]
public int page { get; set; }
[JsonProperty(PropertyName = "per_page")]
public int per_page { get; set; }
[JsonProperty(PropertyName = "result")]
public List<Publisher> result { get; set; }
}
#endregion
#region AuthorInfo
[JsonObject("AuthorInfo")]
public class AuthorInfo
{
[JsonProperty(PropertyName = "authorId")]
public AuthorId authorId { get; set; }
[JsonProperty(PropertyName = "name")]
public AuthorName name { get; set; }
}
#endregion
#region PublisherInfo
[JsonObject("PublisherInfo")]
public class PublisherInfo
{
[JsonProperty(PropertyName = "publisherId")]
public PublisherId publisherId { get; set; }
[JsonProperty(PropertyName = "name")]
public PublisherName name { get; set; }
}
#endregion
#region Book
[JsonObject("Book")]
public class Book
{
[JsonProperty(PropertyName = "bookId")]
public Nullable<BookId> bookId { get; set; }
[JsonProperty(PropertyName = "title")]
public string title { get; set; }
[JsonProperty(PropertyName = "isbn")]
public ISBN isbn { get; set; }
[JsonProperty(PropertyName = "category")]
[JsonConverter(typeof(StringEnumConverter))]
public Category category { get; set; }
[JsonProperty(PropertyName = "description")]
public string description { get; set; }
[JsonProperty(PropertyName = "publishedBy")]
public PublisherInfo publishedBy { get; set; }
[JsonProperty(PropertyName = "authors")]
public List<AuthorInfo> authors { get; set; }
[JsonProperty(PropertyName = "publishedAt")]
[JsonConverter(typeof(DayConverter))]
public DateTime publishedAt { get; set; }
[JsonProperty(PropertyName = "createdAt")]
public DateTime createdAt { get; set; }
[JsonProperty(PropertyName = "updatedAt")]
public DateTime updatedAt { get; set; }
}
#endregion
#region BookQueryCondition
[JsonObject("BookQueryCondition")]
public class BookQueryCondition
{
[JsonProperty(PropertyName = "bookIdEq")]
public Nullable<BookId> bookIdEq { get; set; }
[JsonProperty(PropertyName = "bookIdIn")]
public List<BookId> bookIdIn { get; set; }
[JsonProperty(PropertyName = "isbnEq")]
public ISBN isbnEq { get; set; }
[JsonProperty(PropertyName = "categoryIn", ItemConverterType = typeof(StringEnumConverter))]
public List<Category> categoryIn { get; set; }
[JsonProperty(PropertyName = "authorNameLike")]
public string authorNameLike { get; set; }
[JsonProperty(PropertyName = "publisherNameLike")]
public string publisherNameLike { get; set; }
[JsonProperty(PropertyName = "publishedFrom")]
[JsonConverter(typeof(DayConverter))]
public DateTime? publishedFrom { get; set; }
[JsonProperty(PropertyName = "publishedTo")]
[JsonConverter(typeof(DayConverter))]
public DateTime? publishedTo { get; set; }
}
#endregion
#region BookList
[JsonObject("BookList")]
public class BookList
{
[JsonProperty(PropertyName = "hits")]
public int hits { get; set; }
[JsonProperty(PropertyName = "page")]
public int page { get; set; }
[JsonProperty(PropertyName = "per_page")]
public int per_page { get; set; }
[JsonProperty(PropertyName = "result")]
public List<Book> result { get; set; }
}
#endregion
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Automation;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Profiling;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Win32;
using TestUtilities;
using TestUtilities.Python;
using TestUtilities.UI;
using TestUtilities.UI.Python;
using Task = System.Threading.Tasks.Task;
namespace ProfilingUITests {
public class ProfilingUITests {
#region Test Cases
public void DefaultInterpreterSelected(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var service = app.InterpreterService;
var options = app.OptionsService;
var originalDefault = options.DefaultInterpreter;
try {
foreach (var interpreter in service.Interpreters) {
options.DefaultInterpreter = interpreter;
using (var dialog = app.LaunchPythonProfiling()) {
Assert.AreEqual(interpreter.Configuration.Description, dialog.SelectedInterpreter);
}
app.WaitForDialogDismissed();
}
} finally {
options.DefaultInterpreter = originalDefault;
}
}
public void StartupProjectSelected(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var sln = app.CopyProjectForTest(@"TestData\MultiProjectAnalysis\MultiProjectAnalysis.sln");
app.OpenProject(sln);
foreach (var project in app.Dte.Solution.Projects.Cast<EnvDTE.Project>()) {
var tree = app.OpenSolutionExplorer();
var item = tree.FindByName(project.Name);
item.Select();
app.Dte.ExecuteCommand("Project.SetasStartupProject");
using (var dialog = app.LaunchPythonProfiling()) {
Assert.AreEqual(project.Name, dialog.SelectedProject);
}
app.WaitForDialogDismissed();
}
}
public void NewProfilingSession(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
PythonPaths.Python27.AssertInstalled();
var testFile = TestData.GetPath(@"TestData\ProfileTest\Program.py");
Assert.IsTrue(File.Exists(testFile), "ProfileTest\\Program.py does not exist");
app.OpenPythonPerformance();
app.PythonPerformanceExplorerToolBar.NewPerfSession();
var profiling = (IPythonProfiling)app.Dte.GetObject("PythonProfiling");
app.OpenPythonPerformance();
var perf = app.PythonPerformanceExplorerTreeView.WaitForItem("Performance *");
Assert.IsNotNull(perf);
var session = profiling.GetSession(1);
Assert.IsNotNull(session);
try {
Mouse.MoveTo(perf.GetClickablePoint());
Mouse.DoubleClick(System.Windows.Input.MouseButton.Left);
// wait for the dialog, set some settings, save them.
using (var perfTarget = new PythonPerfTarget(app.WaitForDialog())) {
perfTarget.SelectProfileScript();
perfTarget.InterpreterComboBox.SelectItem("Python 2.7 (32-bit)");
perfTarget.ScriptName = testFile;
perfTarget.WorkingDir = Path.GetDirectoryName(testFile);
try {
perfTarget.Ok();
} catch (ElementNotEnabledException) {
Assert.Fail("Settings were invalid:\n ScriptName = {0}\n Interpreter = {1}",
perfTarget.ScriptName, perfTarget.SelectedInterpreter);
}
}
app.WaitForDialogDismissed();
Mouse.MoveTo(perf.GetClickablePoint());
Mouse.DoubleClick(System.Windows.Input.MouseButton.Left);
// re-open the dialog, verify the settings
using (var perfTarget = new PythonPerfTarget(app.WaitForDialog())) {
Assert.AreEqual("Python 2.7 (32-bit)", perfTarget.SelectedInterpreter);
Assert.AreEqual(TestData.GetPath(@"TestData\ProfileTest\Program.py"), perfTarget.ScriptName);
}
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void DeleteMultipleSessions(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
app.Dte.Solution.Close(false);
app.OpenPythonPerformance();
app.PythonPerformanceExplorerToolBar.NewPerfSession();
app.PythonPerformanceExplorerToolBar.NewPerfSession();
var profiling = (IPythonProfiling)app.Dte.GetObject("PythonProfiling");
app.OpenPythonPerformance();
var perf = app.PythonPerformanceExplorerTreeView.WaitForItem("Performance *");
Assert.IsNotNull(perf);
var perf2 = app.PythonPerformanceExplorerTreeView.WaitForItem("Performance1 *");
AutomationWrapper.Select(perf);
// Cannot use AddToSelection because the tree view declares that
// it does not support multi-select, even though it does.
// AutomationWrapper.AddToSelection(perf2);
Mouse.MoveTo(perf2.GetClickablePoint());
try {
Keyboard.Press(System.Windows.Input.Key.LeftCtrl);
Mouse.Click(System.Windows.Input.MouseButton.Left);
} finally {
Keyboard.Release(System.Windows.Input.Key.LeftCtrl);
}
var dialog = AutomationElement.FromHandle(app.OpenDialogWithDteExecuteCommand("Edit.Delete")).AsWrapper();
dialog.ClickButtonByName("Delete");
Assert.IsNull(app.PythonPerformanceExplorerTreeView.WaitForItemRemoved("Performance *"));
Assert.IsNull(app.PythonPerformanceExplorerTreeView.WaitForItemRemoved("Performance1 *"));
}
public void NewProfilingSessionOpenSolution(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling);
app.OpenPythonPerformance();
app.PythonPerformanceExplorerToolBar.NewPerfSession();
var perf = app.PythonPerformanceExplorerTreeView.WaitForItem("Performance");
var session = profiling.GetSession(1);
Assert.IsNotNull(session);
try {
Mouse.MoveTo(perf.GetClickablePoint());
Mouse.DoubleClick(System.Windows.Input.MouseButton.Left);
// wait for the dialog, set some settings, save them.
using (var perfTarget = new PythonPerfTarget(app.WaitForDialog())) {
perfTarget.SelectProfileProject();
perfTarget.SelectedProjectComboBox.SelectItem("HelloWorld");
try {
perfTarget.Ok();
} catch (ElementNotEnabledException) {
Assert.Fail("Settings were invalid:\n SelectedProject = {0}",
perfTarget.SelectedProjectComboBox.GetSelectedItemName());
}
}
Mouse.MoveTo(perf.GetClickablePoint());
Mouse.DoubleClick(System.Windows.Input.MouseButton.Left);
// re-open the dialog, verify the settings
using (var perfTarget = new PythonPerfTarget(app.WaitForDialog())) {
Assert.AreEqual("HelloWorld", perfTarget.SelectedProject);
}
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void LaunchPythonProfilingWizard(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var project = app.OpenProject(@"TestData\ProfileTest.sln");
using (var perfTarget = app.LaunchPythonProfiling()) {
perfTarget.SelectProfileProject();
perfTarget.SelectedProjectComboBox.SelectItem("HelloWorld");
try {
perfTarget.Ok();
} catch (ElementNotEnabledException) {
Assert.Fail("Settings were invalid:\n SelectedProject = {0}",
perfTarget.SelectedProjectComboBox.GetSelectedItemName());
}
}
app.WaitForDialogDismissed();
var profiling = (IPythonProfiling)app.Dte.GetObject("PythonProfiling");
var session = profiling.GetSession(1);
try {
Assert.IsNotNull(app.PythonPerformanceExplorerTreeView.WaitForItem("HelloWorld *"));
while (profiling.IsProfiling) {
// wait for profiling to finish...
Thread.Sleep(100);
}
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void LaunchProjectPython27(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var version = PythonPaths.Python27_x64 ?? PythonPaths.Python27;
version.AssertInstalled();
LaunchProject(app, version);
}
public void LaunchProjectPython35(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var version = PythonPaths.Python35_x64 ?? PythonPaths.Python35;
version.AssertInstalled();
LaunchProject(app, version);
}
public void LaunchProjectPython36(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var version = PythonPaths.Python36_x64 ?? PythonPaths.Python36;
version.AssertInstalled();
LaunchProject(app, version);
}
public void LaunchProjectPython37(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var version = PythonPaths.Python37_x64 ?? PythonPaths.Python37;
version.AssertInstalled();
LaunchProject(app, version);
}
public void LaunchProjectPython38(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var version = PythonPaths.Python38_x64 ?? PythonPaths.Python38;
version.AssertInstalled();
LaunchProject(app, version);
}
public void LaunchProjectWithSpaceInFilename(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
LaunchProjectAndVerifyReport(
app,
@"TestData\Profile Test.sln",
"Profile Test",
new[] { "Program.f", "time.sleep" }
);
}
public void LaunchProjectWithSolutionFolder(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
LaunchProjectAndVerifyReport(
app,
@"TestData\ProfileTestSolutionFolder.sln",
"ProfileTestSolutionFolder",
new[] { "Program.f", "time.sleep" }
);
}
public void LaunchProjectWithSearchPath(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling, @"TestData\ProfileTestSysPath.sln");
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("HelloWorld"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
VerifyReport(report, true, "A.mod.func");
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void LaunchProjectWithPythonPathSet(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling, @"TestData\ProfileTestSysPath.sln");
var projDir = PathUtils.GetParent(project.FullName);
IPythonProfileSession session = null;
try {
using (new PythonServiceGeneralOptionsSetter(app.PythonToolsService, clearGlobalPythonPath: false))
using (new EnvironmentVariableSetter("PYTHONPATH", Path.Combine(projDir, "B"))) {
session = LaunchProject(app, profiling, project, projDir, false);
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("HelloWorld"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
VerifyReport(report, true, "B.mod2.func");
}
} finally {
if (session != null) {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
}
public void LaunchProjectWithPythonPathClear(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling, @"TestData\ProfileTestSysPath.sln");
var projDir = PathUtils.GetParent(project.FullName);
IPythonProfileSession session = null;
try {
using (new PythonServiceGeneralOptionsSetter(app.PythonToolsService, clearGlobalPythonPath: true))
using (new EnvironmentVariableSetter("PYTHONPATH", Path.Combine(projDir, "B"))) {
session = LaunchProject(app, profiling, project, projDir, false);
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("HelloWorld"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
VerifyReport(report, true, "A.mod.func");
}
} finally {
if (session != null) {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
}
public void LaunchProjectWithEnvironment(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
LaunchProjectAndVerifyReport(
app,
@"TestData\ProfileTestEnvironment.sln",
"HelloWorld",
new[] { "Program.user_env_var_valid" }
);
}
public void SaveDirtySession(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling);
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("HelloWorld"));
app.OpenPythonPerformance();
var pyPerf = app.PythonPerformanceExplorerTreeView;
Assert.IsNotNull(pyPerf);
var item = pyPerf.FindItem("HelloWorld *", "Reports");
var child = item.FindFirst(System.Windows.Automation.TreeScope.Descendants, Condition.TrueCondition);
var childName = child.GetCurrentPropertyValue(AutomationElement.NameProperty) as string;
Assert.IsTrue(childName.StartsWith("HelloWorld"));
// select the dirty session node and save it
var perfSessionItem = pyPerf.FindItem("HelloWorld *");
perfSessionItem.SetFocus();
app.SaveSelection();
// now it should no longer be dirty
perfSessionItem = pyPerf.WaitForItem("HelloWorld");
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void DeleteReport(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling);
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
try {
string reportFilename;
WaitForReport(profiling, session, app, out reportFilename);
new RemoveItemDialog(app.WaitForDialog()).Delete();
app.WaitForDialogDismissed();
Assert.IsTrue(!File.Exists(reportFilename));
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void CompareReports(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling);
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
try {
for (int i = 0; i < 100 && profiling.IsProfiling; i++) {
Thread.Sleep(100);
}
session.Launch(false);
for (int i = 0; i < 100 && profiling.IsProfiling; i++) {
Thread.Sleep(100);
}
var pyPerf = app.PythonPerformanceExplorerTreeView;
var baselineFile = session.GetReport(1).Filename;
var comparisonFile = session.GetReport(2).Filename;
var child = pyPerf.FindItem("HelloWorld *", "Reports", Path.GetFileNameWithoutExtension(baselineFile));
AutomationWrapper.EnsureExpanded(child);
child.SetFocus();
child.Select();
Mouse.MoveTo(child.GetClickablePoint());
Mouse.Click(System.Windows.Input.MouseButton.Right);
Keyboard.PressAndRelease(System.Windows.Input.Key.C);
using (var cmpReports = new ComparePerfReports(app.WaitForDialog())) {
try {
cmpReports.BaselineFile = baselineFile;
cmpReports.ComparisonFile = comparisonFile;
cmpReports.Ok();
app.WaitForDialogDismissed();
} catch (ElementNotEnabledException) {
Assert.Fail("Settings were invalid:\n BaselineFile = {0}\n ComparisonFile = {1}",
cmpReports.BaselineFile, cmpReports.ComparisonFile);
}
}
app.WaitForDialogDismissed();
// verify the difference file opens....
bool foundDiff = false;
for (int j = 0; j < 10 && !foundDiff; j++) {
for (int i = 0; i < app.Dte.Documents.Count; i++) {
var doc = app.Dte.Documents.Item(i + 1);
string name = doc.FullName;
if (name.StartsWith("vsp://diff/?baseline=")) {
foundDiff = true;
Thread.Sleep(5000);
Task.Run(() => doc.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo)).Wait();
break;
}
}
if (!foundDiff) {
Thread.Sleep(300);
}
}
Assert.IsTrue(foundDiff);
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void RemoveReport(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling);
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
try {
string reportFilename;
WaitForReport(profiling, session, app, out reportFilename);
new RemoveItemDialog(app.WaitForDialog()).Remove();
app.WaitForDialogDismissed();
Assert.IsTrue(File.Exists(reportFilename));
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void OpenReport(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling);
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
try {
IPythonPerformanceReport report;
AutomationElement child;
WaitForReport(profiling, session, out report, app, out child);
var clickPoint = child.GetClickablePoint();
Mouse.MoveTo(clickPoint);
Mouse.DoubleClick(System.Windows.Input.MouseButton.Left);
Assert.IsNotNull(app.WaitForDocument(report.Filename));
app.Dte.Documents.CloseAll(EnvDTE.vsSaveChanges.vsSaveChangesNo);
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
private static void WaitForReport(IPythonProfiling profiling, IPythonProfileSession session, out IPythonPerformanceReport report, PythonVisualStudioApp app, out AutomationElement child) {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("HelloWorld"));
app.OpenPythonPerformance();
var pyPerf = app.PythonPerformanceExplorerTreeView;
Assert.IsNotNull(pyPerf);
var item = pyPerf.WaitForItem("HelloWorld *", "Reports");
child = item.FindFirst(TreeScope.Descendants, Condition.TrueCondition);
var childName = (string)child.GetCurrentPropertyValue(AutomationElement.NameProperty);
Assert.IsTrue(childName.StartsWith("HelloWorld"));
AutomationWrapper.EnsureExpanded(child);
}
public void OpenReportCtxMenu(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling);
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
try {
IPythonPerformanceReport report;
AutomationElement child;
WaitForReport(profiling, session, out report, app, out child);
var clickPoint = child.GetClickablePoint();
Mouse.MoveTo(clickPoint);
Mouse.Click(System.Windows.Input.MouseButton.Right);
Keyboard.Press(System.Windows.Input.Key.O);
Assert.IsNotNull(app.WaitForDocument(report.Filename));
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void TargetPropertiesForProject(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling);
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
app.OpenPythonPerformance();
var pyPerf = app.PythonPerformanceExplorerTreeView;
var item = pyPerf.FindItem("HelloWorld *");
Mouse.MoveTo(item.GetClickablePoint());
Mouse.DoubleClick(System.Windows.Input.MouseButton.Left);
using (var perfTarget = new PythonPerfTarget(app.WaitForDialog())) {
Assert.AreEqual("HelloWorld", perfTarget.SelectedProject);
}
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void TargetPropertiesForInterpreter(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
PythonPaths.Python27.AssertInstalled();
IPythonProfiling profiling = GetProfiling(app);
var sln = app.CopyProjectForTest(@"TestData\ProfileTest.sln");
var projDir = Path.Combine(PathUtils.GetParent(sln), "ProfileTest");
var session = LaunchProcess(app,
profiling,
"Global|PythonCore|2.7-32",
Path.Combine(projDir, "Program.py"),
projDir,
"",
false
);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
app.OpenPythonPerformance();
var pyPerf = app.PythonPerformanceExplorerTreeView;
var item = pyPerf.FindItem("Program *");
Mouse.MoveTo(item.GetClickablePoint());
Mouse.DoubleClick(System.Windows.Input.MouseButton.Left);
using (var perfTarget = new PythonPerfTarget(app.WaitForDialog())) {
Assert.AreEqual("Python 2.7 (32-bit)", perfTarget.SelectedInterpreter);
Assert.AreEqual("", perfTarget.Arguments);
Assert.IsTrue(perfTarget.ScriptName.EndsWith("Program.py"));
Assert.IsTrue(perfTarget.ScriptName.StartsWith(perfTarget.WorkingDir));
}
app.WaitForDialogDismissed();
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void TargetPropertiesForExecutable(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var interp = PythonPaths.Python27;
interp.AssertInstalled();
IPythonProfiling profiling = GetProfiling(app);
var sln = app.CopyProjectForTest(@"TestData\ProfileTest.sln");
var projDir = Path.Combine(PathUtils.GetParent(sln), "ProfileTest");
var session = LaunchProcess(app,
profiling,
interp.InterpreterPath,
Path.Combine(projDir, "Program.py"),
projDir,
"",
false
);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
app.OpenPythonPerformance();
var pyPerf = app.PythonPerformanceExplorerTreeView;
var item = pyPerf.FindItem("Program *");
Mouse.MoveTo(item.GetClickablePoint());
Mouse.DoubleClick(System.Windows.Input.MouseButton.Left);
using (var perfTarget = new PythonPerfTarget(app.WaitForDialog())) {
Assert.AreEqual(interp.InterpreterPath, perfTarget.InterpreterPath);
Assert.AreEqual("", perfTarget.Arguments);
Assert.IsTrue(perfTarget.ScriptName.EndsWith("Program.py"));
Assert.IsTrue(perfTarget.ScriptName.StartsWith(perfTarget.WorkingDir));
}
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void StopProfiling(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var interp = PythonPaths.Python27;
interp.AssertInstalled();
IPythonProfiling profiling = GetProfiling(app);
var sln = app.CopyProjectForTest(@"TestData\ProfileTest.sln");
var projDir = Path.Combine(PathUtils.GetParent(sln), "ProfileTest");
var session = LaunchProcess(app,
profiling,
interp.InterpreterPath,
Path.Combine(projDir, "InfiniteProfile.py"),
projDir,
"",
false
);
try {
Thread.Sleep(1000);
Assert.IsTrue(profiling.IsProfiling);
app.OpenPythonPerformance();
app.PythonPerformanceExplorerToolBar.Stop();
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
Assert.IsNotNull(report);
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void MultipleTargets(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling);
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
IPythonProfileSession session2 = null;
try {
{
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("HelloWorld"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
VerifyReport(report, true, "Program.f", "time.sleep");
}
{
var interp = PythonPaths.Python27;
interp.AssertInstalled();
session2 = LaunchProcess(app, profiling, interp.InterpreterPath,
Path.Combine(projDir, "Program.py"),
projDir,
"",
false
);
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session2.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("Program"));
Assert.IsNull(session2.GetReport(2));
Assert.IsNotNull(session2.GetReport(report.Filename));
VerifyReport(report, true, "Program.f", "time.sleep");
}
} finally {
app.InvokeOnMainThread(() => {
profiling.RemoveSession(session, true);
if (session2 != null) {
profiling.RemoveSession(session2, true);
}
});
}
}
public void MultipleTargetsWithProjectHome(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var profiling = GetProfiling(app);
var sln = app.CopyProjectForTest(@"TestData\ProfileTest2.sln");
var slnDir = PathUtils.GetParent(sln);
var profileTestDir = Path.Combine(slnDir, "ProfileTest");
var profileTest2Dir = Path.Combine(slnDir, "ProfileTest2");
FileUtils.CopyDirectory(TestData.GetPath(@"TestData\ProfileTest"), profileTestDir);
var project = app.OpenProject(sln);
var session = LaunchProject(app, profiling, project, profileTest2Dir, false);
IPythonProfileSession session2 = null;
try {
{
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("HelloWorld"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
VerifyReport(report, true, "Program.f", "time.sleep");
}
{
var interp = PythonPaths.Python27;
interp.AssertInstalled();
session2 = LaunchProcess(app, profiling, interp.InterpreterPath,
Path.Combine(profileTestDir, "Program.py"),
profileTestDir,
"",
false
);
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session2.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("Program"));
Assert.IsNull(session2.GetReport(2));
Assert.IsNotNull(session2.GetReport(report.Filename));
VerifyReport(report, true, "Program.f", "time.sleep");
}
} finally {
app.InvokeOnMainThread(() => {
profiling.RemoveSession(session, true);
if (session2 != null) {
profiling.RemoveSession(session2, true);
}
});
}
}
public void MultipleReports(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling);
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("HelloWorld"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
VerifyReport(report, true, "Program.f", "time.sleep");
session.Launch();
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
report = session.GetReport(2);
VerifyReport(report, true, "Program.f", "time.sleep");
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void LaunchExecutable(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var interp = PythonPaths.Python27;
interp.AssertInstalled();
IPythonProfiling profiling = GetProfiling(app);
var sln = app.CopyProjectForTest(@"TestData\ProfileTest.sln");
var projDir = Path.Combine(PathUtils.GetParent(sln), "ProfileTest");
var session = LaunchProcess(app, profiling, interp.InterpreterPath,
Path.Combine(projDir, "Program.py"),
projDir,
"",
false
);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("Program"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
VerifyReport(report, true, "Program.f", "time.sleep");
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void ClassProfile(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var interp = PythonPaths.Python27;
interp.AssertInstalled();
IPythonProfiling profiling = GetProfiling(app);
var sln = app.CopyProjectForTest(@"TestData\ProfileTest.sln");
var projDir = Path.Combine(PathUtils.GetParent(sln), "ProfileTest");
var session = LaunchProcess(app, profiling, interp.InterpreterPath,
Path.Combine(projDir, "ClassProfile.py"),
projDir,
"",
false
);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("ClassProfile"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
Assert.IsTrue(File.Exists(filename));
VerifyReport(report, true, "ClassProfile.C.f", "time.sleep");
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, false));
}
}
public void OldClassProfile(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var version = PythonPaths.Python27 ?? PythonPaths.Python27_x64;
version.AssertInstalled("Unable to run test because Python 2.7 is not installed");
IPythonProfiling profiling = GetProfiling(app);
var sln = app.CopyProjectForTest(@"TestData\ProfileTest.sln");
var projDir = Path.Combine(PathUtils.GetParent(sln), "ProfileTest");
var session = LaunchProcess(app, profiling, version.InterpreterPath,
Path.Combine(projDir, "OldStyleClassProfile.py"),
projDir,
"",
false
);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
Assert.IsNotNull(report);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("OldStyleClassProfile"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
Assert.IsTrue(File.Exists(filename));
VerifyReport(report, true, "OldStyleClassProfile.C.f", "time.sleep");
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, false));
}
}
public void DerivedProfile(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var interp = PythonPaths.Python27;
interp.AssertInstalled();
IPythonProfiling profiling = GetProfiling(app);
var sln = app.CopyProjectForTest(@"TestData\ProfileTest.sln");
var projDir = Path.Combine(PathUtils.GetParent(sln), "ProfileTest");
var session = LaunchProcess(app, profiling, interp.InterpreterPath,
Path.Combine(projDir, "DerivedProfile.py"),
projDir,
"",
false
);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("DerivedProfile"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
VerifyReport(report, true, "DerivedProfile.C.f", "time.sleep");
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
public void Pystone(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
var interp = PythonPaths.Python27;
interp.AssertInstalled();
IPythonProfiling profiling = GetProfiling(app);
var session = LaunchProcess(app, profiling, interp.InterpreterPath,
Path.Combine(interp.PrefixPath, "Lib", "test", "pystone.py"),
Path.Combine(interp.PrefixPath, "Lib", "test"),
"",
false
);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("pystone"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
Assert.IsTrue(File.Exists(filename));
VerifyReport(report, true, "test.pystone.Proc1");
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, false));
}
}
public void BuiltinsProfilePython27(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
BuiltinsProfile(
app,
PythonPaths.Python27,
new[] { "str.startswith", "isinstance", "marshal.dumps", "array.array.tostring" },
null
);
}
public void BuiltinsProfilePython27x64(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
BuiltinsProfile(
app,
PythonPaths.Python27_x64,
new[] { "str.startswith", "isinstance", "marshal.dumps", "array.array.tostring" },
null
);
}
public void BuiltinsProfilePython35(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
BuiltinsProfile(
app,
PythonPaths.Python35,
new[] { "BuiltinsProfile.f", "str.startswith", "isinstance", "marshal.dumps", "array.array.tostring" },
new[] { "compile", "exec", "execfile", "_io.TextIOWrapper.read" }
);
}
public void BuiltinsProfilePython35x64(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
BuiltinsProfile(
app,
PythonPaths.Python35_x64,
new[] { "BuiltinsProfile.f", "str.startswith", "isinstance", "marshal.dumps", "array.array.tostring" },
new[] { "compile", "exec", "execfile", "_io.TextIOWrapper.read" }
);
}
public void BuiltinsProfilePython36(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
BuiltinsProfile(
app,
PythonPaths.Python36,
new[] { "BuiltinsProfile.f", "str.startswith", "isinstance", "marshal.dumps", "array.array.tostring" },
new[] { "compile", "exec", "execfile", "_io.TextIOWrapper.read" }
);
}
public void BuiltinsProfilePython36x64(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
BuiltinsProfile(
app,
PythonPaths.Python36_x64,
new[] { "BuiltinsProfile.f", "str.startswith", "isinstance", "marshal.dumps", "array.array.tostring" },
new[] { "compile", "exec", "execfile", "_io.TextIOWrapper.read" }
);
}
public void BuiltinsProfilePython37(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
BuiltinsProfile(
app,
PythonPaths.Python37,
new[] { "BuiltinsProfile.f", "str.startswith", "isinstance", "marshal.dumps", "array.array.tostring" },
new[] { "compile", "exec", "execfile", "_io.TextIOWrapper.read" }
);
}
public void BuiltinsProfilePython37x64(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
BuiltinsProfile(
app,
PythonPaths.Python37_x64,
new[] { "BuiltinsProfile.f", "str.startswith", "isinstance", "marshal.dumps", "array.array.tostring" },
new[] { "compile", "exec", "execfile", "_io.TextIOWrapper.read" }
);
}
public void BuiltinsProfilePython38(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
BuiltinsProfile(
app,
PythonPaths.Python38,
new[] { "BuiltinsProfile.f", "str.startswith", "isinstance", "marshal.dumps", "array.array.tostring" },
new[] { "compile", "exec", "execfile", "_io.TextIOWrapper.read" }
);
}
public void BuiltinsProfilePython38x64(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
BuiltinsProfile(
app,
PythonPaths.Python38_x64,
new[] { "BuiltinsProfile.f", "str.startswith", "isinstance", "marshal.dumps", "array.array.tostring" },
new[] { "compile", "exec", "execfile", "_io.TextIOWrapper.read" }
);
}
public void LaunchExecutableUsingInterpreterGuid(PythonVisualStudioApp app, ProfileCleanup cleanup, DotNotWaitOnExit optionSetter) {
PythonPaths.Python27.AssertInstalled();
IPythonProfiling profiling = GetProfiling(app);
var sln = app.CopyProjectForTest(@"TestData\ProfileTest.sln");
var projDir = Path.Combine(PathUtils.GetParent(sln), "ProfileTest");
var session = LaunchProcess(app, profiling,
PythonPaths.Python27.Id,
Path.Combine(projDir, "Program.py"),
projDir,
"",
false
);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
Assert.IsNotNull(report);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("Program"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
VerifyReport(report, true, "Program.f", "time.sleep");
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
#endregion
#region Helpers
public class DotNotWaitOnExit : PythonOptionsSetter {
public DotNotWaitOnExit(EnvDTE.DTE dte) :
base(dte, waitOnNormalExit: false, waitOnAbnormalExit: false) {
}
}
public class ProfileCleanup : IDisposable {
public ProfileCleanup() {
}
public void Dispose() {
try {
foreach (var file in Directory.EnumerateFiles(Path.GetTempPath(), "*.vsp", SearchOption.TopDirectoryOnly)) {
try {
File.Delete(file);
} catch {
// Weak attempt only
}
}
} catch {
}
}
}
private string SaveDirectory {
get {
var p = TestData.GetTempPath();
Console.WriteLine($"Saving to {p}");
return p;
}
}
private IPythonProfileSession LaunchSession(
PythonVisualStudioApp app,
Func<IPythonProfileSession> creator
) {
// Ensure the performance window has been opened, which will make
// the app clean up all sessions when it is disposed.
app.OpenPythonPerformance();
IPythonProfileSession session = null;
ExceptionDispatchInfo edi = null;
var task = Task.Factory.StartNew(() => {
try {
session = creator();
} catch (Exception ex) {
edi = ExceptionDispatchInfo.Capture(ex);
}
// Must fault the task to abort the wait
throw new Exception();
});
var dialog = app.WaitForDialog(task);
if (dialog != IntPtr.Zero) {
using (var saveDialog = new SaveDialog(app, AutomationElement.FromHandle(dialog))) {
var originalDestName = Path.Combine(SaveDirectory, Path.GetFileName(saveDialog.FileName));
var destName = originalDestName;
while (File.Exists(destName)) {
destName = string.Format("{0} {1}{2}",
Path.GetFileNameWithoutExtension(originalDestName),
Guid.NewGuid(),
Path.GetExtension(originalDestName)
);
}
saveDialog.FileName = destName;
saveDialog.Save();
try {
task.Wait(TimeSpan.FromSeconds(5.0));
Assert.Fail("Task did not fault");
} catch (AggregateException) {
}
}
} else {
// Ensure the exception is observed
var ex = task.Exception;
}
edi?.Throw();
Assert.IsNotNull(session, "Session was not correctly initialized");
return session;
}
private IPythonProfileSession LaunchProcess(
PythonVisualStudioApp app,
IPythonProfiling profiling,
string interpreterPath,
string filename,
string directory,
string arguments,
bool openReport
) {
return LaunchSession(app,
() => profiling.LaunchProcess(
interpreterPath,
filename,
directory,
"",
openReport
)
);
}
private IPythonProfileSession LaunchProject(
PythonVisualStudioApp app,
IPythonProfiling profiling,
EnvDTE.Project project,
string directory,
bool openReport
) {
return LaunchSession(app, () => profiling.LaunchProject(project, openReport));
}
private void CopyAndOpenProject(
PythonVisualStudioApp app,
out EnvDTE.Project project,
out IPythonProfiling profiling,
string projectFile = @"TestData\ProfileTest.sln"
) {
profiling = GetProfiling(app);
Assert.IsNotNull(projectFile);
var sln = app.CopyProjectForTest(projectFile);
project = app.OpenProject(sln);
}
private IPythonProfiling GetProfiling(PythonVisualStudioApp app) {
var profiling = (IPythonProfiling)app.Dte.GetObject("PythonProfiling");
// no sessions yet
Assert.IsNull(profiling.GetSession(1));
return profiling;
}
private void LaunchProjectAndVerifyReport(PythonVisualStudioApp app, string solutionPath, string expectedFileNameContains, string[] expectedFunctions) {
EnvDTE.Project project;
IPythonProfiling profiling;
CopyAndOpenProject(app, out project, out profiling, solutionPath);
var projDir = PathUtils.GetParent(project.FullName);
var session = LaunchProject(app, profiling, project, projDir, false);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains(expectedFileNameContains));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
VerifyReport(report, true, expectedFunctions);
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, true));
}
}
private static void WaitForReport(IPythonProfiling profiling, IPythonProfileSession session, PythonVisualStudioApp app, out string reportFilename) {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("HelloWorld"));
app.OpenPythonPerformance();
var pyPerf = app.PythonPerformanceExplorerTreeView;
Assert.IsNotNull(pyPerf);
var item = pyPerf.FindItem("HelloWorld *", "Reports");
var child = item.FindFirst(System.Windows.Automation.TreeScope.Descendants, Condition.TrueCondition);
var childName = child.GetCurrentPropertyValue(AutomationElement.NameProperty) as string;
reportFilename = report.Filename;
Assert.IsTrue(childName.StartsWith("HelloWorld"));
child.SetFocus();
Keyboard.PressAndRelease(System.Windows.Input.Key.Delete);
}
private void VerifyReport(IPythonPerformanceReport report, bool includesFunctions, params string[] expectedFunctions) {
var expected = expectedFunctions.ToSet(StringComparer.Ordinal);
var actual = OpenPerformanceReportAsCsv(report)
.Select(line => Regex.Match(line, @"^""(?<name>.+?)["" ]", RegexOptions.IgnoreCase))
.Where(m => m.Success)
.Select(m => m.Groups["name"].Value)
.ToSet(StringComparer.Ordinal);
if (includesFunctions) {
Console.WriteLine(
"expected: {0}\r\nactual: {1}\r\nextra: {2}\r\n\r\nmissing: {3}",
string.Join(", ", expected.OrderBy(k => k)),
string.Join(", ", actual.OrderBy(k => k)),
string.Join(", ", actual.Except(expected).OrderBy(k => k)),
string.Join(", ", expected.Except(actual).OrderBy(k => k))
);
Assert.IsTrue(actual.IsSupersetOf(expected), "Some functions were missing. See test output for details.");
} else {
var intersect = new HashSet<string>(expected);
intersect.IntersectWith(actual);
Console.WriteLine(
"expected: {0}\r\nactual: {1}\r\n\r\nintersect: {2}",
string.Join(", ", expected.OrderBy(k => k)),
string.Join(", ", actual.OrderBy(k => k)),
string.Join(", ", intersect.OrderBy(k => k))
);
Assert.IsTrue(intersect.Count == 0, "Some functions appeared. See test output for details.");
}
}
private string[] OpenPerformanceReportAsCsv(IPythonPerformanceReport report) {
var perfReportPath = Path.Combine(GetPerfToolsPath(false), "vsperfreport.exe");
Console.WriteLine("Opening {0} as CSV", report.Filename);
for (int i = 0; i < 100; i++) {
var csvFilename = Path.Combine(SaveDirectory, Path.GetFileNameWithoutExtension(report.Filename));
var originalName = csvFilename;
for (int counter = 1; File.Exists(csvFilename + "_FunctionSummary.csv"); ++counter) {
csvFilename = originalName + counter;
}
Console.WriteLine("Writing to {0}", csvFilename);
using (var process = ProcessOutput.RunHiddenAndCapture(
perfReportPath,
report.Filename,
"/output:" + csvFilename,
"/summary:function"
)) {
process.Wait();
if (process.ExitCode != 0) {
if (i == 99) {
Assert.Fail(string.Join(Environment.NewLine,
Enumerable.Repeat("Output: ", 1)
.Concat(process.StandardOutputLines)
.Concat(Enumerable.Repeat("Error:", 1))
.Concat(process.StandardErrorLines)
));
} else {
Thread.Sleep(100);
continue;
}
}
}
string[] res = null;
for (int j = 0; j < 100; j++) {
try {
res = File.ReadAllLines(csvFilename + "_FunctionSummary.csv");
break;
} catch {
Thread.Sleep(100);
}
}
return res ?? new string[0];
}
Assert.Fail("Unable to convert to CSV");
return null;
}
private static string GetPerfToolsPath(bool x64) {
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\VisualStudio\" + AssemblyVersionInfo.VSVersion);
var shFolder = key.GetValue("ShellFolder") as string;
if (shFolder == null) {
throw new InvalidOperationException("Cannot find shell folder for Visual Studio");
}
string perfToolsPath;
if (x64) {
perfToolsPath = @"Team Tools\Performance Tools\x64";
} else {
perfToolsPath = @"Team Tools\Performance Tools\";
}
perfToolsPath = Path.Combine(shFolder, perfToolsPath);
return perfToolsPath;
}
private void BuiltinsProfile(PythonVisualStudioApp app, PythonVersion interp, string[] expectedFunctions, string[] expectedNonFunctions) {
interp.AssertInstalled();
IPythonProfiling profiling = GetProfiling(app);
var sln = app.CopyProjectForTest(@"TestData\ProfileTest.sln");
var projDir = Path.Combine(PathUtils.GetParent(sln), "ProfileTest");
var session = LaunchProcess(app, profiling, interp.Id,
Path.Combine(projDir, "BuiltinsProfile.py"),
projDir,
"",
false
);
try {
while (profiling.IsProfiling) {
Thread.Sleep(100);
}
var report = session.GetReport(1);
var filename = report.Filename;
Assert.IsTrue(filename.Contains("BuiltinsProfile"));
Assert.IsNull(session.GetReport(2));
Assert.IsNotNull(session.GetReport(report.Filename));
Assert.IsTrue(File.Exists(filename));
if (expectedFunctions != null && expectedFunctions.Length > 0) {
VerifyReport(report, true, expectedFunctions);
}
if (expectedNonFunctions != null && expectedNonFunctions.Length > 0) {
VerifyReport(report, false, expectedNonFunctions);
}
} finally {
app.InvokeOnMainThread(() => profiling.RemoveSession(session, false));
}
}
private void LaunchProject(PythonVisualStudioApp app, PythonVersion version) {
using (app.SelectDefaultInterpreter(version)) {
LaunchProjectAndVerifyReport(
app,
@"TestData\ProfileTest.sln",
"HelloWorld",
new[] { "Program.f", "time.sleep" }
);
}
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
[Serializable]
public class UFTAtlas : ScriptableObject {
[SerializeField]
private UFTAtlasSize _atlasWidth;
public UFTAtlasSize atlasWidth {
get {
return this._atlasWidth;
}
set {
_atlasWidth = value;
sendEventAtlasWidthHeightChanged();
}
}
[SerializeField]
private UFTAtlasSize _atlasHeight;
public UFTAtlasSize atlasHeight {
get {
return this._atlasHeight;
}
set {
_atlasHeight = value;
sendEventAtlasWidthHeightChanged();
}
}
[SerializeField]
public List<UFTAtlasEntry> atlasEntries;
[SerializeField]
public int borderSize=2;
[SerializeField]
private string _atlasName;
public string atlasName {
get {
return this._atlasName;
}
set {
_atlasName = value;
sendEventAtlasChanged();
}
}
Texture2D atlasCanvasBG;
public static Texture2D borderTexture;
private static int atlasTileCubeFactor=16; // it equals of the cube size on bg
private Rect atlasBGTexCoord=new Rect(0,0,1,1);
private UFTAtlasEntry clickedTextureOnCanvas;
private bool recreateTexturesPositions=false;
void OnEnable() {
hideFlags = HideFlags.HideAndDontSave;
initParams ();
}
public void sendEventAtlasWidthHeightChanged ()
{
if (UFTAtlasEditorEventManager.onAtlasSizeChanged!=null)
UFTAtlasEditorEventManager.onAtlasSizeChanged((int)atlasWidth,(int)atlasHeight);
}
public void OnGUI(){
int width=(int)atlasWidth;
int height=(int)atlasHeight;
//check if in previous frame we clicked on texture, if we did, move this texture to the last index in collection
if (recreateTexturesPositions){
atlasEntries.Remove(clickedTextureOnCanvas);
atlasEntries.Add(clickedTextureOnCanvas);
recreateTexturesPositions=false;
}
// check fi user pressed button delete, in this case we will remove last element in the list
if ((Event.current.type==EventType.keyDown) && (Event.current.keyCode == KeyCode.Delete) && (atlasEntries!=null) && (atlasEntries.Count >0)){
removeLatestEntryFromList ();
}
Rect canvasRect = new Rect (0, 0, width, height);
GUI.DrawTextureWithTexCoords(canvasRect,UFTTextureUtil.atlasCanvasBGTile,atlasBGTexCoord,false);
if(atlasEntries!=null){
foreach(UFTAtlasEntry toc in atlasEntries){
toc.OnGUI();
}
// draw ellow border if mouse under the canvasw
if (canvasRect.Contains (Event.current.mousePosition)){
Color color=GUI.color;
GUI.color=UFTTextureUtil.borderColorDict[UFTTextureState.showBorder];
foreach(UFTAtlasEntry toc in atlasEntries){
GUI.Box(toc.canvasRect,GUIContent.none,UFTTextureUtil.borderStyle);
}
GUI.color=color;
}
}
}
public void readPropertiesFromMetadata(UFTAtlasMetadata atlasMetadata){
atlasWidth=(UFTAtlasSize) atlasMetadata.texture.width;
atlasHeight=(UFTAtlasSize) atlasMetadata.texture.height;
List<UFTAtlasEntry> entries=new List<UFTAtlasEntry>();
foreach (UFTAtlasEntryMetadata meta in atlasMetadata.entries){
UFTAtlasEntry entry=UFTAtlasEntry.CreateInstance<UFTAtlasEntry>();
try{
entry.readPropertiesFromMetadata(meta);
entry.uftAtlas=this;
entries.Add(entry);
}catch (TextureDoesNotExistsException e){
Debug.LogWarning("texture "+e.texturePath+" does not exists exception");
}
}
this.atlasEntries=entries;
this.atlasName=atlasMetadata.atlasName;
}
public void addNewEntry(Texture2D texture, string assetPath){
string name=assetPath.Substring(assetPath.LastIndexOf('/')+1);
Rect rect=new Rect(0,0,texture.width,texture.height);
UFTAtlasEntry uftAtlasEntry=UFTAtlasEntry.CreateInstance<UFTAtlasEntry>();
uftAtlasEntry.assetPath=assetPath;
uftAtlasEntry.textureName=name;
uftAtlasEntry.canvasRect=rect;
uftAtlasEntry.texture=texture;
uftAtlasEntry.uftAtlas=this;
atlasEntries.Add( uftAtlasEntry);
if (UFTAtlasEditorEventManager.onAddNewEntry!=null)
UFTAtlasEditorEventManager.onAddNewEntry(uftAtlasEntry);
sendEventAtlasChanged();
}
void initParams ()
{
borderTexture=UFTTextureUtil.createOnePxBorderTexture();
if(atlasEntries==null)
atlasEntries=new List<UFTAtlasEntry>();
//init listeners
UFTAtlasEditorEventManager.onDragInProgress+=onDragInProgressListener;
UFTAtlasEditorEventManager.onStopDragging+=onStopDraggingListener;
UFTAtlasEditorEventManager.onStartDragging+=onStartDraggingListener;
UFTAtlasEditorEventManager.onAtlasSizeChanged+=onAtlasSizeChanged;
onAtlasSizeChanged((int)atlasWidth,(int)atlasHeight);
}
public void removeAllEntries(){
while(atlasEntries.Count>0)
removeLatestEntryFromList();
}
public void trimAllEntries(){
bool somethingChanged=false;
foreach(UFTAtlasEntry atlasEntry in atlasEntries){
if (atlasEntry.trimTexture())
somethingChanged=true;
}
if (somethingChanged)
sendEventAtlasChanged();
}
private void onDragInProgressListener(){
Repaint();
}
private void onStopDraggingListener(UFTAtlasEntry uftAtlasEntry){
Repaint();
}
void removeLatestEntryFromList ()
{
UFTAtlasEntry latestEntry= atlasEntries[atlasEntries.Count-1];
if (UFTAtlasEditorEventManager.onRemoveEntry!=null)
UFTAtlasEditorEventManager.onRemoveEntry(latestEntry);
atlasEntries.Remove(latestEntry);
sendEventAtlasChanged();
}
private void Repaint(){
if (UFTAtlasEditorEventManager.onNeedToRepaint!=null)
UFTAtlasEditorEventManager.onNeedToRepaint();
}
private void sendEventAtlasChanged(){
if (UFTAtlasEditorEventManager.onAtlasChange!=null)
UFTAtlasEditorEventManager.onAtlasChange();
}
// we cant move this element to the last position in the list, because in paralel iterator can use list
// because of that we will just store this value, and in nex frame in OnGUI function
// we will move this object to the last position
private void onStartDraggingListener (UFTAtlasEntry textureOnCanvas)
{
clickedTextureOnCanvas=textureOnCanvas;
recreateTexturesPositions=true;
}
// in case if atlas size is changed, we need to send event with new size
void onAtlasSizeChanged (int atlasWidth, int atlasHeight)
{
atlasBGTexCoord=new Rect(0,0,atlasWidth/atlasTileCubeFactor,atlasHeight/atlasTileCubeFactor);
}
//this function build atlas texture, create atlas metadata and return it
public UFTAtlasMetadata saveAtlasTextureAndGetMetadata(string assetPath){
List<UFTAtlasEntryMetadata> entryMeta=atlasEntries.ConvertAll(new Converter<UFTAtlasEntry,UFTAtlasEntryMetadata>(entryToEntryMetaConverter));
Texture2D texture=buildAtlasTexture2d();
texture=UFTTextureUtil.saveTexture2DToAssets(texture, assetPath);
UFTAtlasMetadata atlasMetadata=UFTAtlasMetadata.CreateInstance<UFTAtlasMetadata>();
atlasMetadata.entries=entryMeta.ToArray();
atlasMetadata.texture=texture;
atlasMetadata.atlasName=atlasName;
return atlasMetadata;
}
private static UFTAtlasEntryMetadata entryToEntryMetaConverter(UFTAtlasEntry entry){
return entry.getMetadata();
}
public void arrangeEntriesUsingUnityPackager(){
int width=(int)atlasWidth;
int height=(int)atlasHeight;
Texture2D tmpTexture=new Texture2D(width,height);
Texture2D[] entries= atlasEntries.ConvertAll<Texture2D>(entry=>entry.texture).ToArray();
Rect[] rects=tmpTexture.PackTextures(entries,borderSize);
for (int i = 0; i < rects.Length; i++) {
//convert rect from Atlas(which has 0->1 values, 0.5 means center to pixel values)
Rect newRect=new Rect(rects[i].x*width,rects[i].y*height,atlasEntries[i].canvasRect.width,atlasEntries[i].canvasRect.height);
atlasEntries[i].canvasRect=newRect;
}
DestroyImmediate(tmpTexture,true);
}
// save all entries textures to one Texture2d, this function doesn't store result texture to asset or to the file
public Texture2D buildAtlasTexture2d(){
Texture2D atlasTexture=UFTTextureUtil.getBlankTexture((int)atlasWidth,(int)atlasHeight);
Color32[] atlasColors=atlasTexture.GetPixels32();
foreach (UFTAtlasEntry entry in atlasEntries){
Texture2D entryTexture=entry.texture;
Color32[] entryColors=entryTexture.GetPixels32();
int rowPosition=0;
int offset=(int)(atlasColors.Length-((entry.canvasRect.y+entry.canvasRect.height) * (int)atlasWidth)+entry.canvasRect.x);
for (int i = 0; i < entryColors.Length; i++) {
if (rowPosition==entry.canvasRect.width){
rowPosition=0;
offset=offset+ (int)atlasWidth;
}
atlasColors[offset+rowPosition]=entryColors[i];
rowPosition++;
}
}
atlasTexture.SetPixels32(atlasColors);
atlasTexture.Apply();
return atlasTexture;
}
}
| |
using System;
using System.Linq;
using System.Text.RegularExpressions;
using BugReport.DataModel;
using BugReport.Util;
namespace BugReport.Query
{
public class ExpressionLabel : Expression
{
readonly string _labelName;
public ExpressionLabel(string labelName)
{
_labelName = labelName;
}
public override bool Evaluate(DataModelIssue issue)
{
return issue.HasLabel(_labelName);
}
public override void Validate(IssueCollection collection)
{
if (!collection.HasLabel(_labelName))
{
Console.WriteLine($"WARNING: Label does not exist: {_labelName}");
}
}
public override string ToString()
{
return GetGitHubQueryURL();
}
public override string GetGitHubQueryURL()
{
if (_labelName.Contains(' '))
{
return $"label:\"{_labelName}\"";
}
return "label:" + _labelName;
}
internal override bool IsNormalized(NormalizedState minAllowedState)
{
return true;
}
protected override Expression GetSimplified()
{
return this;
}
public override bool Equals(Expression e)
{
return (e is ExpressionLabel) ?
StringComparer.InvariantCultureIgnoreCase.Equals(_labelName, ((ExpressionLabel)e)._labelName) :
false;
}
}
public class ExpressionLabelPattern : Expression
{
readonly string _labelPattern;
readonly Regex _labelRegex;
public ExpressionLabelPattern(string labelPattern)
{
_labelPattern = labelPattern;
_labelRegex = new Regex("^" + labelPattern + "$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
}
public override bool Evaluate(DataModelIssue issue)
{
return issue.Labels.Where(label => _labelRegex.IsMatch(label.Name)).Any();
}
public override void Validate(IssueCollection collection)
{
if (collection.Labels.Where(label => _labelRegex.IsMatch(label.Name)).None())
{
Console.WriteLine($"WARNING: Label pattern does not match any label: {_labelRegex.ToString()}");
}
}
public override string ToString()
{
if (_labelPattern.Contains(' '))
{
return $"label:\"{_labelPattern}\"";
}
return "label:" + _labelPattern;
}
public override string GetGitHubQueryURL()
{
return null;
}
internal override bool IsNormalized(NormalizedState minAllowedState)
{
return true;
}
protected override Expression GetSimplified()
{
return this;
}
public override bool Equals(Expression e)
{
return (e is ExpressionLabelPattern) ?
_labelPattern == ((ExpressionLabelPattern)e)._labelPattern :
false;
}
}
public class ExpressionIsIssue : Expression
{
readonly bool _isIssue;
public ExpressionIsIssue(bool isIssue)
{
_isIssue = isIssue;
}
public override bool Evaluate(DataModelIssue issue)
{
return issue.IsIssueOrComment == _isIssue;
}
public override void Validate(IssueCollection collection)
{
}
public override string ToString()
{
return GetGitHubQueryURL();
}
public override string GetGitHubQueryURL()
{
return _isIssue ? "is:issue" : "is:pr";
}
internal override bool IsNormalized(NormalizedState minAllowedState)
{
return true;
}
protected override Expression GetSimplified()
{
return this;
}
public override bool Equals(Expression e)
{
return (e is ExpressionIsIssue) ?
_isIssue == ((ExpressionIsIssue)e)._isIssue :
false;
}
}
public class ExpressionIsOpen : Expression
{
readonly bool _isOpen;
public ExpressionIsOpen(bool isOpen)
{
_isOpen = isOpen;
}
public override bool Evaluate(DataModelIssue issue)
{
return issue.IsOpen == _isOpen;
}
public override void Validate(IssueCollection collection)
{
}
public override string ToString()
{
return GetGitHubQueryURL();
}
public override string GetGitHubQueryURL()
{
return _isOpen ? "is:open" : "is:closed";
}
internal override bool IsNormalized(NormalizedState minAllowedState)
{
return true;
}
protected override Expression GetSimplified()
{
return this;
}
public override bool Equals(Expression e)
{
return (e is ExpressionIsOpen) ?
_isOpen == ((ExpressionIsOpen)e)._isOpen :
false;
}
}
public class ExpressionMilestone : Expression
{
readonly string _milestoneName;
public ExpressionMilestone(string milestoneName)
{
_milestoneName = milestoneName;
}
public override bool Evaluate(DataModelIssue issue)
{
return issue.IsMilestone(_milestoneName);
}
public override void Validate(IssueCollection collection)
{
if (!collection.HasMilestone(_milestoneName))
{
Console.WriteLine($"WARNING: Milestone does not exist: {_milestoneName}");
}
}
public override string ToString()
{
return GetGitHubQueryURL();
}
public override string GetGitHubQueryURL()
{
if (_milestoneName == null)
{
return "no:milestone";
}
if (_milestoneName.Contains(' '))
{
return $"milestone:\"{_milestoneName}\"";
}
return "milestone:" + _milestoneName;
}
internal override bool IsNormalized(NormalizedState minAllowedState)
{
return true;
}
protected override Expression GetSimplified()
{
return this;
}
public override bool Equals(Expression e)
{
return (e is ExpressionMilestone) ?
StringComparer.InvariantCultureIgnoreCase.Equals(_milestoneName, ((ExpressionMilestone)e)._milestoneName) :
false;
}
}
public class ExpressionMilestonePattern : Expression
{
readonly string _milestonePattern;
readonly Regex _milestoneRegex;
public ExpressionMilestonePattern(string milestonePattern)
{
_milestonePattern = milestonePattern;
_milestoneRegex = new Regex("^" + milestonePattern + "$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
}
public override bool Evaluate(DataModelIssue issue)
{
return ((issue.Milestone != null) &&
_milestoneRegex.IsMatch(issue.Milestone.Title));
}
public override void Validate(IssueCollection collection)
{
// TODO: We could enumerate all Milestones on collection - very low pri
}
public override string ToString()
{
if (_milestonePattern.Contains(' '))
{
return $"milestone:\"{_milestonePattern}\"";
}
return "milestone:" + _milestonePattern;
}
public override string GetGitHubQueryURL()
{
return null;
}
internal override bool IsNormalized(NormalizedState minAllowedState)
{
return true;
}
protected override Expression GetSimplified()
{
return this;
}
public override bool Equals(Expression e)
{
return (e is ExpressionMilestonePattern) ?
_milestonePattern == ((ExpressionMilestonePattern)e)._milestonePattern :
false;
}
}
public class ExpressionAssignee : Expression
{
readonly string _assigneeName;
public ExpressionAssignee(string assigneeName)
{
_assigneeName = assigneeName;
}
public override bool Evaluate(DataModelIssue issue)
{
return issue.HasAssignee(_assigneeName);
}
public override void Validate(IssueCollection collection)
{
if (!collection.HasUser(_assigneeName))
{
Console.WriteLine($"WARNING: Assignee does not exist: {_assigneeName}");
}
}
public override string ToString()
{
return GetGitHubQueryURL();
}
public override string GetGitHubQueryURL()
{
return "assignee:" + _assigneeName;
}
internal override bool IsNormalized(NormalizedState minAllowedState)
{
return true;
}
protected override Expression GetSimplified()
{
return this;
}
public override bool Equals(Expression e)
{
return (e is ExpressionAssignee) ?
StringComparer.InvariantCultureIgnoreCase.Equals(_assigneeName, ((ExpressionAssignee)e)._assigneeName) :
false;
}
}
public class ExpressionConstant : Expression
{
readonly bool _value;
public static readonly ExpressionConstant True = new ExpressionConstant(true);
public static readonly ExpressionConstant False = new ExpressionConstant(false);
private ExpressionConstant(bool value)
{
_value = value;
}
public override bool Evaluate(DataModelIssue issue)
{
return _value;
}
public override void Validate(IssueCollection collection)
{
}
public override string ToString()
{
return _value.ToString();
}
public override string GetGitHubQueryURL()
{
return null;
}
internal override bool IsNormalized(NormalizedState minAllowedState)
{
return true;
}
protected override Expression GetSimplified()
{
return this;
}
public override bool Equals(Expression e)
{
// Only 2 static instances exist (True & False), so it is sufficient to compare object references
return (this == e);
}
}
}
| |
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.14.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Safe Browsing APIs Version v4
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/safe-browsing/'>Safe Browsing APIs</a>
* <tr><th>API Version<td>v4
* <tr><th>API Rev<td>20160520 (505)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/safe-browsing/'>
* https://developers.google.com/safe-browsing/</a>
* <tr><th>Discovery Name<td>safebrowsing
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Safe Browsing APIs can be found at
* <a href='https://developers.google.com/safe-browsing/'>https://developers.google.com/safe-browsing/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Safebrowsing.v4
{
/// <summary>The Safebrowsing Service.</summary>
public class SafebrowsingService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v4";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public SafebrowsingService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public SafebrowsingService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
fullHashes = new FullHashesResource(this);
threatListUpdates = new ThreatListUpdatesResource(this);
threatLists = new ThreatListsResource(this);
threatMatches = new ThreatMatchesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "safebrowsing"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://safebrowsing.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
private readonly FullHashesResource fullHashes;
/// <summary>Gets the FullHashes resource.</summary>
public virtual FullHashesResource FullHashes
{
get { return fullHashes; }
}
private readonly ThreatListUpdatesResource threatListUpdates;
/// <summary>Gets the ThreatListUpdates resource.</summary>
public virtual ThreatListUpdatesResource ThreatListUpdates
{
get { return threatListUpdates; }
}
private readonly ThreatListsResource threatLists;
/// <summary>Gets the ThreatLists resource.</summary>
public virtual ThreatListsResource ThreatLists
{
get { return threatLists; }
}
private readonly ThreatMatchesResource threatMatches;
/// <summary>Gets the ThreatMatches resource.</summary>
public virtual ThreatMatchesResource ThreatMatches
{
get { return threatMatches; }
}
}
///<summary>A base abstract class for Safebrowsing requests.</summary>
public abstract class SafebrowsingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new SafebrowsingBaseServiceRequest instance.</summary>
protected SafebrowsingBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Xgafv { get; set; }
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Alt { get; set; }
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Safebrowsing parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "fullHashes" collection of methods.</summary>
public class FullHashesResource
{
private const string Resource = "fullHashes";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public FullHashesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Finds the full hashes that match the requested hash prefixes.</summary>
/// <param name="body">The body of the request.</param>
public virtual FindRequest Find(Google.Apis.Safebrowsing.v4.Data.FindFullHashesRequest body)
{
return new FindRequest(service, body);
}
/// <summary>Finds the full hashes that match the requested hash prefixes.</summary>
public class FindRequest : SafebrowsingBaseServiceRequest<Google.Apis.Safebrowsing.v4.Data.FindFullHashesResponse>
{
/// <summary>Constructs a new Find request.</summary>
public FindRequest(Google.Apis.Services.IClientService service, Google.Apis.Safebrowsing.v4.Data.FindFullHashesRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Safebrowsing.v4.Data.FindFullHashesRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "find"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v4/fullHashes:find"; }
}
/// <summary>Initializes Find parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
/// <summary>The "threatListUpdates" collection of methods.</summary>
public class ThreatListUpdatesResource
{
private const string Resource = "threatListUpdates";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ThreatListUpdatesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Fetches the most recent threat list updates. A client can request updates for multiple lists at
/// once.</summary>
/// <param name="body">The body of the request.</param>
public virtual FetchRequest Fetch(Google.Apis.Safebrowsing.v4.Data.FetchThreatListUpdatesRequest body)
{
return new FetchRequest(service, body);
}
/// <summary>Fetches the most recent threat list updates. A client can request updates for multiple lists at
/// once.</summary>
public class FetchRequest : SafebrowsingBaseServiceRequest<Google.Apis.Safebrowsing.v4.Data.FetchThreatListUpdatesResponse>
{
/// <summary>Constructs a new Fetch request.</summary>
public FetchRequest(Google.Apis.Services.IClientService service, Google.Apis.Safebrowsing.v4.Data.FetchThreatListUpdatesRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Safebrowsing.v4.Data.FetchThreatListUpdatesRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "fetch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v4/threatListUpdates:fetch"; }
}
/// <summary>Initializes Fetch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
/// <summary>The "threatLists" collection of methods.</summary>
public class ThreatListsResource
{
private const string Resource = "threatLists";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ThreatListsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Lists the Safe Browsing threat lists available for download.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists the Safe Browsing threat lists available for download.</summary>
public class ListRequest : SafebrowsingBaseServiceRequest<Google.Apis.Safebrowsing.v4.Data.ListThreatListsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v4/threatLists"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
/// <summary>The "threatMatches" collection of methods.</summary>
public class ThreatMatchesResource
{
private const string Resource = "threatMatches";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ThreatMatchesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Finds the threat entries that match the Safe Browsing lists.</summary>
/// <param name="body">The body of the request.</param>
public virtual FindRequest Find(Google.Apis.Safebrowsing.v4.Data.FindThreatMatchesRequest body)
{
return new FindRequest(service, body);
}
/// <summary>Finds the threat entries that match the Safe Browsing lists.</summary>
public class FindRequest : SafebrowsingBaseServiceRequest<Google.Apis.Safebrowsing.v4.Data.FindThreatMatchesResponse>
{
/// <summary>Constructs a new Find request.</summary>
public FindRequest(Google.Apis.Services.IClientService service, Google.Apis.Safebrowsing.v4.Data.FindThreatMatchesRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Safebrowsing.v4.Data.FindThreatMatchesRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "find"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v4/threatMatches:find"; }
}
/// <summary>Initializes Find parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
namespace Google.Apis.Safebrowsing.v4.Data
{
/// <summary>The expected state of a client's local database.</summary>
public class Checksum : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The SHA256 hash of the client state; that is, of the sorted list of all hashes present in the
/// database.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sha256")]
public virtual string Sha256 { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The client metadata associated with Safe Browsing API requests.</summary>
public class ClientInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A client ID that (hopefully) uniquely identifies the client implementation of the Safe Browsing
/// API.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("clientId")]
public virtual string ClientId { get; set; }
/// <summary>The version of the client implementation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("clientVersion")]
public virtual string ClientVersion { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The constraints for this update.</summary>
public class Constraints : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Sets the maximum number of entries that the client is willing to have in the local database. This
/// should be a power of 2 between 2**10 and 2**20. If zero, no database size limit is set.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("maxDatabaseEntries")]
public virtual System.Nullable<int> MaxDatabaseEntries { get; set; }
/// <summary>The maximum size in number of entries. The update will not contain more entries than this value.
/// This should be a power of 2 between 2**10 and 2**20. If zero, no update size limit is set.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("maxUpdateEntries")]
public virtual System.Nullable<int> MaxUpdateEntries { get; set; }
/// <summary>Requests the list for a specific geographic location. If not set the server may pick that value
/// based on the user's IP address. Expects ISO 3166-1 alpha-2 format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("region")]
public virtual string Region { get; set; }
/// <summary>The compression types supported by the client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("supportedCompressions")]
public virtual System.Collections.Generic.IList<string> SupportedCompressions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes a Safe Browsing API update request. Clients can request updates for multiple lists in a
/// single request. NOTE: Field index 2 is unused. NEXT: 4</summary>
public class FetchThreatListUpdatesRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The client metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("client")]
public virtual ClientInfo Client { get; set; }
/// <summary>The requested threat list updates.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("listUpdateRequests")]
public virtual System.Collections.Generic.IList<ListUpdateRequest> ListUpdateRequests { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class FetchThreatListUpdatesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list updates requested by the clients.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("listUpdateResponses")]
public virtual System.Collections.Generic.IList<ListUpdateResponse> ListUpdateResponses { get; set; }
/// <summary>The minimum duration the client must wait before issuing any update request. If this field is not
/// set clients may update as soon as they want.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("minimumWaitDuration")]
public virtual string MinimumWaitDuration { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request to return full hashes matched by the provided hash prefixes.</summary>
public class FindFullHashesRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The client metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("client")]
public virtual ClientInfo Client { get; set; }
/// <summary>The current client states for each of the client's local threat lists.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("clientStates")]
public virtual System.Collections.Generic.IList<string> ClientStates { get; set; }
/// <summary>The lists and hashes to be checked.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatInfo")]
public virtual ThreatInfo ThreatInfo { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class FindFullHashesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The full hashes that matched the requested prefixes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("matches")]
public virtual System.Collections.Generic.IList<ThreatMatch> Matches { get; set; }
/// <summary>The minimum duration the client must wait before issuing any find hashes request. If this field is
/// not set, clients can issue a request as soon as they want.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("minimumWaitDuration")]
public virtual string MinimumWaitDuration { get; set; }
/// <summary>For requested entities that did not match the threat list, how long to cache the
/// response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("negativeCacheDuration")]
public virtual string NegativeCacheDuration { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request to check entries against lists.</summary>
public class FindThreatMatchesRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The client metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("client")]
public virtual ClientInfo Client { get; set; }
/// <summary>The lists and entries to be checked for matches.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatInfo")]
public virtual ThreatInfo ThreatInfo { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class FindThreatMatchesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The threat list matches.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("matches")]
public virtual System.Collections.Generic.IList<ThreatMatch> Matches { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class ListThreatListsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The lists available for download by the client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatLists")]
public virtual System.Collections.Generic.IList<ThreatListDescriptor> ThreatLists { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A single list update request.</summary>
public class ListUpdateRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The constraints associated with this request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("constraints")]
public virtual Constraints Constraints { get; set; }
/// <summary>The type of platform at risk by entries present in the list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("platformType")]
public virtual string PlatformType { get; set; }
/// <summary>The current state of the client for the requested list (the encrypted client state that was
/// received from the last successful list update).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>The types of entries present in the list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatEntryType")]
public virtual string ThreatEntryType { get; set; }
/// <summary>The type of threat posed by entries present in the list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatType")]
public virtual string ThreatType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An update to an individual list.</summary>
public class ListUpdateResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A set of entries to add to a local threat type's list. Repeated to allow for a combination of
/// compressed and raw data to be sent in a single response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("additions")]
public virtual System.Collections.Generic.IList<ThreatEntrySet> Additions { get; set; }
/// <summary>The expected SHA256 hash of the client state; that is, of the sorted list of all hashes present in
/// the database after applying the provided update. If the client state doesn't match the expected state, the
/// client must disregard this update and retry later.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("checksum")]
public virtual Checksum Checksum { get; set; }
/// <summary>The new client state, in encrypted format. Opaque to clients.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("newClientState")]
public virtual string NewClientState { get; set; }
/// <summary>The platform type for which data is returned.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("platformType")]
public virtual string PlatformType { get; set; }
/// <summary>A set of entries to remove from a local threat type's list. Repeated for the same reason as
/// above.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("removals")]
public virtual System.Collections.Generic.IList<ThreatEntrySet> Removals { get; set; }
/// <summary>The type of response. This may indicate that an action is required by the client when the response
/// is received.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("responseType")]
public virtual string ResponseType { get; set; }
/// <summary>The format of the threats.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatEntryType")]
public virtual string ThreatEntryType { get; set; }
/// <summary>The threat type for which data is returned.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatType")]
public virtual string ThreatType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A single metadata entry.</summary>
public class MetadataEntry : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The metadata entry key.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual string Key { get; set; }
/// <summary>The metadata entry value.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The uncompressed threat entries in hash format of a particular prefix length. Hashes can be anywhere
/// from 4 to 32 bytes in size. A large majority are 4 bytes, but some hashes are lengthened if they collide with
/// the hash of a popular URL. Used for sending ThreatEntrySet to clients that do not support compression, or when
/// sending non-4-byte hashes to clients that do support compression.</summary>
public class RawHashes : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The number of bytes for each prefix encoded below. This field can be anywhere from 4 (shortest
/// prefix) to 32 (full SHA256 hash).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("prefixSize")]
public virtual System.Nullable<int> PrefixSize { get; set; }
/// <summary>The hashes, all concatenated into one long string. Each hash has a prefix size of |prefix_size|
/// above. Hashes are sorted in lexicographic order.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rawHashes")]
public virtual string RawHashesValue { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A set of raw indices to remove from a local list.</summary>
public class RawIndices : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The indices to remove from a lexicographically-sorted local list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("indices")]
public virtual System.Collections.Generic.IList<System.Nullable<int>> Indices { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The Rice-Golomb encoded data. Used for sending compressed 4-byte hashes or compressed removal
/// indices.</summary>
public class RiceDeltaEncoding : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The encoded deltas that are encoded using the Golomb-Rice coder.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("encodedData")]
public virtual string EncodedData { get; set; }
/// <summary>The offset of the first entry in the encoded data, or, if only a single integer was encoded, that
/// single integer's value.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("firstValue")]
public virtual System.Nullable<long> FirstValue { get; set; }
/// <summary>The number of entries that are delta encoded in the encoded data. If only a single integer was
/// encoded, this will be zero and the single value will be stored in `first_value`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("numEntries")]
public virtual System.Nullable<int> NumEntries { get; set; }
/// <summary>The Golomb-Rice parameter, which is a number between 2 and 28. This field is missing (that is,
/// zero) if `num_entries` is zero.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("riceParameter")]
public virtual System.Nullable<int> RiceParameter { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An individual threat; for example, a malicious URL or its hash representation. Only one of these fields
/// should be set.</summary>
public class ThreatEntry : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The digest of an executable in SHA256 format. The API supports both binary and hex
/// digests.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("digest")]
public virtual string Digest { get; set; }
/// <summary>A hash prefix, consisting of the most significant 4-32 bytes of a SHA256 hash. This field is in
/// binary format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("hash")]
public virtual string Hash { get; set; }
/// <summary>A URL.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("url")]
public virtual string Url { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The metadata associated with a specific threat entry. The client is expected to know the metadata
/// key/value pairs associated with each threat type.</summary>
public class ThreatEntryMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The metadata entries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entries")]
public virtual System.Collections.Generic.IList<MetadataEntry> Entries { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A set of threats that should be added or removed from a client's local database.</summary>
public class ThreatEntrySet : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The compression type for the entries in this set.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("compressionType")]
public virtual string CompressionType { get; set; }
/// <summary>The raw SHA256-formatted entries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rawHashes")]
public virtual RawHashes RawHashes { get; set; }
/// <summary>The raw removal indices for a local list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rawIndices")]
public virtual RawIndices RawIndices { get; set; }
/// <summary>The encoded 4-byte prefixes of SHA256-formatted entries, using a Golomb-Rice encoding.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("riceHashes")]
public virtual RiceDeltaEncoding RiceHashes { get; set; }
/// <summary>The encoded local, lexicographically-sorted list indices, using a Golomb-Rice encoding. Used for
/// sending compressed removal indices.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("riceIndices")]
public virtual RiceDeltaEncoding RiceIndices { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The information regarding one or more threats that a client submits when checking for matches in threat
/// lists.</summary>
public class ThreatInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The platform types to be checked.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("platformTypes")]
public virtual System.Collections.Generic.IList<string> PlatformTypes { get; set; }
/// <summary>The threat entries to be checked.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatEntries")]
public virtual System.Collections.Generic.IList<ThreatEntry> ThreatEntries { get; set; }
/// <summary>The entry types to be checked.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatEntryTypes")]
public virtual System.Collections.Generic.IList<string> ThreatEntryTypes { get; set; }
/// <summary>The threat types to be checked.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatTypes")]
public virtual System.Collections.Generic.IList<string> ThreatTypes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes an individual threat list. A list is defined by three parameters: the type of threat posed,
/// the type of platform targeted by the threat, and the type of entries in the list.</summary>
public class ThreatListDescriptor : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The platform type targeted by the list's entries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("platformType")]
public virtual string PlatformType { get; set; }
/// <summary>The entry types contained in the list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatEntryType")]
public virtual string ThreatEntryType { get; set; }
/// <summary>The threat type posed by the list's entries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatType")]
public virtual string ThreatType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A match when checking a threat entry in the Safe Browsing threat lists.</summary>
public class ThreatMatch : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The cache lifetime for the returned match. Clients must not cache this response for more than this
/// duration to avoid false positives.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("cacheDuration")]
public virtual string CacheDuration { get; set; }
/// <summary>The platform type matching this threat.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("platformType")]
public virtual string PlatformType { get; set; }
/// <summary>The threat matching this threat.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threat")]
public virtual ThreatEntry Threat { get; set; }
/// <summary>Optional metadata associated with this threat.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatEntryMetadata")]
public virtual ThreatEntryMetadata ThreatEntryMetadata { get; set; }
/// <summary>The threat entry type matching this threat.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatEntryType")]
public virtual string ThreatEntryType { get; set; }
/// <summary>The threat type matching this threat.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("threatType")]
public virtual string ThreatType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using NDatabase;
using NDatabase.Api;
using NDatabase.Exceptions;
using NDatabase.Tool.Wrappers;
using NUnit.Framework;
using Test.NDatabase.Odb.Test.VO.Login;
namespace Test.NDatabase.Odb.Test.Delete
{
[TestFixture]
public class TestDelete : ODBTest
{
private static readonly long start = OdbTime.GetCurrentTimeInMs();
public static string FileName1 = "test-delete.ndb";
public static string FileName2 = "test-delete-defrag.ndb";
public override void TearDown()
{
// deleteBase("t-delete12.ndb");
DeleteBase("t-delete1.ndb");
}
[Test]
public virtual void Test1()
{
var baseName = GetBaseName();
var odb = Open(baseName);
decimal n = odb.Query<VO.Login.Function>().Count();
var function1 = new VO.Login.Function("function1");
var function2 = new VO.Login.Function("function2");
var function3 = new VO.Login.Function("function3");
odb.Store(function1);
odb.Store(function2);
odb.Store(function3);
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
query.Descend("name").Constrain((object) "function2").Equal();
var l = query.Execute<VO.Login.Function>();
var function = l.GetFirst();
odb.Delete(function);
odb.Close();
odb = Open(baseName);
var query1 = odb.Query<VO.Login.Function>();
var l2 = query1.Execute<VO.Login.Function>(true);
AssertEquals(n + 2, odb.Query<VO.Login.Function>().Count());
odb.Close();
DeleteBase(baseName);
}
/// <summary>
/// Test : delete the unique object
/// </summary>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test10()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
long size = query.Execute<VO.Login.Function>().Count;
var f1 = new VO.Login.Function("function1");
odb.Store(f1);
odb.Close();
odb = Open(baseName);
var query1 = odb.Query<VO.Login.Function>();
var f1bis = query1.Execute<VO.Login.Function>().GetFirst();
odb.Delete(f1bis);
odb.Close();
odb = Open(baseName);
var query3 = odb.Query<VO.Login.Function>();
AssertEquals(size, query3.Execute<VO.Login.Function>().Count);
odb.Store(new VO.Login.Function("last function"));
odb.Close();
odb = Open(baseName);
var query2 = odb.Query<VO.Login.Function>();
var l = query2.Execute<VO.Login.Function>();
odb.Close();
AssertEquals(size + 1, l.Count);
}
/// <summary>
/// Test : delete the unique object
/// </summary>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test11()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var size = odb.Query<VO.Login.Function>().Count();
var f1 = new VO.Login.Function("function1");
odb.Store(f1);
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
var f1bis = query.Execute<VO.Login.Function>().GetFirst();
odb.Delete(f1bis);
odb.Store(new VO.Login.Function("last function"));
odb.Close();
odb = Open(baseName);
var query1 = odb.Query<VO.Login.Function>();
AssertEquals(size + 1, query1.Execute<VO.Login.Function>().Count);
odb.Close();
}
/// <summary>
/// Bug detected by Olivier using the ODBMainExplorer, deleting many objects
/// without commiting,and commiting at the end
/// </summary>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test12()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
var f3 = new VO.Login.Function("function3");
odb.Store(f1);
odb.Store(f2);
odb.Store(f3);
var idf1 = odb.GetObjectId(f1);
var idf2 = odb.GetObjectId(f2);
var idf3 = odb.GetObjectId(f3);
odb.Close();
try
{
odb = Open(baseName);
odb.DeleteObjectWithId(idf3);
odb.DeleteObjectWithId(idf2);
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
var l = query.Execute<VO.Login.Function>();
odb.Close();
AssertEquals(1, l.Count);
}
catch (OdbRuntimeException)
{
DeleteBase(baseName);
throw;
}
}
/// <summary>
/// Bug detected by Olivier using the ODBMainExplorer, deleting many objects
/// without commiting,and commiting at the end
/// </summary>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test13()
{
var baseName = GetBaseName();
IOdb odb = null;
DeleteBase(baseName);
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
var f3 = new VO.Login.Function("function3");
odb.Store(f1);
odb.Store(f2);
odb.Store(f3);
var idf1 = odb.GetObjectId(f1);
var idf2 = odb.GetObjectId(f2);
var idf3 = odb.GetObjectId(f3);
var storageEngine = ((global::NDatabase.Odb) odb).GetStorageEngine();
var p1 = storageEngine.GetObjectReader().GetObjectPositionFromItsOid(idf1, true, false);
var p2 = storageEngine.GetObjectReader().GetObjectPositionFromItsOid(idf2, true, false);
var p3 = storageEngine.GetObjectReader().GetObjectPositionFromItsOid(idf3, true, false);
odb.Close();
try
{
odb = Open(baseName);
f1 = (VO.Login.Function) odb.GetObjectFromId(idf1);
f2 = (VO.Login.Function) odb.GetObjectFromId(idf2);
f3 = (VO.Login.Function) odb.GetObjectFromId(idf3);
odb.Delete(f3);
odb.Delete(f2);
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
var l = query.Execute<VO.Login.Function>();
odb.Close();
AssertEquals(1, l.Count);
}
catch (OdbRuntimeException)
{
DeleteBase(baseName);
throw;
}
DeleteBase(baseName);
}
/// <summary>
/// creates 5 objects,commit.
/// </summary>
/// <remarks>
/// creates 5 objects,commit. Then create 2 new objects and delete 4 existing
/// objects without committing,and committing at the end
/// </remarks>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test14()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
var f3 = new VO.Login.Function("function3");
var f4 = new VO.Login.Function("function4");
var f5 = new VO.Login.Function("function5");
odb.Store(f1);
odb.Store(f2);
odb.Store(f3);
odb.Store(f4);
odb.Store(f5);
AssertEquals(5, odb.Query<VO.Login.Function>().Count());
odb.Close();
try
{
odb = Open(baseName);
var f6 = new VO.Login.Function("function6");
var f7 = new VO.Login.Function("function7");
odb.Store(f6);
odb.Store(f7);
AssertEquals(7, odb.Query<VO.Login.Function>().Count());
var query = odb.Query<VO.Login.Function>();
var objects = query.Execute<VO.Login.Function>();
var i = 0;
while (objects.HasNext() && i < 4)
{
odb.Delete<VO.Login.Function>(objects.Next());
i++;
}
AssertEquals(3, odb.Query<VO.Login.Function>().Count());
odb.Close();
odb = Open(baseName);
AssertEquals(3, odb.Query<VO.Login.Function>().Count());
var query1 = odb.Query<VO.Login.Function>();
objects = query1.Execute<VO.Login.Function>();
// println(objects);
AssertEquals((string) "function5", (string) (objects.Next()).GetName());
AssertEquals((string) "function6", (string) (objects.Next()).GetName());
AssertEquals((string) "function7", (string) (objects.Next()).GetName());
odb.Close();
}
catch (OdbRuntimeException)
{
DeleteBase(baseName);
throw;
}
DeleteBase(baseName);
}
/// <summary>
/// creates 2 objects.
/// </summary>
/// <remarks>
/// creates 2 objects. Delete them. And create 2 new objects
/// </remarks>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test15()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
odb.Store(f1);
odb.Store(f2);
AssertEquals(2, odb.Query<VO.Login.Function>().Count());
odb.Delete(f1);
odb.Delete(f2);
AssertEquals(0, odb.Query<VO.Login.Function>().Count());
odb.Store(f1);
odb.Store(f2);
AssertEquals(2, odb.Query<VO.Login.Function>().Count());
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
AssertEquals(2, query.Execute<VO.Login.Function>().Count);
odb.Close();
DeleteBase(baseName);
}
/// <summary>
/// creates 2 objects.
/// </summary>
/// <remarks>
/// creates 2 objects. Delete them by oid. And create 2 new objects
/// </remarks>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test15_by_oid()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
var oid1 = odb.Store(f1);
var oid2 = odb.Store(f2);
AssertEquals(2, odb.Query<VO.Login.Function>().Count());
odb.DeleteObjectWithId(oid1);
odb.DeleteObjectWithId(oid2);
AssertEquals(0, odb.Query<VO.Login.Function>().Count());
odb.Store(f1);
odb.Store(f2);
AssertEquals(2, odb.Query<VO.Login.Function>().Count());
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
AssertEquals(2, query.Execute<VO.Login.Function>().Count);
odb.Close();
DeleteBase(baseName);
}
/// <summary>
/// creates 2 objects.
/// </summary>
/// <remarks>
/// creates 2 objects. Delete them by oid. And create 2 new objects
/// </remarks>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test15_by_oid_2()
{
var baseName = GetBaseName();
IOdb odb = null;
DeleteBase(baseName);
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
var oid1 = odb.Store(f1);
var oid2 = odb.Store(f2);
AssertEquals(2, odb.Query<VO.Login.Function>().Count());
odb.Close();
odb = Open(baseName);
odb.DeleteObjectWithId(oid1);
odb.DeleteObjectWithId(oid2);
AssertEquals(0, odb.Query<VO.Login.Function>().Count());
odb.Store(f1);
odb.Store(f2);
AssertEquals(2, odb.Query<VO.Login.Function>().Count());
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
AssertEquals(2, query.Execute<VO.Login.Function>().Count);
odb.Close();
DeleteBase(baseName);
}
/// <summary>
/// creates x objects.
/// </summary>
/// <remarks>
/// creates x objects. Delete them. And create x new objects
/// </remarks>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test16()
{
var baseName = GetBaseName();
var size = 10000;
IOdb odb = null;
DeleteBase(baseName);
odb = Open(baseName);
var oids = new OID[size];
for (var i = 0; i < size; i++)
oids[i] = odb.Store(new VO.Login.Function("function" + i));
AssertEquals(size, odb.Query<VO.Login.Function>().Count());
for (var i = 0; i < size; i++)
odb.DeleteObjectWithId(oids[i]);
AssertEquals(0, odb.Query<VO.Login.Function>().Count());
for (var i = 0; i < size; i++)
oids[i] = odb.Store(new VO.Login.Function("function" + i));
AssertEquals(size, odb.Query<VO.Login.Function>().Count());
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
AssertEquals(size, query.Execute<VO.Login.Function>().Count);
odb.Close();
DeleteBase(baseName);
}
/// <summary>
/// creates 3 objects.
/// </summary>
/// <remarks>
/// creates 3 objects. Delete the 2th. And create 3 new objects
/// </remarks>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test17()
{
var baseName = GetBaseName();
IOdb odb = null;
DeleteBase(baseName);
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
var f3 = new VO.Login.Function("function2");
odb.Store(f1);
odb.Store(f2);
odb.Store(f3);
AssertEquals(3, odb.Query<VO.Login.Function>().Count());
odb.Delete(f2);
AssertEquals(2, odb.Query<VO.Login.Function>().Count());
// odb.store(f1);
odb.Store(f2);
// odb.store(f3);
AssertEquals(3, odb.Query<VO.Login.Function>().Count());
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
AssertEquals(3, query.Execute<VO.Login.Function>().Count);
odb.Close();
DeleteBase(baseName);
}
/// <summary>
/// creates 3 objects.
/// </summary>
/// <remarks>
/// creates 3 objects. commit. Creates 3 new . Delete the 2th commited. And
/// create 3 new objects
/// </remarks>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test18()
{
var baseName = GetBaseName();
IOdb odb = null;
DeleteBase(baseName);
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
var f3 = new VO.Login.Function("function2");
var oid1 = odb.Store(f1);
var oid2 = odb.Store(f2);
var oid3 = odb.Store(f3);
AssertEquals(3, odb.Query<VO.Login.Function>().Count());
odb.Close();
odb = Open(baseName);
odb.DeleteObjectWithId(oid2);
AssertEquals(2, odb.Query<VO.Login.Function>().Count());
// odb.store(f1);
odb.Store(new VO.Login.Function("f11"));
odb.Store(new VO.Login.Function("f12"));
odb.Store(new VO.Login.Function("f13"));
// odb.store(f3);
AssertEquals(5, odb.Query<VO.Login.Function>().Count());
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
AssertEquals(5, query.Execute<VO.Login.Function>().Count);
odb.Close();
DeleteBase(baseName);
}
/// <summary>
/// Stores an object, closes the base.
/// </summary>
/// <remarks>
/// Stores an object, closes the base. Loads the object, gets its oid and
/// delete by oid.
/// </remarks>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test19()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
odb.Store(f1);
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
var objects = query.Execute<VO.Login.Function>();
AssertEquals(1, objects.Count);
var f2 = objects.GetFirst();
var oid = odb.GetObjectId(f2);
odb.DeleteObjectWithId(oid);
var query1 = odb.Query<VO.Login.Function>();
AssertEquals(0, query1.Execute<VO.Login.Function>().Count);
odb.Close();
odb = Open(baseName);
var query2 = odb.Query<VO.Login.Function>();
objects = query2.Execute<VO.Login.Function>();
AssertEquals(0, objects.Count);
}
[Test]
public virtual void Test2()
{
var baseName = GetBaseName();
DeleteBase(baseName);
long nbFunctions;
using (var odb = Open(baseName))
{
nbFunctions = odb.Query<VO.Login.Function>().Count();
decimal nbProfiles = odb.Query<Profile>().Count();
var function1 = new VO.Login.Function("function1");
var function2 = new VO.Login.Function("function2");
var function3 = new VO.Login.Function("function3");
var functions = new List<VO.Login.Function>();
functions.Add(function1);
functions.Add(function2);
functions.Add(function3);
var profile1 = new Profile("profile1", functions);
var profile2 = new Profile("profile2", function1);
odb.Store(profile1);
odb.Store(profile2);
}
using (var odb = Open(baseName))
{
var query1 = odb.Query<VO.Login.Function>();
var lfunctions = query1.Execute<VO.Login.Function>(true);
AssertEquals(nbFunctions + 3, lfunctions.Count);
var query = odb.Query<VO.Login.Function>();
query.Descend("name").Constrain("function2").Equal();
var l = query.Execute<VO.Login.Function>();
var function = l.GetFirst();
odb.Delete(function);
}
using (var odb = Open(baseName))
{
AssertEquals(nbFunctions + 2, odb.Query<VO.Login.Function>().Count());
var query3 = odb.Query<VO.Login.Function>();
var l2 = query3.Execute<VO.Login.Function>(true);
// check Profile 1
var query2 = odb.Query<Profile>();
query2.Descend("name").Constrain("profile1").Equal();
var lprofile = query2.Execute<Profile>();
var p1 = lprofile.GetFirst();
AssertEquals(3, p1.GetFunctions().Count);
Assert.That(p1.GetFunctions(), Contains.Item(null));
}
}
/// <summary>
/// Stores on object and close database then Stores another object, commits
/// without closing.
/// </summary>
/// <remarks>
/// Stores on object and close database then Stores another object, commits
/// without closing. Loads the object, gets its oid and delete by oid. In the
/// case the commit has no write actions. And there was a bug : when there is
/// no write actions, the commit process is much more simple! but in this the
/// cache was not calling the transaction.clear and this was a reason for
/// some connected/unconnected zone problem! (step14 of the turotial.)
/// </remarks>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
[Ignore("it contains commiting bug, it is well know and will be fixed in the future")]
public virtual void Test20()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var f0 = new VO.Login.Function("1function0");
odb.Store(f0);
odb.Close();
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
odb.Store(f1);
odb.Commit();
var query = odb.Query<VO.Login.Function>();
query.Descend("name").Constrain("func%").Like();
var objects = query.Execute<VO.Login.Function>();
AssertEquals(1, objects.Count);
var f2 = objects.GetFirst();
var oid = odb.GetObjectId(f2);
odb.DeleteObjectWithId(oid);
var query1 = odb.Query<VO.Login.Function>();
AssertEquals(1, query1.Execute<VO.Login.Function>().Count);
odb.Close();
odb = Open(baseName);
var query2 = odb.Query<VO.Login.Function>();
objects = query2.Execute<VO.Login.Function>();
AssertEquals(1, objects.Count);
}
/// <summary>
/// Bug when deleting the first object of unconnected zone when commited zone
/// already have at least one object.
/// </summary>
/// <remarks>
/// Bug when deleting the first object of unconnected zone when commited zone
/// already have at least one object.
/// Detected running the polePosiiton Bahrain circuit.
/// </remarks>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test21()
{
IOdb odb = null;
var baseName = GetBaseName();
odb = Open(baseName);
var f0 = new VO.Login.Function("function0");
odb.Store(f0);
odb.Close();
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
odb.Store(f1);
var f2 = new VO.Login.Function("function2");
odb.Store(f2);
odb.Delete(f1);
odb.Close();
odb = Open(baseName);
var objects = odb.Query<VO.Login.Function>().Execute<VO.Login.Function>();
AssertEquals(2, objects.Count);
odb.Close();
}
[Test]
public virtual void Test22Last_toCheckDuration()
{
var duration = OdbTime.GetCurrentTimeInMs() - start;
long d = 2200;
Println("duration=" + duration);
if (testPerformance && duration > d)
Fail("Duration is higher than " + d + " : " + duration);
}
[Test]
public virtual void Test3()
{
var baseName = GetBaseName();
var baseName2 = "2" + baseName;
var odb = Open(baseName);
var size = 1000;
for (var i = 0; i < size; i++)
odb.Store(new VO.Login.Function("function " + i));
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
var objects = query.Execute<VO.Login.Function>(false);
var j = 0;
while (objects.HasNext() && j < objects.Count - 1)
{
odb.Delete(objects.Next());
j++;
}
odb.Close();
odb = Open(baseName);
AssertEquals(1, odb.Query<VO.Login.Function>().Count());
odb.Close();
odb = Open(baseName);
odb.DefragmentTo(baseName2);
odb.Close();
odb = Open(baseName2);
AssertEquals(1, odb.Query<VO.Login.Function>().Count());
odb.Close();
DeleteBase(baseName);
DeleteBase(baseName2);
}
[Test]
public virtual void Test30()
{
var baseName = GetBaseName();
var odb = Open(baseName);
var oid1 = odb.Store(new VO.Login.Function("function 1"));
var oid2 = odb.Store(new VO.Login.Function("function 2"));
odb.Close();
Println(oid1);
Println(oid2);
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
odb.Delete(query.Execute<VO.Login.Function>().GetFirst());
odb.Close();
odb = Open(baseName);
var query1 = odb.Query<VO.Login.Function>();
var f = query1.Execute<VO.Login.Function>().GetFirst();
odb.Close();
DeleteBase(baseName);
AssertEquals("function 2", f.GetName());
}
[Test]
public virtual void Test4()
{
var baseName = GetBaseName();
var n = 100;
var odb = Open(baseName);
var size = odb.Query<VO.Login.Function>().Count();
for (var i = 0; i < n; i++)
{
var login = new VO.Login.Function("login - " + (i + 1));
odb.Store(login);
AssertEquals(size + i + 1, odb.Query<VO.Login.Function>().Count());
Console.WriteLine(i);
}
// IStorageEngine engine = Dummy.getEngine(odb);
odb.Commit();
var query = odb.Query<VO.Login.Function>();
var l = query.Execute<VO.Login.Function>(true);
var j = 0;
while (l.HasNext())
{
Console.WriteLine(" i=" + j);
var f = l.Next();
odb.Delete(f);
var query1 = odb.Query<VO.Login.Function>();
var l2 = query1.Execute<VO.Login.Function>();
AssertEquals(size + n - (j + 1), l2.Count);
j++;
}
odb.Commit();
odb.Close();
DeleteBase(baseName);
}
[Test]
public virtual void Test5()
{
IOdb odb = null;
var baseName = GetBaseName();
odb = Open(baseName);
var f = new VO.Login.Function("function1");
odb.Store(f);
var id = odb.GetObjectId(f);
try
{
odb.Delete(f);
var id2 = odb.GetObjectId(f);
Fail("The object has been deleted, the id should have been marked as deleted");
}
catch (OdbRuntimeException)
{
odb.Close();
DeleteBase(baseName);
}
}
[Test]
public virtual void Test5_byOid()
{
IOdb odb = null;
var baseName = GetBaseName();
odb = Open(baseName);
var f = new VO.Login.Function("function1");
odb.Store(f);
var oid = odb.GetObjectId(f);
try
{
odb.DeleteObjectWithId(oid);
var id2 = odb.GetObjectId(f);
Fail("The object has been deleted, the id should have been marked as deleted");
}
catch (OdbRuntimeException)
{
odb.Close();
DeleteBase(baseName);
}
}
[Test]
public virtual void Test6()
{
IOdb odb = null;
var baseName = GetBaseName();
odb = Open(baseName);
var f = new VO.Login.Function("function1");
odb.Store(f);
var id = odb.GetObjectId(f);
odb.Commit();
try
{
odb.Delete(f);
odb.GetObjectFromId(id);
Fail("The object has been deleted, the id should have been marked as deleted");
}
catch (OdbRuntimeException)
{
odb.Close();
DeleteBase("t-delete1.ndb");
}
}
[Test]
public virtual void Test7()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
var f3 = new VO.Login.Function("function3");
odb.Store(f1);
odb.Store(f2);
odb.Store(f3);
var id = odb.GetObjectId(f3);
odb.Close();
try
{
odb = Open(baseName);
var f3bis = (VO.Login.Function) odb.GetObjectFromId(id);
odb.Delete(f3bis);
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
var l = query.Execute<VO.Login.Function>();
odb.Close();
AssertEquals(2, l.Count);
}
catch (OdbRuntimeException)
{
odb.Close();
DeleteBase(baseName);
}
}
/// <summary>
/// Test : delete the last object and insert a new one in the same
/// transaction - detected by Alessandra
/// </summary>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test8()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
var f3 = new VO.Login.Function("function3");
odb.Store(f1);
odb.Store(f2);
odb.Store(f3);
var id = odb.GetObjectId(f3);
odb.Close();
odb = Open(baseName);
var f3bis = (VO.Login.Function) odb.GetObjectFromId(id);
odb.Delete(f3bis);
odb.Store(new VO.Login.Function("last function"));
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
var l = query.Execute<VO.Login.Function>();
odb.Close();
AssertEquals(3, l.Count);
}
/// <summary>
/// Test : delete the last object and insert a new one in another transaction
/// - detected by Alessandra
/// </summary>
/// <exception cref="System.Exception">System.Exception</exception>
[Test]
public virtual void Test9()
{
var baseName = GetBaseName();
IOdb odb = null;
odb = Open(baseName);
var f1 = new VO.Login.Function("function1");
var f2 = new VO.Login.Function("function2");
var f3 = new VO.Login.Function("function3");
odb.Store(f1);
odb.Store(f2);
odb.Store(f3);
var id = odb.GetObjectId(f3);
odb.Close();
odb = Open(baseName);
var f3bis = (VO.Login.Function) odb.GetObjectFromId(id);
odb.Delete(f3bis);
odb.Close();
odb = Open(baseName);
odb.Store(new VO.Login.Function("last function"));
odb.Close();
odb = Open(baseName);
var query = odb.Query<VO.Login.Function>();
var l = query.Execute<VO.Login.Function>();
odb.Close();
AssertEquals(3, l.Count);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using Aurora.Framework;
using Aurora.Framework.Servers.HttpServer;
using Aurora.Simulation.Base;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Services.Interfaces;
using OpenMetaverse.StructuredData;
namespace Aurora.Framework
{
public class ConnectorRegistry
{
public static List<ConnectorBase> Connectors = new List<ConnectorBase>();
public static void RegisterConnector(ConnectorBase con)
{
Connectors.Add(con);
}
}
public class ConnectorBase
{
protected IRegistryCore m_registry;
protected IConfigurationService m_configService
{
get { return m_registry.RequestModuleInterface<IConfigurationService>(); }
}
protected bool m_doRemoteCalls = false;
protected string m_name;
protected bool m_doRemoteOnly = false;
protected int m_OSDRequestTimeout = 10000;
protected int m_OSDRequestTryCount = 7;
protected string m_password = "";
public string PluginName
{
get { return m_name; }
}
public bool Enabled
{
get;
set;
}
public void Init(IRegistryCore registry, string name, string password)
{
m_password = password;
Init(registry, name);
}
public void Init(IRegistryCore registry, string name)
{
Enabled = true;
m_registry = registry;
m_name = name;
ISimulationBase simBase = registry == null ? null : registry.RequestModuleInterface<ISimulationBase>();
if (simBase != null)
{
IConfigSource source = registry.RequestModuleInterface<ISimulationBase>().ConfigSource;
IConfig config;
if ((config = source.Configs["AuroraConnectors"]) != null)
{
if (config.Contains(name + "DoRemoteCalls"))
m_doRemoteCalls = config.GetBoolean(name + "DoRemoteCalls", false);
else
m_doRemoteCalls = config.GetBoolean("DoRemoteCalls", false);
}
if ((config = source.Configs["Configuration"]) != null)
{
m_OSDRequestTimeout = config.GetInt("OSDRequestTimeout", m_OSDRequestTimeout);
m_OSDRequestTryCount = config.GetInt("OSDRequestTryCount", m_OSDRequestTryCount);
}
}
if (m_doRemoteCalls)
m_doRemoteOnly = true;//Lock out local + remote for now
ConnectorRegistry.RegisterConnector(this);
}
public void SetPassword(string password)
{
m_password = password;
}
public void SetDoRemoteCalls(bool doRemoteCalls)
{
m_doRemoteCalls = doRemoteCalls;
m_doRemoteOnly = doRemoteCalls;
}
public object DoRemote(params object[] o)
{
return DoRemoteCall(false, "ServerURI", false, UUID.Zero, o);
}
public object DoRemoteForced(params object[] o)
{
return DoRemoteCall(true, "ServerURI", false, UUID.Zero, o);
}
public object DoRemoteForUser(UUID userID, params object[] o)
{
return DoRemoteCall(false, "ServerURI", false, UUID.Zero, o);
}
public object DoRemoteByURL(string url, params object[] o)
{
return DoRemoteCall(false, url, false, UUID.Zero, o);
}
public object DoRemoteByHTTP(string url, params object[] o)
{
return DoRemoteCall(false, url, true, UUID.Zero, o);
}
public object DoRemoteCall(bool forced, string url, bool urlOverrides, UUID userID, params object[] o)
{
if (!m_doRemoteCalls && !forced)
return null;
StackTrace stackTrace = new StackTrace();
int upStack = 1;
if (userID == UUID.Zero)
upStack = 2;
MethodInfo method;
CanBeReflected reflection;
GetReflection(upStack, stackTrace, out method, out reflection);
string methodName = reflection != null && reflection.RenamedMethod != "" ? reflection.RenamedMethod : method.Name;
OSDMap map = new OSDMap();
map["Method"] = methodName;
if (reflection.UsePassword)
map["Password"] = m_password;
int i = 0;
var parameters = method.GetParameters();
if (o.Length != parameters.Length)
{
MainConsole.Instance.ErrorFormat("FAILED TO GET VALID NUMBER OF PARAMETERS TO SEND REMOTELY FOR {0}, EXPECTED {1}, GOT {2}", methodName, parameters.Length, o.Length);
return null;
}
foreach(ParameterInfo info in parameters)
{
OSD osd = o[i] == null ? null : Util.MakeOSD(o[i], o[i].GetType());
if (osd != null)
map.Add(info.Name, osd);
else
map.Add(info.Name, new OSD());
i++;
}
List<string> m_ServerURIs = GetURIs(urlOverrides, map, url, userID);
OSDMap response = null;
int loops2Do = (m_ServerURIs.Count < m_OSDRequestTryCount) ? m_ServerURIs.Count : m_OSDRequestTryCount;
for (int index = 0; index < loops2Do; index++)
{
string uri = m_ServerURIs[index];
if (GetOSDMap(uri, map, out response))
break;
}
if (response == null || !response)
return null;
object inst = null;
try
{
if (method.ReturnType == typeof(string))
inst = string.Empty;
else if (method.ReturnType == typeof(void))
return null;
else if (method.ReturnType == typeof(System.Drawing.Image))
inst = null;
else
inst = Activator.CreateInstance(method.ReturnType);
}
catch
{
if (method.ReturnType == typeof(string))
inst = string.Empty;
}
if (response["Value"] == "null")
return null;
var instance = inst as IDataTransferable;
if (instance != null)
{
instance.FromOSD((OSDMap)response["Value"]);
return instance;
}
return Util.OSDToObject(response["Value"], method.ReturnType);
}
protected virtual List<string> GetURIs(bool urlOverrides, OSDMap map, string url, UUID userID)
{
return urlOverrides ? new List<string>() { url } : m_configService.FindValueOf(userID.ToString(), url, false);
}
private void GetReflection(int upStack, StackTrace stackTrace, out MethodInfo method, out CanBeReflected reflection)
{
method = (MethodInfo)stackTrace.GetFrame(upStack).GetMethod();
reflection = (CanBeReflected)Attribute.GetCustomAttribute(method, typeof(CanBeReflected));
if (reflection != null && reflection.NotReflectableLookUpAnotherTrace)
GetReflection(upStack + 1, stackTrace, out method, out reflection);
}
public bool GetOSDMap(string url, OSDMap map, out OSDMap response)
{
response = null;
string resp = WebUtils.ServiceOSDRequest(url, map, "POST", m_OSDRequestTimeout);
if (resp == "" || resp.StartsWith("<"))
return false;
try
{
response = (OSDMap)OSDParser.DeserializeJson(resp);
}
catch
{
response = null;
return false;
}
return response["Success"];
}
public bool CheckPassword(string password)
{
return password == m_password;
}
}
public class ServerHandler : BaseRequestHandler
{
protected string m_SessionID;
protected IRegistryCore m_registry;
protected static Dictionary<string, List<MethodImplementation>> m_methods = null;
protected IGridRegistrationService m_urlModule;
protected ICapsService m_capsService;
public ServerHandler(string url, string SessionID, IRegistryCore registry) :
base("POST", url)
{
m_SessionID = SessionID;
m_registry = registry;
m_capsService = m_registry.RequestModuleInterface<ICapsService>();
m_urlModule = m_registry.RequestModuleInterface<IGridRegistrationService>();
if (m_methods == null)
{
m_methods = new Dictionary<string, List<MethodImplementation>>();
List<string> alreadyRunPlugins = new List<string>();
foreach (ConnectorBase plugin in ConnectorRegistry.Connectors)
{
if (alreadyRunPlugins.Contains(plugin.PluginName))
continue;
alreadyRunPlugins.Add(plugin.PluginName);
foreach (MethodInfo method in plugin.GetType().GetMethods())
{
CanBeReflected reflection = (CanBeReflected)Attribute.GetCustomAttribute(method, typeof(CanBeReflected));
if (reflection != null)
{
string methodName = reflection.RenamedMethod == "" ? method.Name : reflection.RenamedMethod;
List<MethodImplementation> methods = new List<MethodImplementation>();
MethodImplementation imp = new MethodImplementation() { Method = method, Reference = plugin, Attribute = reflection };
if (!m_methods.TryGetValue(methodName, out methods))
m_methods.Add(methodName, (methods = new List<MethodImplementation>()));
methods.Add(imp);
}
}
}
}
}
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
try
{
OSDMap args = WebUtils.GetOSDMap(body, false);
if (args != null)
return HandleMap(args);
}
catch (Exception ex)
{
MainConsole.Instance.Warn("[ServerHandler]: Error occured: " + ex.ToString());
}
return MainServer.BadRequest;
}
public byte[] HandleMap(OSDMap args)
{
if (args.ContainsKey("Method"))
{
string method = args["Method"].AsString();
try
{
MethodImplementation methodInfo;
if (GetMethodInfo(method, args.Count - 1, out methodInfo))
{
if (m_SessionID == "")
{
if (methodInfo.Attribute.ThreatLevel != ThreatLevel.None)
return MainServer.BadRequest;
}
else if (!m_urlModule.CheckThreatLevel(m_SessionID, method, methodInfo.Attribute.ThreatLevel))
return MainServer.BadRequest;
if (methodInfo.Attribute.UsePassword)
{
if (!methodInfo.Reference.CheckPassword(args["Password"].AsString()))
return MainServer.BadRequest;
}
if (methodInfo.Attribute.OnlyCallableIfUserInRegion)
{
UUID userID = args["UserID"].AsUUID();
IClientCapsService clientCaps = m_capsService.GetClientCapsService(userID);
if (userID == UUID.Zero || clientCaps == null || clientCaps.GetRootCapsService().RegionHandle != ulong.Parse(m_SessionID))
return MainServer.BadRequest;
}
ParameterInfo[] paramInfo = methodInfo.Method.GetParameters();
object[] parameters = new object[paramInfo.Length];
int paramNum = 0;
foreach (ParameterInfo param in paramInfo)
{
if (args[param.Name].Type == OSDType.Unknown)
parameters[paramNum++] = null;
else if(param.ParameterType == typeof(OSD))
parameters[paramNum++] = args[param.Name];
else
parameters[paramNum++] = Util.OSDToObject(args[param.Name], param.ParameterType);
}
object o = methodInfo.Method.FastInvoke(paramInfo, methodInfo.Reference, parameters);
OSDMap response = new OSDMap();
if (o == null)//void method
response["Value"] = "null";
else
response["Value"] = Util.MakeOSD(o, methodInfo.Method.ReturnType);
response["Success"] = true;
return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(response, true));
}
}
catch (Exception ex)
{
MainConsole.Instance.WarnFormat("[ServerHandler]: Error occured for method {0}: {1}", method, ex.ToString());
}
}
else
MainConsole.Instance.Warn("[ServerHandler]: Post did not have a method block");
return MainServer.BadRequest;
}
private bool GetMethodInfo(string method, int parameters, out MethodImplementation methodInfo)
{
List<MethodImplementation> methods = new List<MethodImplementation>();
if (m_methods.TryGetValue(method, out methods))
{
if (methods.Count == 1)
{
methodInfo = methods[0];
return true;
}
foreach (MethodImplementation m in methods)
{
if (m.Method.GetParameters().Length == parameters)
{
methodInfo = m;
return true;
}
}
}
MainConsole.Instance.Warn("COULD NOT FIND METHOD: " + method);
methodInfo = null;
return false;
}
}
public class MethodImplementation
{
public MethodInfo Method;
public ConnectorBase Reference;
public CanBeReflected Attribute;
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.Results;
using QuantConnect.Lean.Engine.Setup;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Orders;
using QuantConnect.Packets;
using QuantConnect.Statistics;
namespace QuantConnect.Tests.Engine
{
/// <summary>
/// Provides a result handler implementation that handles result packets via
/// a constructor defined function. Also, this implementation does not require
/// the Run method to be called at all, a task is launched via ctor to process
/// the packets
/// </summary>
public class TestResultHandler : IResultHandler
{
private AlgorithmNodePacket _job = new BacktestNodePacket();
private readonly Action<Packet> _packetHandler;
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
public ConcurrentQueue<Packet> Messages { get; set; }
public ConcurrentDictionary<string, Chart> Charts { get; set; }
public TimeSpan ResamplePeriod { get; private set; }
public TimeSpan NotificationPeriod { get; private set; }
public bool IsActive { get; private set; }
public TestResultHandler(Action<Packet> packetHandler = null)
{
_packetHandler = packetHandler ?? (packet => { });
Messages = new ConcurrentQueue<Packet>();
Task.Run(() =>
{
try
{
IsActive = true;
while (!_cancellationTokenSource.IsCancellationRequested)
{
Packet packet;
if (Messages.TryDequeue(out packet))
{
_packetHandler(packet);
}
Thread.Sleep(1);
}
}
finally
{
IsActive = false;
}
});
}
public void Initialize(AlgorithmNodePacket job,
IMessagingHandler messagingHandler,
IApi api,
IDataFeed dataFeed,
ISetupHandler setupHandler,
ITransactionHandler transactionHandler)
{
_job = job;
}
public void Run()
{
}
public void DebugMessage(string message)
{
Messages.Enqueue(new DebugPacket(_job.ProjectId, _job.AlgorithmId, _job.CompileId, message));
}
public void SystemDebugMessage(string message)
{
Messages.Enqueue(new SystemDebugPacket(_job.ProjectId, _job.AlgorithmId, _job.CompileId, message));
}
public void SecurityType(List<SecurityType> types)
{
}
public void LogMessage(string message)
{
Messages.Enqueue(new LogPacket(_job.AlgorithmId, message));
}
public void ErrorMessage(string error, string stacktrace = "")
{
Messages.Enqueue(new HandledErrorPacket(_job.AlgorithmId, error, stacktrace));
}
public void RuntimeError(string message, string stacktrace = "")
{
Messages.Enqueue(new RuntimeErrorPacket(_job.UserId, _job.AlgorithmId, message, stacktrace));
}
public void Sample(string chartName, string seriesName, int seriesIndex, SeriesType seriesType, DateTime time, decimal value, string unit = "$")
{
//Add a copy locally:
if (!Charts.ContainsKey(chartName))
{
Charts.AddOrUpdate(chartName, new Chart(chartName));
}
//Add the sample to our chart:
if (!Charts[chartName].Series.ContainsKey(seriesName))
{
Charts[chartName].Series.Add(seriesName, new Series(seriesName, seriesType, seriesIndex, unit));
}
//Add our value:
Charts[chartName].Series[seriesName].Values.Add(new ChartPoint(time, value));
}
public void SampleEquity(DateTime time, decimal value)
{
Sample("Strategy Equity", "Equity", 0, SeriesType.Candle, time, value);
}
public void SamplePerformance(DateTime time, decimal value)
{
Sample("Strategy Equity", "Daily Performance", 1, SeriesType.Line, time, value, "%");
}
public void SampleBenchmark(DateTime time, decimal value)
{
Sample("Benchmark", "Benchmark", 0, SeriesType.Line, time, value);
}
public void SampleAssetPrices(Symbol symbol, DateTime time, decimal value)
{
Sample("Stockplot: " + symbol.Value, "Stockplot: " + symbol.Value, 0, SeriesType.Line, time, value);
}
public void SampleRange(List<Chart> updates)
{
foreach (var update in updates)
{
//Create the chart if it doesn't exist already:
if (!Charts.ContainsKey(update.Name))
{
Charts.AddOrUpdate(update.Name, new Chart(update.Name, update.ChartType));
}
//Add these samples to this chart.
foreach (var series in update.Series.Values)
{
//If we don't already have this record, its the first packet
if (!Charts[update.Name].Series.ContainsKey(series.Name))
{
Charts[update.Name].Series.Add(series.Name, new Series(series.Name, series.SeriesType, series.Index, series.Unit));
}
//We already have this record, so just the new samples to the end:
Charts[update.Name].Series[series.Name].Values.AddRange(series.Values);
}
}
}
public void SetAlgorithm(IAlgorithm algorithm)
{
}
public void StoreResult(Packet packet, bool async = false)
{
}
public void SendFinalResult(AlgorithmNodePacket job,
Dictionary<int, Order> orders,
Dictionary<DateTime, decimal> profitLoss,
Dictionary<string, Holding> holdings,
StatisticsResults statisticsResults,
Dictionary<string, string> banner)
{
}
public void SendStatusUpdate(AlgorithmStatus status, string message = "")
{
}
public void SetChartSubscription(string symbol)
{
}
public void RuntimeStatistic(string key, string value)
{
}
public void OrderEvent(OrderEvent newEvent)
{
}
public void Exit()
{
_cancellationTokenSource.Cancel();
}
public void PurgeQueue()
{
Messages.Clear();
}
public void ProcessSynchronousEvents(bool forceProcess = false)
{
}
}
}
| |
namespace IndustrialAutomaton.MaintenanceAstromech
{
using System;
using System.Collections.Generic;
using System.Text;
using VRage.ModAPI;
using VRage.Utils;
using VRageMath;
using Sandbox.ModAPI;
using Sandbox.ModAPI.Interfaces.Terminal;
using SpaceEquipmentLtd.Utils;
[Flags]
public enum SearchModes
{
/// <summary>
/// Search Target blocks only inside connected blocks
/// </summary>
Grids = 0x0001,
/// <summary>
/// Search Target blocks in bounding boy independend of connection
/// </summary>
BoundingBox = 0x0002
}
[Flags]
public enum WorkModes
{
/// <summary>
/// Grind only if nothing to weld
/// </summary>
WeldBeforeGrind = 0x0001,
/// <summary>
/// Weld onyl if nothing to grind
/// </summary>
GrindBeforeWeld = 0x0002,
/// <summary>
/// Grind only if nothing to weld or
/// build waiting for missing items
/// </summary>
GrindIfWeldGetStuck = 0x0004
}
public static class NanobotBuildAndRepairSystemTerminal
{
public static bool CustomControlsInit = false;
private static List<IMyTerminalControl> CustomControls = new List<IMyTerminalControl>();
private static List<IMyTerminalAction> CustomActions = new List<IMyTerminalAction>();
private static IMyTerminalControlButton _EnableDisableButton;
private static IMyTerminalControlButton _PriorityButtonUp;
private static IMyTerminalControlButton _PriorityButtonDown;
private static IMyTerminalControlListbox _PriorityListBox;
/// <summary>
/// Initialize custom control definition
/// </summary>
public static void InitializeControls()
{
lock (CustomControls)
{
if (CustomControlsInit) return;
CustomControlsInit = true;
try
{
// As CustomControlGetter is only called if the Terminal is opened,
// I add also some properties immediately and permanent to support scripting.
// !! As we can't subtype here they will be also available in every Shipwelder but without function !!
if (Mod.Log.ShouldLog(Logging.Level.Event)) Mod.Log.Write(Logging.Level.Event, "InitializeControls");
MyAPIGateway.TerminalControls.CustomControlGetter += CustomControlGetter;
MyAPIGateway.TerminalControls.CustomActionGetter += CustomActionsGetter;
IMyTerminalControlCheckbox checkbox;
IMyTerminalControlCombobox comboBox;
IMyTerminalControlSeparator separateArea;
IMyTerminalControlSlider slider;
// --- AllowBuild CheckBox
if (!NanobotBuildAndRepairSystemMod.Settings.Welder.AllowBuildFixed)
{
checkbox = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, IMyShipWelder>("AllowBuild");
checkbox.Title = MyStringId.GetOrCompute("Build new");
checkbox.Tooltip = MyStringId.GetOrCompute("When checked, the BuildAndRepairSystem will also construct projected blocks.");
checkbox.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.AllowBuild : false;
};
checkbox.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
system.Settings.AllowBuild = y;
checkbox.UpdateVisual();
}
};
CreateCheckBoxAction("AllowBuild", checkbox);
CustomControls.Add(checkbox);
CreateProperty(checkbox);
}
// --- Select search mode
if ((NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedSearchModes & (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedSearchModes - 1)) != 0)
{
comboBox = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCombobox, IMyShipWelder>("Mode");
comboBox.Title = MyStringId.GetOrCompute("Mode");
comboBox.Tooltip = MyStringId.GetOrCompute("Select how the nanobots search and reach their targets");
comboBox.Visible = (block) =>
{
return (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedSearchModes & (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedSearchModes - 1)) != 0;
};
comboBox.ComboBoxContent = (list) =>
{
if (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedSearchModes.HasFlag(SearchModes.Grids))
list.Add(new MyTerminalControlComboBoxItem() { Key = (long)SearchModes.Grids, Value = MyStringId.GetOrCompute("Walk mode") });
if (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedSearchModes.HasFlag(SearchModes.BoundingBox))
list.Add(new MyTerminalControlComboBoxItem() { Key = (long)SearchModes.BoundingBox, Value = MyStringId.GetOrCompute("Fly mode") });
};
comboBox.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system == null) return 0;
else return (long)system.Settings.SearchMode;
};
comboBox.Setter = (block, value) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
if (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedSearchModes.HasFlag((SearchModes)value))
{
system.Settings.SearchMode = (SearchModes)value;
comboBox.UpdateVisual();
}
}
};
CustomControls.Add(comboBox);
CreateProperty(comboBox);
}
// --- Select work mode
if ((NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedWorkModes & (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedWorkModes - 1)) != 0)
{
comboBox = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCombobox, IMyShipWelder>("Work Mode");
comboBox.Title = MyStringId.GetOrCompute("WorkMode");
comboBox.Tooltip = MyStringId.GetOrCompute("Select how the nanobots decide what to do (weld or grind)");
comboBox.Visible = (block) =>
{
return (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedWorkModes & (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedWorkModes - 1)) != 0;
};
comboBox.ComboBoxContent = (list) =>
{
if (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedWorkModes.HasFlag(WorkModes.WeldBeforeGrind))
list.Add(new MyTerminalControlComboBoxItem() { Key = (long)WorkModes.WeldBeforeGrind, Value = MyStringId.GetOrCompute("Weld before grind") });
if (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedWorkModes.HasFlag(WorkModes.GrindBeforeWeld))
list.Add(new MyTerminalControlComboBoxItem() { Key = (long)WorkModes.GrindBeforeWeld, Value = MyStringId.GetOrCompute("Grind before weld") });
if (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedWorkModes.HasFlag(WorkModes.GrindIfWeldGetStuck))
list.Add(new MyTerminalControlComboBoxItem() { Key = (long)WorkModes.GrindIfWeldGetStuck, Value = MyStringId.GetOrCompute("Grind if weld get stuck") });
};
comboBox.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system == null) return 0;
else return (long)system.Settings.WorkMode;
};
comboBox.Setter = (block, value) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
if (NanobotBuildAndRepairSystemMod.Settings.Welder.AllowedWorkModes.HasFlag((WorkModes)value))
{
system.Settings.WorkMode = (WorkModes)value;
comboBox.UpdateVisual();
}
}
};
CustomControls.Add(comboBox);
CreateProperty(comboBox);
}
// --- Set Color that marks blocks as 'ignore'
if (!NanobotBuildAndRepairSystemMod.Settings.Welder.UseIgnoreColorFixed)
{
separateArea = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, IMyShipWelder>("SeparateIgnoreColor");
CustomControls.Add(separateArea);
checkbox = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, IMyShipWelder>("UseIgnoreColor");
checkbox.Title = MyStringId.GetOrCompute("Use Ignore Color");
checkbox.Tooltip = MyStringId.GetOrCompute("When checked, the system will ignore blocks with the color defined further down.");
checkbox.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.UseIgnoreColor : false;
};
checkbox.Setter = (block, value) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
system.Settings.UseIgnoreColor = value;
foreach (var ctrl in CustomControls)
{
if (ctrl.Id.Contains("IgnoreColor")) ctrl.UpdateVisual();
}
}
};
CreateCheckBoxAction("UseIgnoreColor", checkbox);
CustomControls.Add(checkbox);
CreateProperty(checkbox);
Func<IMyTerminalBlock, bool> colorPickerEnabled = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.UseIgnoreColor : false;
};
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("IgnoreColorHue");
slider.Title = MyStringId.GetOrCompute("Hue");
slider.SetLimits(0, 360);
slider.Enabled = colorPickerEnabled;
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.IgnoreColor.X * 360f : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.IgnoreColor;
y = y < 0 ? 0 : y > 360 ? 360 : y;
hsv.X = (float)Math.Round(y) / 360;
system.Settings.IgnoreColor = hsv;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.IgnoreColor;
y.Append(Math.Round(hsv.X * 360f));
}
};
CustomControls.Add(slider);
CreateSliderActions("IgnoreColorHue", slider, 0, 360);
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("IgnoreColorSaturation");
slider.Title = MyStringId.GetOrCompute("Saturation");
slider.SetLimits(-100, 100);
slider.Enabled = colorPickerEnabled;
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.IgnoreColor.Y * 100f : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.IgnoreColor;
y = y < -100 ? -100 : y > 100 ? 100 : y;
hsv.Y = (float)Math.Round(y) / 100f;
system.Settings.IgnoreColor = hsv;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.IgnoreColor;
y.Append(Math.Round(hsv.Y * 100f));
}
};
CustomControls.Add(slider);
CreateSliderActions("IgnoreColorSaturation", slider, -100, 100);
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("IgnoreColorValue");
slider.Title = MyStringId.GetOrCompute("Value");
slider.SetLimits(-100, 100);
slider.Enabled = colorPickerEnabled;
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.IgnoreColor.Z * 100f : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.IgnoreColor;
y = y < -100 ? -100 : y > 100 ? 100 : y;
hsv.Z = (float)Math.Round(y) / 100f;
system.Settings.IgnoreColor = hsv;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.IgnoreColor;
y.Append(Math.Round(hsv.Z * 100f));
}
};
CustomControls.Add(slider);
CreateSliderActions("ColorValue", slider, -100, 100);
var propertyIC = MyAPIGateway.TerminalControls.CreateProperty<Vector3, IMyShipWelder>("BuildAndRepair.IgnoreColor");
propertyIC.SupportsMultipleBlocks = false;
propertyIC.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.IgnoreColor : Vector3.Zero;
};
propertyIC.Setter = (block, value) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
if (value.X < 0f) value.X = 0f;
if (value.X > 1f) value.X = 1f;
if (value.Y < -1f) value.X = -1f;
if (value.Y > 1f) value.X = 1f;
if (value.Z < -1f) value.X = -1f;
if (value.Z > 1f) value.X = 1f;
system.Settings.IgnoreColor = value;
}
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertyIC);
}
// --- Set Color that marks blocks as 'grind'
if (!NanobotBuildAndRepairSystemMod.Settings.Welder.UseGrindColorFixed)
{
separateArea = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, IMyShipWelder>("SeparateGrindColor");
CustomControls.Add(separateArea);
checkbox = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, IMyShipWelder>("UseGrindColor");
checkbox.Title = MyStringId.GetOrCompute("Use Grind Color");
checkbox.Tooltip = MyStringId.GetOrCompute("When checked, the system will grind blocks with the color defined further down.");
checkbox.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.UseGrindColor : false;
};
checkbox.Setter = (block, value) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
system.Settings.UseGrindColor = value;
foreach (var ctrl in CustomControls)
{
if (ctrl.Id.Contains("GrindColor")) ctrl.UpdateVisual();
}
}
};
CreateCheckBoxAction("UseGrindColor", checkbox);
CustomControls.Add(checkbox);
CreateProperty(checkbox);
Func<IMyTerminalBlock, bool> colorPickerEnabled = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.UseGrindColor : false;
};
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("GrindColorHue");
slider.Title = MyStringId.GetOrCompute("Hue");
slider.SetLimits(0, 360);
slider.Enabled = colorPickerEnabled;
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.GrindColor.X * 360f : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.GrindColor;
y = y < 0 ? 0 : y > 360 ? 360 : y;
hsv.X = (float)Math.Round(y) / 360;
system.Settings.GrindColor = hsv;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.GrindColor;
y.Append(Math.Round(hsv.X * 360f));
}
};
CustomControls.Add(slider);
CreateSliderActions("GrindColorHue", slider, 0, 360);
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("GrindColorSaturation");
slider.Title = MyStringId.GetOrCompute("Saturation");
slider.SetLimits(-100, 100);
slider.Enabled = colorPickerEnabled;
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.GrindColor.Y * 100f : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.GrindColor;
y = y < -100 ? -100 : y > 100 ? 100 : y;
hsv.Y = (float)Math.Round(y) / 100f;
system.Settings.GrindColor = hsv;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.GrindColor;
y.Append(Math.Round(hsv.Y * 100f));
}
};
CustomControls.Add(slider);
CreateSliderActions("GrindColorSaturation", slider, -100, 100);
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("GrindColorValue");
slider.Title = MyStringId.GetOrCompute("Value");
slider.SetLimits(-100, 100);
slider.Enabled = colorPickerEnabled;
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.GrindColor.Z * 100f : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.GrindColor;
y = y < -100 ? -100 : y > 100 ? 100 : y;
hsv.Z = (float)Math.Round(y) / 100f;
system.Settings.GrindColor = hsv;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var hsv = system.Settings.GrindColor;
y.Append(Math.Round(hsv.Z * 100f));
}
};
CustomControls.Add(slider);
CreateSliderActions("ColorValue", slider, -100, 100);
var propertyGC = MyAPIGateway.TerminalControls.CreateProperty<Vector3, IMyShipWelder>("BuildAndRepair.GrindColor");
propertyGC.SupportsMultipleBlocks = false;
propertyGC.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.GrindColor : Vector3.Zero;
};
propertyGC.Setter = (block, value) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
if (value.X < 0f) value.X = 0f;
if (value.X > 1f) value.X = 1f;
if (value.Y < -1f) value.X = -1f;
if (value.Y > 1f) value.X = 1f;
if (value.Z < -1f) value.X = -1f;
if (value.Z > 1f) value.X = 1f;
system.Settings.GrindColor = value;
}
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertyGC);
}
// -- Highlight Area
if (!NanobotBuildAndRepairSystemMod.Settings.Welder.ShowAreaFixed || !NanobotBuildAndRepairSystemMod.Settings.Welder.AreaSizeFixed)
{
separateArea = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, IMyShipWelder>("SeparateArea");
CustomControls.Add(separateArea);
Func<IMyTerminalBlock, float> getLimitMin = (block) => NanobotBuildAndRepairSystemBlock.WELDER_RANGE_MIN_IN_M;
Func<IMyTerminalBlock, float> getLimitMax = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.WelderMaximumRange : NanobotBuildAndRepairSystemBlock.WELDER_RANGE_MIN_IN_M;
};
if (!NanobotBuildAndRepairSystemMod.Settings.Welder.ShowAreaFixed)
{
checkbox = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, IMyShipWelder>("ShowArea");
checkbox.Title = MyStringId.GetOrCompute("Show Area");
checkbox.Tooltip = MyStringId.GetOrCompute("When checked, it will show you the area this system covers");
checkbox.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
return system.Settings.ShowArea;
}
return false;
};
checkbox.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
system.Settings.ShowArea = y;
checkbox.UpdateVisual();
}
};
CustomControls.Add(checkbox);
CreateProperty(checkbox);
}
if (!NanobotBuildAndRepairSystemMod.Settings.Welder.AreaSizeFixed)
{
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("AreaWidthLeft");
slider.Title = MyStringId.GetOrCompute("Area Width Left");
slider.SetLimits(getLimitMin, getLimitMax);
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.AreaWidthLeft : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var min = getLimitMin(block);
var max = getLimitMax(block);
y = y < min ? min : y > max ? max : y;
system.Settings.AreaWidthLeft = (int)y;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
y.Append(system.Settings.AreaWidthLeft + " m");
}
};
CustomControls.Add(slider);
CreateSliderActionsArea("AreaWidthLeft", slider);
CreateProperty(slider);
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("AreaWidthRight");
slider.Title = MyStringId.GetOrCompute("Area Width Right");
slider.SetLimits(getLimitMin, getLimitMax);
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.AreaWidthRight : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var min = getLimitMin(block);
var max = getLimitMax(block);
y = y < min ? min : y > max ? max : y;
system.Settings.AreaWidthRight = (int)y;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
y.Append(system.Settings.AreaWidthRight + " m");
}
};
CustomControls.Add(slider);
CreateSliderActionsArea("AreaWidthRight", slider);
CreateProperty(slider);
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("AreaHeightBottom");
slider.Title = MyStringId.GetOrCompute("Area Height Bottom");
slider.SetLimits(getLimitMin, getLimitMax);
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.AreaHeightBottom : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var min = getLimitMin(block);
var max = getLimitMax(block);
y = y < min ? min : y > max ? max : y;
system.Settings.AreaHeightBottom = (int)y;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
y.Append(system.Settings.AreaHeightBottom + " m");
}
};
CustomControls.Add(slider);
CreateSliderActionsArea("AreaHeightBottom", slider);
CreateProperty(slider);
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("AreaHeightTop");
slider.Title = MyStringId.GetOrCompute("Area Height Top");
slider.SetLimits(getLimitMin, getLimitMax);
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.AreaHeightTop : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var min = getLimitMin(block);
var max = getLimitMax(block);
y = y < min ? min : y > max ? max : y;
system.Settings.AreaHeightTop = (int)y;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
y.Append(system.Settings.AreaHeightTop + " m");
}
};
CustomControls.Add(slider);
CreateSliderActionsArea("AreaHeightTop", slider);
CreateProperty(slider);
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("AreaDepthRear");
slider.Title = MyStringId.GetOrCompute("Area Depth Rear");
slider.SetLimits(getLimitMin, getLimitMax);
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.AreaDepthRear : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var min = getLimitMin(block);
var max = getLimitMax(block);
y = y < min ? min : y > max ? max : y;
system.Settings.AreaDepthRear = (int)y;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
y.Append(system.Settings.AreaDepthRear + " m");
}
};
CustomControls.Add(slider);
CreateSliderActionsArea("AreaDepthRear", slider);
CreateProperty(slider);
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("AreaDepthFront");
slider.Title = MyStringId.GetOrCompute("Area Depth Front");
slider.SetLimits(getLimitMin, getLimitMax);
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.AreaDepthFront : 0;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var min = getLimitMin(block);
var max = getLimitMax(block);
y = y < min ? min : y > max ? max : y;
system.Settings.AreaDepthFront = (int)y;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
y.Append(system.Settings.AreaDepthFront + " m");
}
};
CustomControls.Add(slider);
CreateSliderActionsArea("AreaDepthFront", slider);
CreateProperty(slider);
}
}
// -- Priority
if (!NanobotBuildAndRepairSystemMod.Settings.Welder.PriorityFixed)
{
separateArea = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, IMyShipWelder>("SeparatePrio");
CustomControls.Add(separateArea);
var textbox = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlLabel, IMyShipWelder>("Priority");
textbox.Label = MyStringId.GetOrCompute("Build-Repair Priority");
CustomControls.Add(textbox);
var button = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlButton, IMyShipWelder>("EnableDisable");
_EnableDisableButton = button;
button.Title = MyStringId.GetOrCompute("Enable/Disable");
button.Enabled = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.BuildPriority.Selected != null : false;
};
button.Action = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
system.BuildPriority.ToggleEnabled();
system.Settings.BuildPriority = system.BuildPriority.GetEntries();
_PriorityListBox.UpdateVisual();
}
};
CustomControls.Add(button);
button = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlButton, IMyShipWelder>("PriorityUp");
_PriorityButtonUp = button;
button.Title = MyStringId.GetOrCompute("Priority Up");
button.Enabled = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.BuildPriority.Selected != null : false;
};
button.Action = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
system.BuildPriority.MoveSelectedUp();
system.Settings.BuildPriority = system.BuildPriority.GetEntries();
_PriorityListBox.UpdateVisual();
}
};
CustomControls.Add(button);
button = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlButton, IMyShipWelder>("PriorityDown");
_PriorityButtonDown = button;
button.Title = MyStringId.GetOrCompute("Priority Down");
button.Enabled = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.BuildPriority.Selected != null : false;
};
button.Action = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
system.BuildPriority.MoveSelectedDown();
system.Settings.BuildPriority = system.BuildPriority.GetEntries();
_PriorityListBox.UpdateVisual();
}
};
CustomControls.Add(button);
var listbox = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlListbox, IMyShipWelder>("Priority");
_PriorityListBox = listbox;
listbox.Multiselect = false;
listbox.VisibleRowsCount = 15;
listbox.ItemSelected = (block, selected) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
if (selected.Count > 0)
{
system.BuildPriority.Selected = (BlockClass)selected[0].UserData;
}
else system.BuildPriority.Selected = null;
_EnableDisableButton.UpdateVisual();
_PriorityButtonUp.UpdateVisual();
_PriorityButtonDown.UpdateVisual();
}
};
listbox.ListContent = (block, items, selected) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
system.BuildPriority.FillTerminalList(items, selected);
}
};
CustomControls.Add(listbox);
}
// -- Sound enabled
if (!NanobotBuildAndRepairSystemMod.Settings.Welder.SoundVolumeFixed)
{
separateArea = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, IMyShipWelder>("SeparateOther");
CustomControls.Add(separateArea);
slider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyShipWelder>("SoundVolume");
slider.Title = MyStringId.GetOrCompute("Sound Volume");
slider.SetLimits(0f, 100f);
slider.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? 100f * system.Settings.SoundVolume / NanobotBuildAndRepairSystemBlock.WELDER_SOUND_VOLUME : 0f;
};
slider.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
var min = 0;
var max = 100;
y = y < min ? min : y > max ? max : y;
system.Settings.SoundVolume = (float)Math.Round(y * NanobotBuildAndRepairSystemBlock.WELDER_SOUND_VOLUME) / 100f;
slider.UpdateVisual();
}
};
slider.Writer = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
y.Append(Math.Round(100f * system.Settings.SoundVolume / NanobotBuildAndRepairSystemBlock.WELDER_SOUND_VOLUME) + " %");
}
};
CustomControls.Add(slider);
CreateSliderActionsArea("SoundVolume", slider);
CreateProperty(slider);
}
// -- Script Control
if (!NanobotBuildAndRepairSystemMod.Settings.Welder.ScriptControllFixed)
{
separateArea = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, IMyShipWelder>("SeparateScriptControl");
CustomControls.Add(separateArea);
checkbox = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, IMyShipWelder>("ScriptControlled");
checkbox.Title = MyStringId.GetOrCompute("Controlled by Script");
checkbox.Tooltip = MyStringId.GetOrCompute("When checked, the system will not build/repair blocks automatically. Each block has to be picked by calling scripting functions.");
checkbox.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.ScriptControlled : false;
};
checkbox.Setter = (block, y) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
system.Settings.ScriptControlled = y;
checkbox.UpdateVisual();
}
};
CreateCheckBoxAction("ScriptControlled", checkbox);
CustomControls.Add(checkbox);
CreateProperty(checkbox);
//Scripting support for Priority and enabling BlockClasses
var propertyBlockClassList = MyAPIGateway.TerminalControls.CreateProperty<List<string>, IMyShipWelder>("BuildAndRepair.BlockClassList");
propertyBlockClassList.SupportsMultipleBlocks = false;
propertyBlockClassList.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.BuildPriority.GetList() : null;
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertyBlockClassList);
var propertySP = MyAPIGateway.TerminalControls.CreateProperty<Action<int, int>, IMyShipWelder>("BuildAndRepair.SetPriority");
propertySP.SupportsMultipleBlocks = false;
propertySP.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
return system.BuildPriority.SetPriority;
}
return null;
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertySP);
var propertyGP = MyAPIGateway.TerminalControls.CreateProperty<Func<int, int>, IMyShipWelder>("BuildAndRepair.GetPriority");
propertyGP.SupportsMultipleBlocks = false;
propertyGP.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
return system.BuildPriority.GetPriority;
}
return null;
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertyGP);
var propertySE = MyAPIGateway.TerminalControls.CreateProperty<Action<int, bool>, IMyShipWelder>("BuildAndRepair.SetEnabled");
propertySE.SupportsMultipleBlocks = false;
propertySE.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
return system.BuildPriority.SetEnabled;
}
return null;
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertySE);
var propertyGE = MyAPIGateway.TerminalControls.CreateProperty<Func<int, bool>, IMyShipWelder>("BuildAndRepair.GetEnabled");
propertyGE.SupportsMultipleBlocks = false;
propertyGE.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
return system.BuildPriority.GetEnabled;
}
return null;
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertyGE);
var propertyMissingComponentsDict = MyAPIGateway.TerminalControls.CreateProperty<Dictionary<VRage.Game.MyDefinitionId, int>, IMyShipWelder>("BuildAndRepair.MissingComponents");
propertyMissingComponentsDict.SupportsMultipleBlocks = false;
propertyMissingComponentsDict.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.GetMissingComponentsDict() : null;
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertyMissingComponentsDict);
var propertyPossibleWeldTargetsList = MyAPIGateway.TerminalControls.CreateProperty<List<VRage.Game.ModAPI.Ingame.IMySlimBlock>, IMyShipWelder>("BuildAndRepair.PossibleTargets");
propertyPossibleWeldTargetsList.SupportsMultipleBlocks = false;
propertyPossibleWeldTargetsList.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.GetPossibleWeldTargetsList() : null;
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertyPossibleWeldTargetsList);
var propertyCPT = MyAPIGateway.TerminalControls.CreateProperty<VRage.Game.ModAPI.Ingame.IMySlimBlock, IMyShipWelder>("BuildAndRepair.CurrentPickedTarget");
propertyCPT.SupportsMultipleBlocks = true;
propertyCPT.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.Settings.CurrentPickedWeldingBlock : null;
};
propertyCPT.Setter = (block, value) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
if (system != null)
{
system.Settings.CurrentPickedWeldingBlock = value;
}
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertyCPT);
var propertyCT = MyAPIGateway.TerminalControls.CreateProperty<VRage.Game.ModAPI.Ingame.IMySlimBlock, IMyShipWelder>("BuildAndRepair.CurrentTarget");
propertyCT.SupportsMultipleBlocks = false;
propertyCT.Getter = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
return system != null ? system.State.CurrentWeldingBlock : null;
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertyCT);
//Publish functions to scripting
var propertyPEQ = MyAPIGateway.TerminalControls.CreateProperty<Func<IEnumerable<long>, VRage.Game.MyDefinitionId, int, int>, IMyShipWelder>("BuildAndRepair.ProductionBlock.EnsureQueued");
propertyPEQ.SupportsMultipleBlocks = false;
propertyPEQ.Getter = (block) =>
{
return UtilsProductionBlock.EnsureQueued;
};
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(propertyPEQ);
}
}
catch (Exception ex)
{
Mod.Log.Write(Logging.Level.Error, "BuildAndRepairSystemBlock {0}: InitializeControls exception: {1}", ex);
}
}
}
/// <summary>
///
/// </summary>
private static void CreateCheckBoxAction(string name, IMyTerminalControlCheckbox checkbox)
{
var action = MyAPIGateway.TerminalControls.CreateAction<IMyShipWelder>(string.Format("{0}OnOff", name));
action.Name = new StringBuilder(string.Format("{0} On/Off", name));
action.Icon = @"Textures\GUI\Icons\Actions\Toggle.dds";
action.Enabled = (block) => true;
action.Action = (block) =>
{
checkbox.Setter(block, !checkbox.Getter(block));
};
CustomActions.Add(action);
}
/// <summary>
///
/// </summary>
private static void CreateSliderActions(string sliderName, IMyTerminalControlSlider slider, int minValue, int maxValue)
{
var action = MyAPIGateway.TerminalControls.CreateAction<IMyShipWelder>(string.Format("{0}_Increase", sliderName));
action.Name = new StringBuilder(string.Format("{0} Increase", sliderName));
action.Icon = @"Textures\GUI\Icons\Actions\Increase.dds";
action.Enabled = (block) => true;
action.Action = (block) =>
{
var val = slider.Getter(block);
if (val < maxValue)
slider.Setter(block, val + 1);
};
CustomActions.Add(action);
action = MyAPIGateway.TerminalControls.CreateAction<IMyShipWelder>(string.Format("{0}_Decrease", sliderName));
action.Name = new StringBuilder(string.Format("{0} Decrease", sliderName));
action.Icon = @"Textures\GUI\Icons\Actions\Decrease.dds";
action.Enabled = (block) => true;
action.Action = (block) =>
{
var val = slider.Getter(block);
if (val > minValue)
slider.Setter(block, val - 1);
};
CustomActions.Add(action);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="control"></param>
private static void CreateProperty<T>(IMyTerminalValueControl<T> control)
{
var property = MyAPIGateway.TerminalControls.CreateProperty<T, IMyShipWelder>("BuildAndRepair." + control.Id);
property.SupportsMultipleBlocks = false;
property.Getter = control.Getter;
property.Setter = control.Setter;
MyAPIGateway.TerminalControls.AddControl<IMyShipWelder>(property);
}
/// <summary>
///
/// </summary>
private static void CreateSliderActionsArea(string sliderName, IMyTerminalControlSlider slider)
{
var action = MyAPIGateway.TerminalControls.CreateAction<IMyShipWelder>(string.Format("{0}_Increase", sliderName));
action.Name = new StringBuilder(string.Format("{0} Increase", sliderName));
action.Icon = @"Textures\GUI\Icons\Actions\Increase.dds";
action.Enabled = (block) => true;
action.Action = (block) =>
{
var system = block.GameLogic.GetAs<NanobotBuildAndRepairSystemBlock>();
var max = system != null ? system.WelderMaximumRange : NanobotBuildAndRepairSystemBlock.WELDER_RANGE_MIN_IN_M;
var val = slider.Getter(block);
if (val < max)
slider.Setter(block, val + 1);
};
CustomActions.Add(action);
action = MyAPIGateway.TerminalControls.CreateAction<IMyShipWelder>(string.Format("{0}_Decrease", sliderName));
action.Name = new StringBuilder(string.Format("{0} Decrease", sliderName));
action.Icon = @"Textures\GUI\Icons\Actions\Decrease.dds";
action.Enabled = (block) => true;
action.Action = (block) =>
{
var min = NanobotBuildAndRepairSystemBlock.WELDER_RANGE_MIN_IN_M;
var val = slider.Getter(block);
if (val > min)
slider.Setter(block, val - 1);
};
CustomActions.Add(action);
}
/// <summary>
/// Callback to add custom controls
/// </summary>
private static void CustomControlGetter(IMyTerminalBlock block, List<IMyTerminalControl> controls)
{
if (block.BlockDefinition.SubtypeName.Contains("Big_Astromech_Maintenance") || block.BlockDefinition.SubtypeName.Contains("Small_Astromech_Maintenance")) {
foreach (var item in CustomControls)
controls.Add(item);
}
}
/// <summary>
/// Callback to add custom actions
/// </summary>
private static void CustomActionsGetter(IMyTerminalBlock block, List<IMyTerminalAction> actions)
{
if (block.BlockDefinition.SubtypeName.Contains("Big_Astromech_Maintenance") || block.BlockDefinition.SubtypeName.Contains("Small_Astromech_Maintenance")) {
foreach (var item in CustomActions)
actions.Add(item);
}
}
}
}
| |
using System;
using System.Diagnostics;
using BTDB.KVDBLayer;
using BTDB.ODBLayer;
namespace ODbDump.Visitor
{
class ToConsoleSizeVisitor : IODBVisitor
{
long _currentMemorySize;
long _currentOnDiskSize;
string? _currentRelation;
string? _currentSingleton;
bool _headerWritten;
readonly Stopwatch _stopWatch = new Stopwatch();
const int KeyOverhead = 20;
public void MarkCurrentKeyAsUsed(IKeyValueDBTransaction tr)
{
var (memory, disk) = tr.GetStorageSizeOfCurrentKey();
_currentMemorySize += memory + KeyOverhead;
_currentOnDiskSize += disk;
}
void Flush()
{
if (!_headerWritten)
{
Console.WriteLine("name,memory,disk,type,iteration(s)");
_headerWritten = true;
}
else
{
_stopWatch.Stop();
}
var elapsed = _stopWatch.Elapsed.TotalSeconds;
if (!string.IsNullOrEmpty(_currentRelation))
{
Console.WriteLine(
$"{_currentRelation},{_currentMemorySize},{_currentOnDiskSize},relation,{elapsed:F2}");
_currentRelation = null;
}
else if (!string.IsNullOrEmpty(_currentSingleton))
{
Console.WriteLine(
$"{_currentSingleton},{_currentMemorySize},{_currentOnDiskSize},singleton,{elapsed:F2}");
_currentSingleton = null;
}
_currentMemorySize = 0;
_currentOnDiskSize = 0;
_stopWatch.Restart();
}
public bool VisitSingleton(uint tableId, string? tableName, ulong oid)
{
Flush();
_currentSingleton = tableName;
return true;
}
public bool StartObject(ulong oid, uint tableId, string tableName, uint version)
{
return true;
}
public bool StartField(string name)
{
return true;
}
public bool NeedScalarAsObject()
{
return false;
}
public void ScalarAsObject(object content)
{
}
public bool NeedScalarAsText()
{
return false;
}
public void ScalarAsText(string content)
{
}
public void OidReference(ulong oid)
{
}
public bool StartInlineObject(uint tableId, string tableName, uint version)
{
return true;
}
public void EndInlineObject()
{
}
public bool StartList()
{
return true;
}
public bool StartItem()
{
return true;
}
public void EndItem()
{
}
public void EndList()
{
}
public bool StartDictionary()
{
return true;
}
public bool StartDictKey()
{
return false;
}
public void EndDictKey()
{
}
public bool StartDictValue()
{
return true;
}
public void EndDictValue()
{
}
public void EndDictionary()
{
}
public bool StartSet()
{
return true;
}
public bool StartSetKey()
{
return true;
}
public void EndSetKey()
{
}
public void EndSet()
{
}
public void EndField()
{
}
public void EndObject()
{
}
public bool StartRelation(ODBIteratorRelationInfo relationInfo)
{
Flush();
_currentRelation = relationInfo.Name;
return true;
}
public bool StartRelationKey()
{
return false;
}
public void EndRelationKey()
{
}
public bool StartRelationValue()
{
return true;
}
public void EndRelationValue()
{
}
public void EndRelation()
{
Flush();
}
public void InlineBackRef(int iid)
{
}
public void InlineRef(int iid)
{
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2014 lambdalice
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using CoreTweet.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CoreTweet.Streaming
{
/// <summary>
/// Disconnect code.
/// </summary>
public enum DisconnectCode
{
Shutdown,
DuplicateStream,
ControlRequest,
Stall,
Normal,
TokenRevoked,
AdminLogout,
Reserved,
MaxMessageLimit,
StreamException,
BrokerStall,
ShedLoad
}
/// <summary>
/// Event code.
/// </summary>
public enum EventCode
{
Block,
Unblock,
Favorite,
Unfavorite,
Follow,
Unfollow,
ListCreated,
ListDestroyed,
ListUpdated,
ListMemberAdded,
ListMemberRemoved,
ListUserSubscribed,
ListUserUnsubscribed,
UserUpdate
}
/// <summary>
/// Message type.
/// </summary>
public enum MessageType
{
Delete,
ScrubGeo,
StatusWithheld,
UserWithheld,
Disconnect,
Warning,
Event,
Envelopes,
Create,
Friends,
Limit,
Control,
RawJson
}
/// <summary>
/// Base class of streaming messages.
/// </summary>
public abstract class StreamingMessage : CoreBase
{
/// <summary>
/// Gets the type of this message.
/// </summary>
/// <value>The type.</value>
public MessageType Type { get { return GetMessageType(); } }
/// <summary>
/// Gets the message type
/// </summary>
internal abstract MessageType GetMessageType();
/// <summary>
/// Parse the specified json
/// </summary>
internal static StreamingMessage Parse(TokensBase tokens, string x)
{
var j = JObject.Parse(x);
try
{
if(j["text"] != null)
return StatusMessage.Parse(tokens, j);
else if(j["friends"] != null)
return CoreBase.Convert<FriendsMessage>(tokens, x);
else if(j["event"] != null)
return EventMessage.Parse(tokens, j);
else if(j["for_user"] != null)
return EnvelopesMessage.Parse(tokens, j);
else if(j["control"] != null)
return CoreBase.Convert<ControlMessage>(tokens, x);
else
return ExtractRoot(tokens, j);
}
catch(ParsingException)
{
throw;
}
catch(Exception e)
{
throw new ParsingException("on streaming, cannot parse the json", j.ToString(Formatting.Indented), e);
}
}
/// <summary>
/// Extracts the root to parse
/// </summary>
static StreamingMessage ExtractRoot(TokensBase tokens, JObject jo)
{
JToken jt;
if(jo.TryGetValue("disconnect", out jt))
return jt.ToObject<DisconnectMessage>();
else if(jo.TryGetValue("warning", out jt))
return jt.ToObject<WarningMessage>();
else if(jo.TryGetValue("control", out jt))
return jt.ToObject<ControlMessage>();
else if(jo.TryGetValue("delete", out jt))
{
var id = jt.ToObject<IDMessage>();
id.messageType = MessageType.Delete;
return id;
}
else if(jo.TryGetValue("scrub_geo", out jt))
{
var id = jt.ToObject<IDMessage>();
id.messageType = MessageType.ScrubGeo;
return id;
}
else if(jo.TryGetValue("limit", out jt))
{
return jt.ToObject<LimitMessage>();
}
else if(jo.TryGetValue("status_withheld", out jt))
{
var id = jt.ToObject<IDMessage>();
id.messageType = MessageType.StatusWithheld;
return id;
}
else if(jo.TryGetValue("user_withheld", out jt))
{
var id = jt.ToObject<IDMessage>();
id.messageType = MessageType.UserWithheld;
return id;
}
else
throw new ParsingException("on streaming, cannot parse the json", jo.ToString(Formatting.Indented), null);
}
}
/// <summary>
/// Status message.
/// </summary>
public class StatusMessage : StreamingMessage
{
/// <summary>
/// The status.
/// </summary>
/// <value>The status.</value>
public Status Status { get; set; }
internal override MessageType GetMessageType()
{
return MessageType.Create;
}
internal static StatusMessage Parse(TokensBase t, JObject j)
{
return new StatusMessage()
{
Status = j.ToObject<Status>()
};
}
}
/// <summary>
/// Message contains ids of friends.
/// </summary>
[JsonObject]
public class FriendsMessage : StreamingMessage,IEnumerable<long>
{
/// <summary>
/// The ids of friends.
/// </summary>
/// <value>The friends.</value>
[JsonProperty("friends")]
public long[] Friends { get; set; }
internal override MessageType GetMessageType()
{
return MessageType.Friends;
}
/// <summary>
/// IEnumerable\<T\> implementation
/// </summary>
public IEnumerator<long> GetEnumerator()
{
return ((IEnumerable<long>)Friends).GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return Friends.GetEnumerator();
}
}
/// <summary>
/// Message that notices limit.
/// </summary>
public class LimitMessage : StreamingMessage
{
[JsonProperty("track")]
public int Track { get; set; }
internal override MessageType GetMessageType()
{
return MessageType.Limit;
}
}
/// <summary>
/// Message contains ids.
/// </summary>
public class IDMessage : StreamingMessage
{
/// <summary>
/// ID.
/// </summary>
/// <value>The I.</value>
[JsonProperty("id")]
public long ID { get; set; }
/// <summary>
/// User's ID.
/// </summary>
/// <value>The user I.</value>
[JsonProperty("user_id")]
public long UserID { get; set; }
/// <summary>
/// Status ID.
/// </summary>
/// <value>Up to status I.</value>
[JsonProperty("up_to_status_id")]
public long? UpToStatusID { get; set; }
/// <summary>
/// Withhelds.
/// </summary>
/// <value>The withheld in countries.</value>
[JsonProperty("withheld_in_countries")]
public string[] WithheldInCountries { get; set; }
internal MessageType messageType { get; set; }
internal override MessageType GetMessageType()
{
return messageType;
}
}
/// <summary>
/// Message published when Twitter disconnects the stream.
/// </summary>
public class DisconnectMessage : StreamingMessage
{
/// <summary>
/// The disconnect code.
/// </summary>
/// <value>The code.</value>
[JsonProperty("code")]
public DisconnectCode Code { get; set; }
/// <summary>
/// The screen name of current stream.
/// </summary>
/// <value>The name of the stream.</value>
[JsonProperty("stream_name")]
public string StreamName { get; set; }
/// <summary>
/// Human readable message for the reason.
/// </summary>
/// <value>The reason.</value>
[JsonProperty("reason")]
public string Reason { get; set; }
internal override MessageType GetMessageType()
{
return MessageType.Disconnect;
}
}
/// <summary>
/// Warning message.
/// </summary>
public class WarningMessage : StreamingMessage
{
/// <summary>
/// Warning code.
/// </summary>
/// <value>The code.</value>
[JsonProperty("code")]
public string Code { get; set; }
/// <summary>
/// Warning message.
/// </summary>
/// <value>The message.</value>
[JsonProperty("message")]
public string Message { get; set; }
/// <summary>
/// Percentage of the stall messages
/// </summary>
/// <value>The percent full.</value>
[JsonProperty("percent_full")]
public int? PercentFull { get; set; }
/// <summary>
/// Target user ID.
/// </summary>
/// <value>The user ID.</value>
[JsonProperty("user_id")]
public long? UserID { get; set; }
internal override MessageType GetMessageType()
{
return MessageType.Warning;
}
}
/// <summary>
/// Event target type.
/// </summary>
public enum EventTargetType
{
List,
Status,
Null
}
/// <summary>
/// Event message.
/// </summary>
public class EventMessage : StreamingMessage
{
/// <summary>
/// The target.
/// </summary>
public User Target { get; set; }
/// <summary>
/// The source.
/// </summary>
public User Source { get; set; }
/// <summary>
/// The event code.
/// </summary>
public EventCode Event { get; set; }
/// <summary>
/// The type of target,
/// </summary>
public EventTargetType TargetType { get; set; }
/// <summary>
/// The target status.
/// </summary>
public Status TargetStatus { get; set; }
/// <summary>
/// The target list.
/// </summary>
public CoreTweet.List TargetList { get; set; }
/// <summary>
/// When this event happened.
/// </summary>
public DateTimeOffset CreatedAt { get; set; }
internal override MessageType GetMessageType()
{
return MessageType.Event;
}
internal static EventMessage Parse(TokensBase t, JObject j)
{
var e = new EventMessage();
e.Target = j["target"].ToObject<User>();
e.Source = j["source"].ToObject<User>();
e.Event = (EventCode)Enum.Parse(typeof(EventCode), ((string)j["event"]).Replace("_", ""), true);
e.CreatedAt = DateTimeOffset.ParseExact((string)j["created_at"], "ddd MMM dd HH:mm:ss K yyyy",
System.Globalization.DateTimeFormatInfo.InvariantInfo,
System.Globalization.DateTimeStyles.AllowWhiteSpaces);
var eventstr = (string)j["event"];
e.TargetType = eventstr.Contains("List") ? EventTargetType.List :
eventstr.Contains("favorite") ? EventTargetType.Status : EventTargetType.Null;
switch(e.TargetType)
{
case EventTargetType.Status:
e.TargetStatus = j["target_object"].ToObject<Status>();
break;
case EventTargetType.List:
e.TargetList = j["target_object"].ToObject<CoreTweet.List>();
break;
default:
break;
}
return e;
}
}
/// <summary>
/// Envelopes message.
/// </summary>
public class EnvelopesMessage : StreamingMessage
{
/// <summary>
/// User ID.
/// </summary>
public long ForUser { get; set; }
/// <summary>
/// The message.
/// </summary>
public StreamingMessage Message { get; set; }
internal override MessageType GetMessageType()
{
return MessageType.Envelopes;
}
internal static EnvelopesMessage Parse(TokensBase t, JObject j)
{
return new EnvelopesMessage()
{
ForUser = (long)j["for_user"],
Message = StreamingMessage.Parse(t, j["message"].ToString(Formatting.None))
};
}
}
/// <summary>
/// Control message.
/// </summary>
public class ControlMessage : StreamingMessage
{
/// <summary>
/// The URI.
/// </summary>
/// <value>The control URI.</value>
[JsonProperty("control_uri")]
public string ControlUri { get; set; }
internal override MessageType GetMessageType()
{
return MessageType.Control;
}
}
/// <summary>
/// Raw JSON message.
/// </summary>
public class RawJsonMessage : StreamingMessage
{
/// <summary>
/// The raw JSON.
/// </summary>
public string Json { get; set; }
internal static RawJsonMessage Create(TokensBase t, string json)
{
return new RawJsonMessage
{
Json = json
};
}
internal override MessageType GetMessageType()
{
return MessageType.RawJson;
}
}
}
| |
using System.Collections.Generic;
using UnityEngine;
public class StateGame : ExaState {
public StateGame(): base(GAME) {
//Initialize
m_ScoreCounterTimers = new List<float>();
m_HealthCounterTimers = new List<float>();
m_HealthChanges = new List<float>();
m_EnemyShootTimer = new List<float>();
m_Started = false;
m_ConsoleLog = new string[CONSOLE_MAX_LINE];
for(int i=0;i<CONSOLE_MAX_LINE;i++) m_ConsoleLog[i] = "";
//Create backgrounds
m_Background11 = new FSprite("clouds") { x = Constants.UNITY_CENTER_X, y = Constants.UNITY_CENTER_Y };
m_Background12 = new FSprite("clouds") { x = Constants.UNITY_CANVAS_RIGHT + (Constants.UNITY_CANVAS_WIDTH / 2f) - 1, y = Constants.UNITY_CENTER_Y };
m_Background22 = new FSprite("hills") { x = Constants.UNITY_CANVAS_RIGHT + (Constants.UNITY_CANVAS_WIDTH / 2f) - 1 };
m_Background21 = new FSprite("hills") { x = Constants.UNITY_CENTER_X };
m_Background21.y = Constants.UNITY_CANVAS_BOTTOM + m_Background21.textureRect.height * 0.5f;
m_Background22.y = Constants.UNITY_CANVAS_BOTTOM + m_Background22.textureRect.height * 0.5f;
AddChild(m_Background11);
AddChild(m_Background12);
AddChild(m_Background21);
AddChild(m_Background22);
//Create components
m_Exa = new Exa();
m_Enemies = new FContainer();
m_EnemyBullets = new FContainer();
m_PlayerBullets = new FContainer();
AddChild(m_Enemies);
AddChild(m_Exa);
AddChild(m_PlayerBullets);
AddChild(m_EnemyBullets);
//Create interface
m_ScoreCounter = new FLabel("font", "") { isVisible = false };
m_ErrorCounter = new FLabel("font", "") { isVisible = false };
m_ScoreOverlay = new FSprite("target") { isVisible = false };
m_HealthOverlay = new FSprite("target") { isVisible = false };
m_HealthGauge = new FSprite("gauge") { isVisible = false };
m_HealthBar = new FSprite("rect") { isVisible = false, color = new Color(0, 1, 0, 1) };
//Add
AddChild(m_HealthBar);
AddChild(m_HealthGauge);
//AddChild(m_ErrorCounter);
AddChild(m_ScoreCounter);
AddChild(m_ScoreOverlay);
AddChild(m_HealthOverlay);
//Create unity canvas
m_Unity = new FSprite("unity") { x = Futile.screen.halfWidth, y = Futile.screen.halfHeight };
m_Console = new FLabel[CONSOLE_MAX_LINE];
for(int i=0;i<CONSOLE_MAX_LINE;i++) m_Console[i] = new FLabel("font_console", "") { isVisible = false };
//Add
AddChild(m_Unity);
foreach(FLabel line in m_Console) AddChild(line);
}
public void start() {
//Started
m_Started = true;
//Show interface
m_HealthBar.isVisible = true;
m_HealthGauge.isVisible = true;
m_ErrorCounter.isVisible = true;
m_ScoreCounter.isVisible = true;
for(int i=0;i<CONSOLE_MAX_LINE;i++) m_Console[i].isVisible = true;
//Start
setup();
}
public void setup() {
//Initialize
m_Score = 0;
m_Error = 0;
m_Health = HEALTH_MAX;
m_Gameover = false;
m_EnemyTimer = 2.0f;
m_PlayerBulletTimer = 0;
m_PlayerBulletBorder = Constants.UNITY_CANVAS_RIGHT - 38;
m_PlayerBullets.RemoveAllChildren();
m_EnemyBullets.RemoveAllChildren();
m_Enemies.RemoveAllChildren();
m_HealthCounterTimers.Clear();
m_ScoreCounterTimers.Clear();
m_HealthChanges.Clear();
//Reset background
m_Background11.x = Constants.UNITY_CENTER_X;
m_Background12.x = Constants.UNITY_CANVAS_RIGHT + (Constants.UNITY_CANVAS_WIDTH / 2f) - 1;
m_Background22.x = Constants.UNITY_CANVAS_RIGHT + (Constants.UNITY_CANVAS_WIDTH / 2f) - 1;
m_Background21.x = Constants.UNITY_CENTER_X;
//Prepare interface
m_Error--;
incrementError(false);
increaseScore(0);
changeHealth();
//Log
logConsole("[LOG] StateManager: StateGame initialized");
}
public override void onUpdate(FTouch[] touches) {
//If not started
if (!m_Started) StateManager.instance.goTo(TITLE, new object[] { this }, false);
else if (m_Gameover) StateManager.instance.goTo(RESULT, new object[] { this, m_Health }, false);
else {
//Update
m_Exa.update();
processEnemies();
processBackground();
//For each enemy
Drawable Enemy = null;
for (int i = 0; i < m_Enemies.GetChildCount() && Enemy == null; i++) {
//Get enemy
Enemy = m_Enemies.GetChildAt(i) as Drawable;
if (Enemy != null && Enemy.x < m_Exa.x) Enemy = null;
}
//IF closest enemy exist
if (Enemy != null) {
//Move player
if (Enemy.y < m_Exa.y - 8) m_Exa.y -= 8;
else if (Enemy.y > m_Exa.y + 8) m_Exa.y += 8;
else m_Exa.y = Enemy.y;
}
//Process bullets
Enemy e = (Enemy)Enemy;
processPlayerBullets(e);
processEnemyBullets();
//Check input
processCoinCounter(touches);
processHealthCounter(touches);
checkTouchedObjects(touches);
}
}
protected void addScoreChange(float duration) {
//Add
m_ScoreCounterTimers.Add(duration);
m_ScoreOverlay.isVisible = true;
//Log
logConsole("[LOG] Engine: Game need to change score in " + duration + " Seconds");
}
protected void addHealthChange(float change, float duration) {
//Add
m_HealthChanges.Add(change);
m_HealthCounterTimers.Add(duration);
//Show
m_HealthOverlay.isVisible = true;
//Log
logConsole("[LOG] Engine: Game need to change health in " + duration + " Seconds");
}
protected void increaseScore(int amount) {
//Add
m_Score += amount;
if (m_ScoreCounterTimers.Count > 0) m_ScoreCounterTimers.RemoveAt(0);
//Refresh
m_ScoreCounter.text = "Score: " + m_Score;
m_ScoreCounter.x = Constants.UNITY_CANVAS_RIGHT - 12 - (m_ScoreCounter.textRect.width * 0.5f);
m_ScoreCounter.y = Constants.UNITY_CANVAS_TOP - 12 - (m_ScoreCounter.textRect.height * 0.5f);
//Refresh overlay
m_ScoreOverlay.x = m_ScoreCounter.x;
m_ScoreOverlay.y = m_ScoreCounter.y;
}
protected void changeHealth() {
//If there's change
if (m_HealthChanges.Count > 0) {
//Change health
m_Health += m_HealthChanges[0];
}
m_HealthCounterTimers.Clear();
m_HealthChanges.Clear();
//Refresh
m_HealthBar.height = 34;
m_HealthBar.width = m_Health / HEALTH_MAX * 264;
m_HealthGauge.x = Constants.UNITY_CANVAS_LEFT + 12 + (m_HealthGauge.textureRect.width * 0.5f);
m_HealthGauge.y = Constants.UNITY_CANVAS_TOP - 12 - (m_HealthGauge.textureRect.height * 0.5f);
m_HealthBar.x = Constants.UNITY_CANVAS_LEFT + 12 + 65 + (m_HealthBar.width * 0.5f);
m_HealthBar.y = Constants.UNITY_CANVAS_TOP - 12 - 31 - (m_HealthBar.height * 0.5f);
//Refresh overlay
m_HealthOverlay.x = m_HealthBar.x + (m_HealthBar.width * 0.5f);
m_HealthOverlay.y = m_HealthBar.y;
//DOne
if (m_Health <= 0) m_Gameover = true;
}
protected void incrementError() { incrementError(true); }
protected void incrementError(bool sfx) {
//Increase
m_Error++;
if (m_Error >= ERROR_MAX) {
//Gameover
m_Gameover = true;
FSoundManager.PlaySound("gameover");
//Log
logConsole("[ERROR] Engine: Too many errors. Game crashed");
}
//Refresh
m_ErrorCounter.text = "Error: " + m_Error;
m_ErrorCounter.x = Constants.UNITY_CANVAS_LEFT + 12 + (m_ErrorCounter.textRect.width * 0.5f);
m_ErrorCounter.y = Constants.UNITY_CANVAS_BOTTOM + 4 + (m_ErrorCounter.textRect.height * 0.5f);
//SFX
if (sfx && !m_Gameover) FSoundManager.PlaySound("error");
}
protected void logConsole(string log) {
string first = m_ConsoleLog[0];
m_ConsoleLog[0] = log;
for(int i=1;i<CONSOLE_MAX_LINE;i++) {
string second = m_ConsoleLog[i];
m_ConsoleLog[i] = first;
first = second;
}
for(int i=0;i<CONSOLE_MAX_LINE;i++) {
m_Console[i].text = m_ConsoleLog[i];
m_Console[i].x = 65 + (m_Console[i].textRect.width * 0.5f);
m_Console[i].y = 67.5f - (CONSOLE_LINE_OFFSET * i) + (m_Console[i].textRect.height * 0.5f);
}
}
/*protected void processCoins(float offset) {
//Initialize
List<FNode> Deads = new List<FNode>();
//For each child in the container
for (int i = 0; i < m_Coins.GetChildCount(); i++) {
//Get platform
Coin ACoin = m_Coins.GetChildAt(i) as Coin;
if (ACoin != null) {
//Move
ACoin.x -= offset;
//Coin dead, assumed player not clicking
float CoinRight = ACoin.x + (ACoin.getWidth() / 2);
if (CoinRight < 0) {
Deads.Add(ACoin);
incrementError();
}
//Update duration
bool ShouldTouch = ACoin.ShouldBeTouched();
ACoin.UpdateDuration(Time.deltaTime);
if (!ShouldTouch && ACoin.ShouldBeTouched()) m_CoinCounterTime = 2.0f;
}
}
//Remove dead coins
for (int i = 0; i < Deads.Count; i++) m_Coins.RemoveChild(Deads[i]);
//Spawn
m_CurrentCoinTime -= Time.deltaTime;
if (m_CurrentCoinTime <= 0f) {
//Create
float X = Futile.screen.width + (Random.Range(0, 6) * 40);
float Y = Futile.screen.height / 16.0f * (float)(Random.Range(6, 14));
Coin NewCoin = new Coin(X, Y, 2f);
//Add
m_Coins.AddChild(NewCoin);
//Reset
m_CurrentCoinTime = m_SpawnCoinTime;
}
}
protected void checkTouchedCoins(FTouch[] touches) {
//Initialize
List<FNode> Deads = new List<FNode>();
//For each child in the container
for (int i = 0; i < m_Coins.GetChildCount(); i++) {
//Get coins
Coin ACoin = m_Coins.GetChildAt(i) as Coin;
if (ACoin != null) {
foreach(FTouch touch in touches) {
if (ACoin.IsTouched(touch.position)) {
Deads.Add(ACoin);
if (!ACoin.ShouldBeTouched()) incrementError();
break;
}
}
}
}
//Remove dead coins
for (int i = 0; i < Deads.Count; i++) m_Coins.RemoveChild(Deads[i]);
}*/
protected void processBackground() {
//Move backgrounds
m_Background11.x -= m_Exa.getOffset() * 0.2f;
m_Background12.x -= m_Exa.getOffset() * 0.2f;
m_Background21.x -= m_Exa.getOffset() * 0.5f;
m_Background22.x -= m_Exa.getOffset() * 0.5f;
//Loop
if (m_Background11.x <= Constants.UNITY_CANVAS_LEFT - (Constants.UNITY_CANVAS_WIDTH / 2f)) {
m_Background11.x += Constants.UNITY_CANVAS_WIDTH;
m_Background12.x += Constants.UNITY_CANVAS_WIDTH - 1;
//Log
logConsole("[LOG] ParallaxBackground: Layer 1 is now looping");
}
if (m_Background21.x <= Constants.UNITY_CANVAS_LEFT - (Constants.UNITY_CANVAS_WIDTH / 2f)) {
m_Background21.x += Constants.UNITY_CANVAS_WIDTH;
m_Background22.x += Constants.UNITY_CANVAS_WIDTH - 1;
//Log
logConsole("[LOG] ParallaxBackground: Layer 2 is now looping");
}
}
protected void processCoinCounter(FTouch[] touches) {
//While not all timer
int Index = 0;
while (Index < m_ScoreCounterTimers.Count) {
//Manage time
m_ScoreCounterTimers[Index] -= Time.deltaTime;
if (m_ScoreCounterTimers[Index] > 0) Index++;
else {
//Remove
if (m_ScoreOverlay.isVisible) {
//Log
logConsole("[ERROR] UIHandler: NullException. Couldn't get score data " + (m_Error + 1) + "/" + ERROR_MAX);
incrementError();
}
m_ScoreCounterTimers.RemoveAt(Index);
}
}
//Check score overlay
m_ScoreOverlay.isVisible = m_ScoreCounterTimers.Count > 0;
if (m_ScoreOverlay.isVisible) {
//For each touch
bool Touched = false;
for (int i = 0; i < touches.Length && !Touched; i++) {
//If done
if (touches[i].phase == TouchPhase.Ended) {
//Check position
float TouchX = touches[i].position.x;
float TouchY = touches[i].position.y;
float HalfWidth = m_ScoreOverlay.textureRect.width * 0.5f;
float HalfHeight = m_ScoreOverlay.textureRect.height * 0.5f;
if (TouchX >= m_ScoreCounter.x - HalfWidth && TouchX <= m_ScoreCounter.x + HalfWidth && TouchY >= m_ScoreCounter.y - HalfHeight && TouchY <= m_ScoreCounter.y + HalfHeight) Touched = true;
}
}
//If touched
if (Touched) {
//Do stuff
increaseScore(500);
FSoundManager.PlaySound("success");
//Log
logConsole("[LOG] UIHandler: Score successfully increased");
}
}
}
protected void processHealthCounter(FTouch[] touches) {
//While not all timer
int Index = 0;
while (Index < m_HealthCounterTimers.Count) {
//Manage time
m_HealthCounterTimers[Index] -= Time.deltaTime;
if (m_HealthCounterTimers[Index] > 0) Index++;
else {
//Remove
if (m_HealthOverlay.isVisible) {
//Log
logConsole("[ERROR] UIHandler: NullException. Couldn't get health data " + (m_Error + 1) + "/" + ERROR_MAX);
incrementError();
}
m_HealthCounterTimers.RemoveAt(Index);
m_HealthChanges.RemoveAt(Index);
}
}
//Check health overlay
m_HealthOverlay.isVisible = m_HealthCounterTimers.Count > 0;
if (m_HealthOverlay.isVisible) {
//For each touch
bool Touched = false;
for (int i = 0; i < touches.Length && !Touched; i++) {
//If done
if (touches[i].phase == TouchPhase.Ended) {
//Check position
float TouchX = touches[i].position.x;
float TouchY = touches[i].position.y;
float HalfWidth = m_HealthOverlay.textureRect.width * 0.5f;
float HalfHeight = m_HealthOverlay.textureRect.height * 0.5f;
if (TouchX >= m_HealthOverlay.x - HalfWidth && TouchX <= m_HealthOverlay.x + HalfWidth && TouchY >= m_HealthOverlay.y - HalfHeight && TouchY <= m_HealthOverlay.y + HalfHeight) Touched = true;
}
}
//If touched
if (Touched) {
//Change stuff
changeHealth();
FSoundManager.PlaySound("success");
//Log
logConsole("[LOG] UIHandler: Health successfully decreased");
}
}
}
protected void checkTouchedObjects(FTouch[] touches) {
foreach(FTouch touch in touches) {
//Enemy
List<Enemy> deadEnemies = new List<Enemy>();
List<float> deadTimerIndex = new List<float>();
for (int i = 0; i < m_Enemies.GetChildCount(); i++) {
//Get enemy
Enemy enemy = m_Enemies.GetChildAt(i) as Enemy;
if (enemy != null && enemy.ShouldBeTouched() && enemy.IsTouched(touch.position)) {
deadEnemies.Add(enemy);
deadTimerIndex.Add(m_EnemyShootTimer[i]);
addScoreChange(2);
//SFX
FSoundManager.PlaySound("success");
//Log
logConsole("[LOG] GarbageCollector: Enemy is successfully deleted");
break;
}
}
foreach(Enemy enemy in deadEnemies) m_Enemies.RemoveChild(enemy);
foreach(float f in deadTimerIndex) m_EnemyShootTimer.Remove(f);
//Player bullets
List<PlayerBullet> deadPlayerBullets = new List<PlayerBullet>();
for (int i = 0; i < m_PlayerBullets.GetChildCount(); i++) {
//Get player bullets
PlayerBullet bullet = m_PlayerBullets.GetChildAt(i) as PlayerBullet;
if (bullet != null && bullet.ShouldBeTouched() && bullet.IsTouched(touch.position)) {
deadPlayerBullets.Add(bullet);
//SFX
FSoundManager.PlaySound("success");
//Log
logConsole("[LOG] GarbageCollector: PlayerBullet is successfully deleted");
break;
}
}
foreach(PlayerBullet bullet in deadPlayerBullets) m_PlayerBullets.RemoveChild(bullet);
}
}
protected void processEnemies() {
//Initialize
List<FNode> Deads = new List<FNode>();
List<float> deadTimerIndex = new List<float>();
//For each child in the container
for (int i = 0; i < m_Enemies.GetChildCount(); i++) {
//Get enemy
Enemy enemy = m_Enemies.GetChildAt(i) as Enemy;
if (enemy != null) {
//Move
enemy.x -= ENEMY_SPEED;
enemy.UpdateDuration(Time.deltaTime);
m_EnemyShootTimer[i] -= Time.deltaTime;
if (m_EnemyShootTimer[i] <= 0) {
//Shoot bullet
m_EnemyShootTimer[i] = ENEMY_SHOOT_INTERVAL;
EnemyBullet bullet = new EnemyBullet(enemy.GetPosition().x - 10, enemy.GetPosition().y);
bullet.SetTarget(m_Exa.GetPosition());
m_EnemyBullets.AddChild(bullet);
//Animate enemy
enemy.Attack();
//Log
//logConsole("[LOG] Enemy: Shooting bullet");
}
if (enemy.ShouldBeDead()) {
//Log
logConsole("[ERROR] Memory Leak: Enemy not deleted " + (m_Error + 1) + "/" + ERROR_MAX);
incrementError();
}
if (enemy.x + (enemy.getWidth() / 2) < 0) {
Deads.Add(enemy);
deadTimerIndex.Add(m_EnemyShootTimer[i]);
//Log
logConsole("[LOG] Enemy: OutOfScreen");
}
}
}
//Remove dead coins
for (int i = 0; i < Deads.Count; i++) m_Enemies.RemoveChild(Deads[i]);
foreach(float f in deadTimerIndex) m_EnemyShootTimer.Remove(f);
//Spawn
m_EnemyTimer -= Time.deltaTime;
if (m_EnemyTimer <= 0f) {
//Create
float X = Constants.UNITY_CANVAS_RIGHT + 61.0f; //Hardcode width / 2
float Y = Constants.UNITY_CANVAS_BOTTOM + (Constants.UNITY_CANVAS_HEIGHT / 12.0f * (float)(Random.Range(3, 10)));
Enemy enemy = new Enemy(X,Y);
//Add
m_Enemies.AddChild(enemy);
m_EnemyShootTimer.Add(ENEMY_FIRST_SHOOT_INTERVAL);
//Reset
m_EnemyTimer = Random.Range(1, 9) / 2.0f;
if (m_EnemyTimer > 1) m_EnemyTimer -= 1;
//Log
//logConsole("[LOG] Enemy: Spawned");
}
}
protected void processPlayerBullets(Enemy enemy) {
//Initialize
List<FNode> Deads = new List<FNode>();
List<FNode> HittedEnemies = new List<FNode>();
//For each child in the container
for (int i = 0; i < m_PlayerBullets.GetChildCount(); i++) {
//Get enemy
PlayerBullet Bullet = m_PlayerBullets.GetChildAt(i) as PlayerBullet;
if (Bullet != null) {
//Move
Bullet.x += 8.0f;
Bullet.Update(Time.deltaTime);
if (Bullet.ShouldBeDead()) {
//Log
logConsole("[ERROR] Memory Leak: PlayerBullet not deleted " + (m_Error + 1) + "/" + ERROR_MAX);
Deads.Add(Bullet);
incrementError();
}
if (enemy != null && !Bullet.ShouldBeTouched() && Bullet.doesCollide(enemy)) {
HittedEnemies.Add(enemy);
Bullet.EnableTouchChecking();
FSoundManager.PlaySound("explosion");
//Log
logConsole("[LOG] Engine: Bullet - Enemy collision detected!");
}
}
}
//Remove deads
for (int i = 0; i < Deads.Count; i++) m_PlayerBullets.RemoveChild(Deads[i]);
//Activate hitted enemies
foreach(Enemy hitted in HittedEnemies) {
hitted.EnableTouchChecking();
}
//Spawn
m_PlayerBulletTimer -= Time.deltaTime;
if (m_PlayerBulletTimer <= 0f && enemy != null && enemy.y == m_Exa.y) {
//Create
Vector2 playerPos = m_Exa.GetPosition();
float X = playerPos.x + 10.0f;
float Y = playerPos.y;
PlayerBullet bullet = new PlayerBullet(X,Y);
bullet.SetBorder(m_PlayerBulletBorder);
//Add
m_PlayerBullets.AddChild(bullet);
//Reset
m_PlayerBulletTimer = 1.5f;
//Log
//logConsole("[LOG] Player: Shooting bullet");
}
}
protected void processEnemyBullets() {
//Initialize
List<FNode> Deads = new List<FNode>();
//For each child in the container
for (int i = 0; i < m_EnemyBullets.GetChildCount(); i++) {
//Get enemy
EnemyBullet Bullet = m_EnemyBullets.GetChildAt(i) as EnemyBullet;
if (Bullet != null) {
//Move
Bullet.Update(Time.deltaTime);
//Check collision
if (Bullet.doesCollide(m_Exa)) {
addHealthChange(-10, 2);
Deads.Add(Bullet);
//SFX
FSoundManager.PlaySound("damage");
//Log
logConsole("[LOG] Engine: Player - Bullet collision automatically handled");
}
//Remove if out of screen
if (Bullet.IsOutOfScreen()) {
Deads.Add(Bullet);
//Log
logConsole("[LOG] EnemyBullet: OutOfScreen");
}
}
}
//Remove deads
for (int i = 0; i < Deads.Count; i++) m_EnemyBullets.RemoveChild(Deads[i]);
}
//Data
protected int m_Score;
protected int m_Error;
protected float m_Health;
protected float m_CoinCounterTime;
protected float m_EnemyTimer;
protected float m_PlayerBulletTimer;
protected float m_PlayerBulletBorder;
protected bool m_Started;
protected bool m_Gameover;
protected List<float> m_HealthChanges;
protected List<float> m_ScoreCounterTimers;
protected List<float> m_HealthCounterTimers;
protected List<float> m_EnemyShootTimer;
protected string[] m_ConsoleLog;
//Components
protected Exa m_Exa;
protected FContainer m_Enemies;
protected FContainer m_EnemyBullets;
protected FContainer m_PlayerBullets;
protected FSprite m_Background11;
protected FSprite m_Background12;
protected FSprite m_Background21;
protected FSprite m_Background22;
protected FSprite m_HealthGauge;
protected FSprite m_HealthBar;
protected FSprite m_Unity;
//Interface
protected FLabel m_ScoreCounter;
protected FLabel m_ErrorCounter;
protected FSprite m_HealthOverlay;
protected FSprite m_ScoreOverlay;
protected FLabel[] m_Console;
//Constants
protected const float HEALTH_MAX = 100;
protected const float ENEMY_SPEED = 3.0f;
protected const float ENEMY_FIRST_SHOOT_INTERVAL = 0f;
protected const float ENEMY_SHOOT_INTERVAL = 2.0f;
protected const int CONSOLE_MAX_LINE = 4;
protected const float CONSOLE_LINE_OFFSET = 27.5f;
protected const int ERROR_MAX = 10;
}
| |
using IntuiLab.Kinect.DataUserTracking;
using IntuiLab.Kinect.DataUserTracking.Events;
using IntuiLab.Kinect.Enums;
using IntuiLab.Kinect.Utils;
using Microsoft.Kinect;
using System.Collections.Generic;
using System.Windows.Media.Media3D;
namespace IntuiLab.Kinect.DataRecording
{
public class DataUserReplay
{
/// <summary>
/// Instance of UserData
/// </summary>
private UserData m_refUserData;
/// <summary>
/// Constructor
/// </summary>
public DataUserReplay()
{
m_refUserData = null;
}
/// <summary>
/// Create a UserData to replay
/// The joints position represent the first frame for the replay.
/// </summary>
/// <param name="userID">User ID</param>
/// <param name="jointPosition">Joints position</param>
/// <param name="depth">Depth</param>
/// <param name="timesTamp">TimesTamp</param>
public void CreateUser(int userID, Dictionary<string, Point3D> jointPosition, double depth, long timesTamp)
{
// Create Skeleton
Skeleton newSkeleton = CreateSkeleton(jointPosition);
// Create UserData
m_refUserData = new UserData(userID, newSkeleton, depth, timesTamp);
// Conect event
m_refUserData.UserGestureDetected += OnUserGestureDetected;
}
/// <summary>
/// Update the UserData for create a new frame.
/// </summary>
/// <param name="jointPosition">Joints position</param>
/// <param name="depth">Depth</param>
/// <param name="timesTamp">TimesTamp</param>
public void ReceiveNewFrame(Dictionary<string, Point3D> jointPosition, double depth, long timesTamp)
{
// Create Skeleton
Skeleton newSkeleton = CreateSkeleton(jointPosition);
// Add Skeleton to UserData
m_refUserData.AddSkeleton(newSkeleton, timesTamp);
m_refUserData.UserDepth = depth;
}
/// <summary>
/// Terminates the replay
/// </summary>
public void EndReplay()
{
m_refUserData = null;
}
/// <summary>
/// Create a Skeleton with joints position
/// </summary>
/// <param name="jointPosition">Joints position</param>
/// <returns>Skeleton</returns>
private Skeleton CreateSkeleton(Dictionary<string, Point3D> jointPosition)
{
// Create a Skeleton
Skeleton refSkeleton = new Skeleton();
refSkeleton.TrackingState = SkeletonTrackingState.Tracked;
// Inform position of every joints
foreach (KeyValuePair<string, Point3D> joint in jointPosition)
{
SkeletonPoint refSkeletonPoint = new SkeletonPoint();
refSkeletonPoint.X = (float)joint.Value.X;
refSkeletonPoint.Y = (float)joint.Value.Y;
refSkeletonPoint.Z = (float)joint.Value.Z;
Joint newJoint = refSkeleton.Joints[GetJoinType(joint.Key)];
newJoint.Position = refSkeletonPoint;
refSkeleton.Joints[GetJoinType(joint.Key)] = newJoint;
}
return refSkeleton;
}
/// <summary>
/// Get the JointType whith her name in string.
/// </summary>
/// <param name="jointName">Joint name</param>
/// <returns>JointType</returns>
private JointType GetJoinType(string jointName)
{
switch (jointName)
{
case "Head":
return JointType.Head;
case "ShoulderCenter":
return JointType.ShoulderCenter;
case "HandRight":
return JointType.HandRight;
case "WristRight":
return JointType.WristRight;
case "ElbowRight":
return JointType.ElbowRight;
case "ShoulderRight":
return JointType.ShoulderRight;
case "HandLeft":
return JointType.HandLeft;
case "WristLeft":
return JointType.WristLeft;
case "ElbowLeft":
return JointType.ElbowLeft;
case "ShoulderLeft":
return JointType.ShoulderLeft;
case "Spine":
return JointType.Spine;
case "HipCenter":
return JointType.HipCenter;
case "HipLeft":
return JointType.HipLeft;
case "KneeLeft":
return JointType.KneeLeft;
case "AnkleLeft":
return JointType.AnkleLeft;
case "FootLeft":
return JointType.FootLeft;
case "HipRight":
return JointType.HipRight;
case "KneeRight":
return JointType.KneeRight;
case "AnkleRight":
return JointType.AnkleRight;
case "FootRight":
return JointType.FootRight;
default:
return 0;
}
}
/// <summary>
/// Callback when a gesture is detected
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnUserGestureDetected(object sender, UserGestureDetectedEventArgs e)
{
switch (e.Gesture)
{
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_SWIPE_LEFT :
DebugLog.DebugTraceLog("SwipeLeft detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_SWIPE_RIGHT :
DebugLog.DebugTraceLog("SwipeRight detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_WAVE :
DebugLog.DebugTraceLog("Wave detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_PUSH :
DebugLog.DebugTraceLog("Push detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_MAXIMIZE:
DebugLog.DebugTraceLog("Maximize detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_MINIMIZE:
DebugLog.DebugTraceLog("Minimize detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_A :
DebugLog.DebugTraceLog("Posture A detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_HOME :
DebugLog.DebugTraceLog("Posture Home detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_STAY :
DebugLog.DebugTraceLog("Posture Stay detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_T :
DebugLog.DebugTraceLog("Posture T detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_U :
DebugLog.DebugTraceLog("Posture U detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_V :
DebugLog.DebugTraceLog("Posture V detected", false);
break;
case EnumKinectGestureRecognize.KINECT_RECOGNIZE_WAIT :
DebugLog.DebugTraceLog("Posture Wait detected", false);
break;
}
}
}
}
| |
using System.Collections.Generic;
namespace ProGaudi.Tarantool.Client.Model
{
public interface ITarantoolTuple
{
}
public class TarantoolTuple<T1> : ITarantoolTuple
{
public TarantoolTuple(T1 item1)
{
Item1 = item1;
}
public T1 Item1 { get; }
protected bool Equals(TarantoolTuple<T1> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TarantoolTuple<T1>) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = EqualityComparer<T1>.Default.GetHashCode(Item1);
return hashCode;
}
}
public override string ToString()
{
return $"{Item1}";
}
}
public class TarantoolTuple<T1, T2> : ITarantoolTuple
{
public TarantoolTuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
public T1 Item1 { get; }
public T2 Item2 { get; }
protected bool Equals(TarantoolTuple<T1, T2> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1) &&
EqualityComparer<T2>.Default.Equals(Item2, other.Item2);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TarantoolTuple<T1, T2>) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = EqualityComparer<T1>.Default.GetHashCode(Item1);
hashCode = (hashCode*397) ^ EqualityComparer<T2>.Default.GetHashCode(Item2);
return hashCode;
}
}
public override string ToString()
{
return $"{Item1}, {Item2}";
}
}
public class TarantoolTuple<T1, T2, T3> : ITarantoolTuple
{
public TarantoolTuple(T1 item1, T2 item2, T3 item3)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
}
public T1 Item1 { get; }
public T2 Item2 { get; }
public T3 Item3 { get; }
protected bool Equals(TarantoolTuple<T1, T2, T3> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1) &&
EqualityComparer<T2>.Default.Equals(Item2, other.Item2) &&
EqualityComparer<T3>.Default.Equals(Item3, other.Item3);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TarantoolTuple<T1, T2, T3>) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = EqualityComparer<T1>.Default.GetHashCode(Item1);
hashCode = (hashCode*397) ^ EqualityComparer<T2>.Default.GetHashCode(Item2);
hashCode = (hashCode*397) ^ EqualityComparer<T3>.Default.GetHashCode(Item3);
return hashCode;
}
}
public override string ToString()
{
return $"{Item1}, {Item2}, {Item3}";
}
}
public class TarantoolTuple<T1, T2, T3, T4> : ITarantoolTuple
{
public TarantoolTuple(T1 item1, T2 item2, T3 item3, T4 item4)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
}
public T1 Item1 { get; }
public T2 Item2 { get; }
public T3 Item3 { get; }
public T4 Item4 { get; }
protected bool Equals(TarantoolTuple<T1, T2, T3, T4> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1) &&
EqualityComparer<T2>.Default.Equals(Item2, other.Item2) &&
EqualityComparer<T3>.Default.Equals(Item3, other.Item3) &&
EqualityComparer<T4>.Default.Equals(Item4, other.Item4);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TarantoolTuple<T1, T2, T3, T4>) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = EqualityComparer<T1>.Default.GetHashCode(Item1);
hashCode = (hashCode*397) ^ EqualityComparer<T2>.Default.GetHashCode(Item2);
hashCode = (hashCode*397) ^ EqualityComparer<T3>.Default.GetHashCode(Item3);
hashCode = (hashCode*397) ^ EqualityComparer<T4>.Default.GetHashCode(Item4);
return hashCode;
}
}
public override string ToString()
{
return $"{Item1}, {Item2}, {Item3}, {Item4}";
}
}
public class TarantoolTuple<T1, T2, T3, T4, T5> : ITarantoolTuple
{
public TarantoolTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
}
public T1 Item1 { get; }
public T2 Item2 { get; }
public T3 Item3 { get; }
public T4 Item4 { get; }
public T5 Item5 { get; }
protected bool Equals(TarantoolTuple<T1, T2, T3, T4, T5> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1) &&
EqualityComparer<T2>.Default.Equals(Item2, other.Item2) &&
EqualityComparer<T3>.Default.Equals(Item3, other.Item3) &&
EqualityComparer<T4>.Default.Equals(Item4, other.Item4) &&
EqualityComparer<T5>.Default.Equals(Item5, other.Item5);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TarantoolTuple<T1, T2, T3, T4, T5>) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = EqualityComparer<T1>.Default.GetHashCode(Item1);
hashCode = (hashCode*397) ^ EqualityComparer<T2>.Default.GetHashCode(Item2);
hashCode = (hashCode*397) ^ EqualityComparer<T3>.Default.GetHashCode(Item3);
hashCode = (hashCode*397) ^ EqualityComparer<T4>.Default.GetHashCode(Item4);
hashCode = (hashCode*397) ^ EqualityComparer<T5>.Default.GetHashCode(Item5);
return hashCode;
}
}
public override string ToString()
{
return $"{Item1}, {Item2}, {Item3}, {Item4}, {Item5}";
}
}
public class TarantoolTuple<T1, T2, T3, T4, T5, T6> : ITarantoolTuple
{
public TarantoolTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
}
public T1 Item1 { get; }
public T2 Item2 { get; }
public T3 Item3 { get; }
public T4 Item4 { get; }
public T5 Item5 { get; }
public T6 Item6 { get; }
protected bool Equals(TarantoolTuple<T1, T2, T3, T4, T5, T6> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1) &&
EqualityComparer<T2>.Default.Equals(Item2, other.Item2) &&
EqualityComparer<T3>.Default.Equals(Item3, other.Item3) &&
EqualityComparer<T4>.Default.Equals(Item4, other.Item4) &&
EqualityComparer<T5>.Default.Equals(Item5, other.Item5) &&
EqualityComparer<T6>.Default.Equals(Item6, other.Item6);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TarantoolTuple<T1, T2, T3, T4, T5, T6>) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = EqualityComparer<T1>.Default.GetHashCode(Item1);
hashCode = (hashCode*397) ^ EqualityComparer<T2>.Default.GetHashCode(Item2);
hashCode = (hashCode*397) ^ EqualityComparer<T3>.Default.GetHashCode(Item3);
hashCode = (hashCode*397) ^ EqualityComparer<T4>.Default.GetHashCode(Item4);
hashCode = (hashCode*397) ^ EqualityComparer<T5>.Default.GetHashCode(Item5);
hashCode = (hashCode*397) ^ EqualityComparer<T6>.Default.GetHashCode(Item6);
return hashCode;
}
}
public override string ToString()
{
return $"{Item1}, {Item2}, {Item3}, {Item4}, {Item5}, {Item6}";
}
}
public class TarantoolTuple<T1, T2, T3, T4, T5, T6, T7> : ITarantoolTuple
{
public TarantoolTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
Item7 = item7;
}
public T1 Item1 { get; }
public T2 Item2 { get; }
public T3 Item3 { get; }
public T4 Item4 { get; }
public T5 Item5 { get; }
public T6 Item6 { get; }
public T7 Item7 { get; }
protected bool Equals(TarantoolTuple<T1, T2, T3, T4, T5, T6, T7> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1) &&
EqualityComparer<T2>.Default.Equals(Item2, other.Item2) &&
EqualityComparer<T3>.Default.Equals(Item3, other.Item3) &&
EqualityComparer<T4>.Default.Equals(Item4, other.Item4) &&
EqualityComparer<T5>.Default.Equals(Item5, other.Item5) &&
EqualityComparer<T6>.Default.Equals(Item6, other.Item6) &&
EqualityComparer<T7>.Default.Equals(Item7, other.Item7);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TarantoolTuple<T1, T2, T3, T4, T5, T6, T7>) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = EqualityComparer<T1>.Default.GetHashCode(Item1);
hashCode = (hashCode*397) ^ EqualityComparer<T2>.Default.GetHashCode(Item2);
hashCode = (hashCode*397) ^ EqualityComparer<T3>.Default.GetHashCode(Item3);
hashCode = (hashCode*397) ^ EqualityComparer<T4>.Default.GetHashCode(Item4);
hashCode = (hashCode*397) ^ EqualityComparer<T5>.Default.GetHashCode(Item5);
hashCode = (hashCode*397) ^ EqualityComparer<T6>.Default.GetHashCode(Item6);
hashCode = (hashCode*397) ^ EqualityComparer<T7>.Default.GetHashCode(Item7);
return hashCode;
}
}
public override string ToString()
{
return $"{Item1}, {Item2}, {Item3}, {Item4}, {Item5}, {Item6}, {Item7}";
}
}
public class TarantoolTuple<T1, T2, T3, T4, T5, T6, T7, T8> : ITarantoolTuple
{
public TarantoolTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
Item7 = item7;
Item8 = item8;
}
public T1 Item1 { get; }
public T2 Item2 { get; }
public T3 Item3 { get; }
public T4 Item4 { get; }
public T5 Item5 { get; }
public T6 Item6 { get; }
public T7 Item7 { get; }
public T8 Item8 { get; }
protected bool Equals(TarantoolTuple<T1, T2, T3, T4, T5, T6, T7, T8> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1) &&
EqualityComparer<T2>.Default.Equals(Item2, other.Item2) &&
EqualityComparer<T3>.Default.Equals(Item3, other.Item3) &&
EqualityComparer<T4>.Default.Equals(Item4, other.Item4) &&
EqualityComparer<T5>.Default.Equals(Item5, other.Item5) &&
EqualityComparer<T6>.Default.Equals(Item6, other.Item6) &&
EqualityComparer<T7>.Default.Equals(Item7, other.Item7) &&
EqualityComparer<T8>.Default.Equals(Item8, other.Item8);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TarantoolTuple<T1, T2, T3, T4, T5, T6, T7, T8>) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = EqualityComparer<T1>.Default.GetHashCode(Item1);
hashCode = (hashCode*397) ^ EqualityComparer<T2>.Default.GetHashCode(Item2);
hashCode = (hashCode*397) ^ EqualityComparer<T3>.Default.GetHashCode(Item3);
hashCode = (hashCode*397) ^ EqualityComparer<T4>.Default.GetHashCode(Item4);
hashCode = (hashCode*397) ^ EqualityComparer<T5>.Default.GetHashCode(Item5);
hashCode = (hashCode*397) ^ EqualityComparer<T6>.Default.GetHashCode(Item6);
hashCode = (hashCode*397) ^ EqualityComparer<T7>.Default.GetHashCode(Item7);
hashCode = (hashCode*397) ^ EqualityComparer<T8>.Default.GetHashCode(Item8);
return hashCode;
}
}
public override string ToString()
{
return $"{Item1}, {Item2}, {Item3}, {Item4}, {Item5}, {Item6}, {Item7}, {Item8}";
}
}
public class TarantoolTuple : ITarantoolTuple
{
private TarantoolTuple()
{
}
public static TarantoolTuple Empty { get; } = new TarantoolTuple();
public static TarantoolTuple<T1>
Create<T1>(T1 item1)
{
return new TarantoolTuple<T1>
(item1);
}
public static TarantoolTuple<T1, T2>
Create<T1, T2>(T1 item1, T2 item2)
{
return new TarantoolTuple<T1, T2>
(item1, item2);
}
public static TarantoolTuple<T1, T2, T3>
Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3)
{
return new TarantoolTuple<T1, T2, T3>
(item1, item2, item3);
}
public static TarantoolTuple<T1, T2, T3, T4>
Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4)
{
return new TarantoolTuple<T1, T2, T3, T4>
(item1, item2, item3, item4);
}
public static TarantoolTuple<T1, T2, T3, T4, T5>
Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
return new TarantoolTuple<T1, T2, T3, T4, T5>
(item1, item2, item3, item4, item5);
}
public static TarantoolTuple<T1, T2, T3, T4, T5, T6>
Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
return new TarantoolTuple<T1, T2, T3, T4, T5, T6>
(item1, item2, item3, item4, item5, item6);
}
public static TarantoolTuple<T1, T2, T3, T4, T5, T6, T7>
Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
return new TarantoolTuple<T1, T2, T3, T4, T5, T6, T7>
(item1, item2, item3, item4, item5, item6, item7);
}
public static TarantoolTuple<T1, T2, T3, T4, T5, T6, T7, T8>
Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7,
T8 item8)
{
return new TarantoolTuple<T1, T2, T3, T4, T5, T6, T7, T8>
(item1, item2, item3, item4, item5, item6, item7, item8);
}
}
}
| |
//-----------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All Rights Reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Cci.MetadataReader;
using Microsoft.Cci.MetadataReader.PEFile;
using Microsoft.Cci.MetadataReader.ObjectModelImplementation;
using Microsoft.Cci.UtilityDataStructures;
using System.Threading;
using System.Text;
using System.Diagnostics;
using System.Diagnostics.Contracts;
//^ using Microsoft.Contracts;
namespace Microsoft.Cci {
/// <summary>
/// Generic exception thrown by the internal implementation. This exception is not meant to be leaked outside, hence all the
/// public classes where this exception can be thrown needs to catch this.
/// </summary>
internal sealed class MetadataReaderException : Exception {
internal MetadataReaderException(
string message
)
: base(message) {
}
}
/// <summary>
/// This interface is implemented by providers of Module read write errors. That is, errors discovered while reading the metadata/il.
/// Many of these errors will be discovered incrementally and as part of background activities.
/// </summary>
public interface IMetadataReaderErrorsReporter {
}
/// <summary>
/// Dummy class to identify the error reporter.
/// </summary>
internal sealed class MetadataReaderErrorsReporter : IMetadataReaderErrorsReporter {
}
/// <summary>
/// Factory for loading assemblies and modules persisted as portable executable (pe) files.
/// </summary>
public sealed class PeReader {
internal readonly MetadataReaderErrorsReporter ErrorsReporter;
internal readonly IMetadataReaderHost metadataReaderHost;
// In Multimodule case only the main module is added to this map.
readonly Hashtable<Module> InternedIdToModuleMap;
Assembly/*?*/ coreAssembly;
internal readonly IName Value__;
internal readonly IName AsyncCallback;
internal readonly IName ParamArrayAttribute;
internal readonly IName IAsyncResult;
internal readonly IName ICloneable;
internal readonly IName RuntimeArgumentHandle;
internal readonly IName RuntimeFieldHandle;
internal readonly IName RuntimeMethodHandle;
internal readonly IName RuntimeTypeHandle;
internal readonly IName ArgIterator;
internal readonly IName IList;
internal readonly IName Mscorlib;
internal readonly IName System_Runtime;
internal readonly IName _Deleted_;
/*^
#pragma warning disable 2669
^*/
/// <summary>
/// Allocates a factory for loading assemblies and modules persisted as portable executable (pe) files.
/// </summary>
/// <param name="metadataReaderHost">
/// The host is used for providing access to pe files (OpenBinaryDocument),
/// applying host specific unification policies (UnifyAssembly, UnifyAssemblyReference, UnifyModuleReference) and for deciding
/// whether and how to load referenced assemblies and modules (ResolvingAssemblyReference, ResolvingModuleReference).
/// </param>
public PeReader(
IMetadataReaderHost metadataReaderHost
) {
this.ErrorsReporter = new MetadataReaderErrorsReporter();
this.metadataReaderHost = metadataReaderHost;
this.InternedIdToModuleMap = new Hashtable<Module>();
INameTable nameTable = metadataReaderHost.NameTable;
this.Value__ = nameTable.GetNameFor("value__");
this.AsyncCallback = nameTable.GetNameFor("AsyncCallback");
this.ParamArrayAttribute = nameTable.GetNameFor("ParamArrayAttribute");
this.IAsyncResult = nameTable.GetNameFor("IAsyncResult");
this.ICloneable = nameTable.GetNameFor("ICloneable");
this.RuntimeArgumentHandle = nameTable.GetNameFor("RuntimeArgumentHandle");
this.RuntimeFieldHandle = nameTable.GetNameFor("RuntimeFieldHandle");
this.RuntimeMethodHandle = nameTable.GetNameFor("RuntimeMethodHandle");
this.RuntimeTypeHandle = nameTable.GetNameFor("RuntimeTypeHandle");
this.ArgIterator = nameTable.GetNameFor("ArgIterator");
this.IList = nameTable.GetNameFor("IList");
this.Mscorlib = nameTable.GetNameFor("mscorlib");
this.System_Runtime = nameTable.GetNameFor("System.Runtime");
this._Deleted_ = nameTable.GetNameFor("_Deleted*");
}
/*^
#pragma warning restore 2669
^*/
/// <summary>
/// Registers the core assembly. This is called by PEFileToObjectModel when it recognizes that assembly being loaded is the Core assembly as
/// identified by the Compilation Host.
/// </summary>
/// <param name="coreAssembly"></param>
internal void RegisterCoreAssembly(Assembly/*?*/ coreAssembly) {
if (coreAssembly == null) {
// Error... Core assembly is not proper.
}
if (this.coreAssembly != null) {
// Error Core Assembly Already loaded?!?
}
this.coreAssembly = coreAssembly;
}
internal Assembly/*?*/ CoreAssembly {
get {
if (this.coreAssembly == null)
this.coreAssembly = this.LookupAssembly(null, this.metadataReaderHost.CoreAssemblySymbolicIdentity) as Assembly;
return this.coreAssembly;
}
}
/// <summary>
/// This method is called when an assembly is loaded. This makes sure that all the member modules of the assembly are loaded.
/// </summary>
/// <param name="binaryDocument"></param>
/// <param name="assembly"></param>
void OpenMemberModules(IBinaryDocument binaryDocument, Assembly assembly) {
List<Module> memberModuleList = new List<Module>();
AssemblyIdentity assemblyIdentity = assembly.AssemblyIdentity;
foreach (IFileReference fileRef in assembly.PEFileToObjectModel.GetFiles()) {
if (!fileRef.HasMetadata)
continue;
IBinaryDocumentMemoryBlock/*?*/ binaryDocumentMemoryBlock = this.metadataReaderHost.OpenBinaryDocument(binaryDocument, fileRef.FileName.Value);
if (binaryDocumentMemoryBlock == null) {
// Error...
continue;
}
try {
PEFileReader peFileReader = new PEFileReader(this, binaryDocumentMemoryBlock);
if (peFileReader.ReaderState < ReaderState.Metadata) {
// Error...
continue;
}
if (peFileReader.IsAssembly) {
// Error...
continue;
}
ModuleIdentity moduleIdentity = this.GetModuleIdentifier(peFileReader, assemblyIdentity);
PEFileToObjectModel peFileToObjectModel = new PEFileToObjectModel(this, peFileReader, moduleIdentity, assembly, this.metadataReaderHost.PointerSize);
memberModuleList.Add(peFileToObjectModel.Module);
} catch (MetadataReaderException) {
continue;
}
}
if (memberModuleList.Count == 0)
return;
assembly.SetMemberModules(memberModuleList.ToArray());
}
void LoadedModule(Module module) {
this.InternedIdToModuleMap.Add(module.InternedModuleId, module);
}
/// <summary>
/// Method to open the assembly in MetadataReader. This method loads the assembly and returns the object corresponding to the
/// opened assembly. Also returns the AssemblyIdentifier corresponding to the assembly as the out parameter.
/// Only assemblies that unify to themselves can be opened i.e. if the unification policy of the compilation host says that mscorlib 1.0 unifies to mscorlib 2.0
/// then only mscorlib 2.0 can be loaded.
/// </summary>
/// <param name="binaryDocument">The binary document that needes to be opened as an assembly.</param>
/// <param name="assemblyIdentity">Contains the assembly identifier of the binary document in case it is an assembly.</param>
/// <returns>Assembly that is loaded or Dummy.Assembly in case assembly could not be loaded.</returns>
public IAssembly OpenAssembly(IBinaryDocument binaryDocument, out AssemblyIdentity/*?*/ assemblyIdentity) {
Contract.Requires(binaryDocument != null);
Contract.Ensures(Contract.Result<IAssembly>() != null);
assemblyIdentity = null;
lock (GlobalLock.LockingObject) {
IBinaryDocumentMemoryBlock/*?*/ binaryDocumentMemoryBlock = this.metadataReaderHost.OpenBinaryDocument(binaryDocument);
if (binaryDocumentMemoryBlock == null) {
// Error...
return Dummy.Assembly;
}
PEFileReader peFileReader = new PEFileReader(this, binaryDocumentMemoryBlock);
if (peFileReader.ReaderState < ReaderState.Metadata) {
// Error...
return Dummy.Assembly;
}
//^ assert peFileReader.ReaderState >= ReaderState.Metadata;
if (!peFileReader.IsAssembly) {
// Error...
return Dummy.Assembly;
}
assemblyIdentity = this.GetAssemblyIdentifier(peFileReader);
Assembly/*?*/ lookupAssembly = this.LookupAssembly(null, assemblyIdentity);
if (lookupAssembly != null) {
return lookupAssembly;
}
try {
PEFileToObjectModel peFileToObjectModel = new PEFileToObjectModel(this, peFileReader, assemblyIdentity, null, this.metadataReaderHost.PointerSize);
Assembly/*?*/ assembly = peFileToObjectModel.Module as Assembly;
//^ assert assembly != null;
this.LoadedModule(assembly);
this.OpenMemberModules(binaryDocument, assembly);
return assembly;
} catch (MetadataReaderException) {
return Dummy.Assembly;
}
}
}
/// <summary>
/// Method to open the module in the MetadataReader. This method loads the module and returns the object corresponding to the opened module.
/// Also returns the ModuleIDentifier corresponding to the module as the out parameter. Modules are opened as if they are not contained in any assembly.
/// </summary>
/// <param name="binaryDocument">The binary document that needes to be opened as an module.</param>
/// <param name="moduleIdentity">Contains the module identity of the binary document in case it is an module.</param>
/// <returns>Module that is loaded or Dummy.Module in case module could not be loaded.</returns>
public IModule OpenModule(IBinaryDocument binaryDocument, out ModuleIdentity/*?*/ moduleIdentity) {
Contract.Requires(binaryDocument != null);
Contract.Ensures(Contract.Result<IModule>() != null);
moduleIdentity = null;
lock (GlobalLock.LockingObject) {
IBinaryDocumentMemoryBlock/*?*/ binaryDocumentMemoryBlock = this.metadataReaderHost.OpenBinaryDocument(binaryDocument);
if (binaryDocumentMemoryBlock == null) {
// Error...
return Dummy.Module;
}
PEFileReader peFileReader = new PEFileReader(this, binaryDocumentMemoryBlock);
if (peFileReader.ReaderState < ReaderState.Metadata) {
// Error...
return Dummy.Module;
}
//^ assert peFileReader.ReaderState >= ReaderState.Metadata;
if (peFileReader.IsAssembly) {
AssemblyIdentity assemblyIdentity = this.GetAssemblyIdentifier(peFileReader);
moduleIdentity = assemblyIdentity;
Assembly/*?*/ lookupAssembly = this.LookupAssembly(null, assemblyIdentity);
if (lookupAssembly != null) {
return lookupAssembly;
}
} else {
moduleIdentity = this.GetModuleIdentifier(peFileReader);
Module/*?*/ lookupModule = this.LookupModule(null, moduleIdentity);
if (lookupModule != null) {
return lookupModule;
}
}
try {
PEFileToObjectModel peFileToObjectModel = new PEFileToObjectModel(this, peFileReader, moduleIdentity, null, this.metadataReaderHost.PointerSize);
this.LoadedModule(peFileToObjectModel.Module);
Assembly/*?*/ assembly = peFileToObjectModel.Module as Assembly;
if (assembly != null) {
this.OpenMemberModules(binaryDocument, assembly);
}
return peFileToObjectModel.Module;
} catch (MetadataReaderException) {
// Error...
}
}
return Dummy.Module;
}
/// <summary>
/// Method to open the assembly in MetadataReader. This method loads the assembly and returns the object corresponding to the
/// opened assembly. Also returns the AssemblyIdentifier corresponding to the assembly as the out parameter.
/// Only assemblies that unify to themselves can be opened i.e. if the unification policy of the compilation host says that mscorlib 1.0 unifies to mscorlib 2.0
/// then only mscorlib 2.0 can be loaded.
/// </summary>
/// <param name="binaryDocument">The binary document that needes to be opened as an assembly.</param>
/// <returns>Assembly that is loaded or Dummy.Assembly in case assembly could not be loaded.</returns>
public IAssembly OpenAssembly(IBinaryDocument binaryDocument) {
Contract.Requires(binaryDocument != null);
Contract.Ensures(Contract.Result<IAssembly>() != null);
AssemblyIdentity/*?*/ retAssemblyIdentity;
return this.OpenAssembly(binaryDocument, out retAssemblyIdentity);
}
/// <summary>
/// Method to open the module in the MetadataReader. This method loads the module and returns the object corresponding to the opened module.
/// Also returns the ModuleIDentifier corresponding to the module as the out parameter. Modules are opened as if they are not contained in any assembly.
/// </summary>
/// <param name="binaryDocument">The binary document that needes to be opened as an module.</param>
/// <returns>Module that is loaded or Dummy.Module in case module could not be loaded.</returns>
public IModule OpenModule(IBinaryDocument binaryDocument) {
Contract.Requires(binaryDocument != null);
Contract.Ensures(Contract.Result<IModule>() != null);
ModuleIdentity/*?*/ retModuleIdentity;
return this.OpenModule(binaryDocument, out retModuleIdentity);
}
/// <summary>
/// Does a look up in the loaded assemblies if the given assembly identified by assemblyIdentifier is loaded. This also gives a chance to MetadataReaderHost to
/// delay load the assembly if needed.
/// </summary>
/// <param name="referringModule"></param>
/// <param name="unifiedAssemblyIdentity"></param>
/// <returns></returns>
internal Assembly/*?*/ LookupAssembly(IModule/*?*/ referringModule, AssemblyIdentity unifiedAssemblyIdentity) {
lock (GlobalLock.LockingObject) {
uint internedModuleId = (uint)this.metadataReaderHost.InternFactory.GetAssemblyInternedKey(unifiedAssemblyIdentity);
Module/*?*/ module = this.InternedIdToModuleMap.Find(internedModuleId);
if (module == null && referringModule != null) {
this.metadataReaderHost.ResolvingAssemblyReference(referringModule, unifiedAssemblyIdentity);
// See if the host loaded the assembly using this PeReader (loading indirectly causes the map to be updated)
module = this.InternedIdToModuleMap.Find(internedModuleId);
if (module == null) {
// One last chance, it might have been already loaded by a different instance of PeReader
var a = this.metadataReaderHost.FindAssembly(unifiedAssemblyIdentity);
Module m = a as Module;
if (m != null) {
this.LoadedModule(m);
module = m;
}
}
}
return module as Assembly;
}
}
/// <summary>
/// Does a look up in the loaded modules if the given module identified by moduleIdentifier is loaded. This also gives a chance to MetadataReaderHost to
/// delay load the module if needed.
/// </summary>
/// <param name="referringModule"></param>
/// <param name="moduleIdentity"></param>
/// <returns></returns>
internal Module/*?*/ LookupModule(IModule/*?*/ referringModule, ModuleIdentity moduleIdentity) {
lock (GlobalLock.LockingObject) {
uint internedModuleId = (uint)this.metadataReaderHost.InternFactory.GetModuleInternedKey(moduleIdentity);
Module/*?*/ module = this.InternedIdToModuleMap.Find(internedModuleId);
if (module == null && referringModule != null) {
this.metadataReaderHost.ResolvingModuleReference(referringModule, moduleIdentity);
module = this.InternedIdToModuleMap.Find(internedModuleId);
}
return module;
}
}
/// <summary>
/// If the given binary document contains a CLR assembly, return the identity of the assembly. Otherwise, return null.
/// </summary>
public AssemblyIdentity/*?*/ GetAssemblyIdentifier(IBinaryDocument binaryDocument) {
IBinaryDocumentMemoryBlock/*?*/ binaryDocumentMemoryBlock = this.metadataReaderHost.OpenBinaryDocument(binaryDocument);
if (binaryDocumentMemoryBlock == null) return null;
PEFileReader peFileReader = new PEFileReader(this, binaryDocumentMemoryBlock);
if (peFileReader.ReaderState < ReaderState.Metadata) return null;
if (!peFileReader.IsAssembly) return null;
return this.GetAssemblyIdentifier(peFileReader);
}
/// <summary>
/// Computes the AssemblyIdentifier of the PE File. This requires that peFile is an assembly.
/// </summary>
/// <param name="peFileReader"></param>
/// <returns></returns>
internal AssemblyIdentity GetAssemblyIdentifier(PEFileReader peFileReader)
//^ requires peFileReader.ReaderState >= ReaderState.Metadata && peFileReader.IsAssembly;
//^ ensures (result.Location != null && result.Location.Length != 0);
{
AssemblyRow assemblyRow = peFileReader.AssemblyTable[1];
IName assemblyName = this.metadataReaderHost.NameTable.GetNameFor(peFileReader.StringStream[assemblyRow.Name]);
string cultureName = peFileReader.StringStream[assemblyRow.Culture];
Version version = new Version(assemblyRow.MajorVersion, assemblyRow.MinorVersion, assemblyRow.BuildNumber, assemblyRow.RevisionNumber);
byte[] publicKeyArray = TypeCache.EmptyByteArray;
byte[] publicKeyTokenArray = TypeCache.EmptyByteArray;
if (assemblyRow.PublicKey != 0) {
publicKeyArray = peFileReader.BlobStream[assemblyRow.PublicKey];
if (publicKeyArray.Length > 0) {
publicKeyTokenArray = UnitHelper.ComputePublicKeyToken(publicKeyArray);
}
}
return new AssemblyIdentity(assemblyName, cultureName, version, publicKeyTokenArray, peFileReader.BinaryDocumentMemoryBlock.BinaryDocument.Location);
}
/// <summary>
/// Computes the ModuleIdentifier of the PE File as if the module did not belong to any assembly.
/// </summary>
/// <param name="peFileReader"></param>
/// <returns></returns>
internal ModuleIdentity GetModuleIdentifier(PEFileReader peFileReader)
//^ requires peFileReader.ReaderState >= ReaderState.Metadata;
//^ ensures (result.Location != null && result.Location.Length != 0);
{
ModuleRow moduleRow = peFileReader.ModuleTable[1];
IName moduleName = this.metadataReaderHost.NameTable.GetNameFor(peFileReader.StringStream[moduleRow.Name]);
return new ModuleIdentity(moduleName, peFileReader.BinaryDocumentMemoryBlock.BinaryDocument.Location);
}
/// <summary>
/// Computes the ModuleIdentifier of the PE File as if the module belong to given assembly.
/// </summary>
/// <param name="peFileReader"></param>
/// <param name="containingAssemblyIdentity"></param>
/// <returns></returns>
internal ModuleIdentity GetModuleIdentifier(PEFileReader peFileReader, AssemblyIdentity containingAssemblyIdentity)
//^ requires peFileReader.ReaderState >= ReaderState.Metadata;
//^ ensures (result.Location != null && result.Location.Length != 0);
{
ModuleRow moduleRow = peFileReader.ModuleTable[1];
IName moduleName = this.metadataReaderHost.NameTable.GetNameFor(peFileReader.StringStream[moduleRow.Name]);
return new ModuleIdentity(moduleName, peFileReader.BinaryDocumentMemoryBlock.BinaryDocument.Location, containingAssemblyIdentity);
}
/// <summary>
/// Lists all the opened modules.
/// </summary>
public IEnumerable<IModule> OpenedModules {
get {
foreach (Module module in this.InternedIdToModuleMap.Values) {
yield return module;
}
}
}
/// <summary>
/// Returns the module corresponding to passed moduleIdentifier if it was loaded.
/// </summary>
/// <param name="moduleIdentity"></param>
/// <returns></returns>
public IModule/*?*/ FindModule(ModuleIdentity moduleIdentity) {
return this.LookupModule(null, moduleIdentity);
}
/// <summary>
/// Returns the assembly corresponding to passed assemblyIdentifier if it was loaded.
/// </summary>
/// <param name="unifiedAssemblyIdentity">THe assembly Identifier that is unified with respect to the compilation host.</param>
/// <returns></returns>
public IAssembly/*?*/ FindAssembly(AssemblyIdentity unifiedAssemblyIdentity) {
lock (GlobalLock.LockingObject) {
uint internedModuleId = (uint)this.metadataReaderHost.InternFactory.GetAssemblyInternedKey(unifiedAssemblyIdentity);
Module/*?*/ module = this.InternedIdToModuleMap.Find(internedModuleId);
return module as IAssembly;
}
}
/// <summary>
/// Resolves the serialized type name as if it belonged to the passed assembly.
/// </summary>
/// <param name="typeName">Serialized type name.</param>
/// <param name="assembly">Assembly in which this needs to be resolved. If null then it is to be resolved in mscorlib.</param>
/// <returns></returns>
public ITypeDefinition ResolveSerializedTypeName(string typeName, IAssembly/*?*/ assembly) {
if (assembly == null) {
assembly = this.CoreAssembly;
}
Assembly/*?*/ internalAssembly = assembly as Assembly;
if (internalAssembly == null) {
return Dummy.Type;
}
ITypeReference/*?*/ moduleTypeRef = internalAssembly.PEFileToObjectModel.GetSerializedTypeNameAsTypeReference(typeName);
if (moduleTypeRef == null) {
return Dummy.Type;
}
return moduleTypeRef.ResolvedType;
}
/// <summary>
/// A simple host environment using default settings inherited from MetadataReaderHost and that
/// uses PeReader as its metadata reader.
/// </summary>
public class DefaultHost : MetadataReaderHost {
PeReader peReader;
/// <summary>
/// Allocates a simple host environment using default settings inherited from MetadataReaderHost and that
/// uses PeReader as its metadata reader.
/// </summary>
public DefaultHost()
: base(new NameTable(), new InternFactory(), 0, null, true) {
this.peReader = new PeReader(this);
}
/// <summary>
/// Allocates a simple host environment using default settings inherited from MetadataReaderHost and that
/// uses PeReader as its metadata reader.
/// </summary>
/// <param name="nameTable">
/// A collection of IName instances that represent names that are commonly used during compilation.
/// This is a provided as a parameter to the host environment in order to allow more than one host
/// environment to co-exist while agreeing on how to map strings to IName instances.
/// </param>
public DefaultHost(INameTable nameTable)
: base(nameTable, new InternFactory(), 0, null, false) {
this.peReader = new PeReader(this);
}
/// <summary>
/// Returns the unit that is stored at the given location, or a dummy unit if no unit exists at that location or if the unit at that location is not accessible.
/// </summary>
/// <param name="location">A path to the file that contains the unit of metdata to load.</param>
public override IUnit LoadUnitFrom(string location) {
IUnit result = this.peReader.OpenModule(
BinaryDocument.GetBinaryDocumentForFile(location, this));
this.RegisterAsLatest(result);
return result;
}
}
}
}
| |
using System;
using System.ComponentModel.Design;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using BTDB.Buffer;
using Microsoft.Extensions.Primitives;
namespace BTDB.StreamLayer;
public ref struct SpanWriter
{
public SpanWriter(Span<byte> initialBuffer)
{
Buf = initialBuffer;
InitialBuffer = initialBuffer;
HeapBuffer = null;
Controller = null;
}
public unsafe SpanWriter(void* buf, int size)
{
Buf = MemoryMarshal.CreateSpan(ref Unsafe.AsRef<byte>(buf), size);
InitialBuffer = Buf;
HeapBuffer = null;
Controller = null;
}
public SpanWriter(ISpanWriter controller)
{
Controller = controller;
Buf = new Span<byte>();
InitialBuffer = new Span<byte>();
HeapBuffer = null;
Controller.Init(ref this);
}
public Span<byte> Buf;
public Span<byte> InitialBuffer;
// When this is not null than Buf must be slice of HeapBuffer.AsSpan(), otherwise Buf must be slice of InitialBuffer
public byte[]? HeapBuffer;
public ISpanWriter? Controller;
public ReadOnlySpan<byte> GetSpan()
{
if (Controller != null) ThrowCannotBeUsedWithController();
if (HeapBuffer != null)
{
return HeapBuffer.AsSpan(0, HeapBuffer.Length - Buf.Length);
}
return InitialBuffer.Slice(0, InitialBuffer.Length - Buf.Length);
}
public ReadOnlySpan<byte> GetPersistentSpanAndReset()
{
if (Controller != null) ThrowCannotBeUsedWithController();
if (HeapBuffer != null)
{
var res = HeapBuffer.AsSpan(0, HeapBuffer.Length - Buf.Length);
Buf = InitialBuffer;
HeapBuffer = null;
return res;
}
else
{
var res = InitialBuffer.Slice(0, InitialBuffer.Length - Buf.Length);
InitialBuffer = Buf;
return res;
}
}
static void ThrowCannotBeUsedWithController()
{
throw new InvalidOperationException("Cannot have controller");
}
public void Reset()
{
#if DEBUG
if (Controller != null) ThrowCannotBeUsedWithController();
#endif
Buf = HeapBuffer ?? InitialBuffer;
}
public ReadOnlySpan<byte> GetSpanAndReset()
{
#if DEBUG
if (Controller != null) ThrowCannotBeUsedWithController();
#endif
if (HeapBuffer != null)
{
var buf = HeapBuffer;
var res = buf.AsSpan(0, buf.Length - Buf.Length);
HeapBuffer = null;
Buf = InitialBuffer;
return res;
}
else
{
var res = InitialBuffer.Slice(0, InitialBuffer.Length - Buf.Length);
Buf = InitialBuffer;
return res;
}
}
public ByteBuffer GetByteBufferAndReset()
{
if (Controller != null) ThrowCannotBeUsedWithController();
if (HeapBuffer != null)
{
var buf = HeapBuffer;
var res = ByteBuffer.NewAsync(buf, 0, buf.Length - Buf.Length);
HeapBuffer = null;
Buf = InitialBuffer;
return res;
}
else
{
var res = ByteBuffer.NewAsync(InitialBuffer.Slice(0, InitialBuffer.Length - Buf.Length));
Buf = InitialBuffer;
return res;
}
}
public long GetCurrentPosition()
{
if (Controller != null) return Controller.GetCurrentPosition(this);
if (HeapBuffer != null)
{
return HeapBuffer.Length - Buf.Length;
}
return InitialBuffer.Length - Buf.Length;
}
public void SetCurrentPosition(long pos)
{
if (Controller != null)
{
Controller.SetCurrentPosition(ref this, pos);
return;
}
if (HeapBuffer != null)
{
Buf = HeapBuffer.AsSpan((int)pos);
return;
}
Buf = InitialBuffer.Slice((int)pos);
}
/// <summary>
/// DANGER: This can be called only as last method on this `SpanWriter`!
/// </summary>
public void Sync()
{
if (Controller == null) ThrowCanBeUsedOnlyWithController();
Controller!.Sync(ref this);
}
static void ThrowCanBeUsedOnlyWithController()
{
throw new InvalidOperationException("Need controller");
}
bool Resize(uint spaceNeeded)
{
if (Controller != null)
{
return Controller.Flush(ref this);
}
var pos = (uint)GetCurrentPosition();
if (HeapBuffer == null)
{
var newSize = Math.Max((uint)InitialBuffer.Length * 2, 32);
newSize = Math.Max(newSize, pos + spaceNeeded);
newSize = Math.Min(newSize, int.MaxValue);
HeapBuffer = new byte[newSize];
InitialBuffer.Slice(0, (int)pos).CopyTo(HeapBuffer);
Buf = HeapBuffer.AsSpan((int)pos, (int)(newSize - pos));
}
else
{
var newSize = Math.Max((uint)HeapBuffer.Length * 2, pos + spaceNeeded);
newSize = Math.Min(newSize, int.MaxValue);
Array.Resize(ref HeapBuffer, (int)newSize);
Buf = HeapBuffer.AsSpan((int)pos, (int)(newSize - pos));
}
return true;
}
public void WriteByteZero()
{
if (Buf.IsEmpty)
{
Resize(1);
}
PackUnpack.UnsafeGetAndAdvance(ref Buf, 1) = 0;
}
public unsafe void WriteBool(bool value)
{
if (Buf.IsEmpty)
{
Resize(1);
}
PackUnpack.UnsafeGetAndAdvance(ref Buf, 1) = *(byte*)&value;
}
public void WriteUInt8(byte value)
{
if (Buf.IsEmpty)
{
Resize(1);
}
PackUnpack.UnsafeGetAndAdvance(ref Buf, 1) = value;
}
public void WriteInt8(sbyte value)
{
if (Buf.IsEmpty)
{
Resize(1);
}
PackUnpack.UnsafeGetAndAdvance(ref Buf, 1) = (byte)value;
}
public void WriteInt8Ordered(sbyte value)
{
if (Buf.IsEmpty)
{
Resize(1);
}
PackUnpack.UnsafeGetAndAdvance(ref Buf, 1) = (byte)(value + 128);
}
public void WriteVInt16(short value)
{
WriteVInt64(value);
}
public void WriteVUInt16(ushort value)
{
WriteVUInt64(value);
}
public void WriteVInt32(int value)
{
WriteVInt64(value);
}
public void WriteVUInt32(uint value)
{
WriteVUInt64(value);
}
[SkipLocalsInit]
public void WriteVInt64(long value)
{
var len = PackUnpack.LengthVInt(value);
if ((uint)Buf.Length < len)
{
if (!Resize(len))
{
Span<byte> buf = stackalloc byte[(int)len];
ref var bufRef = ref MemoryMarshal.GetReference(buf);
PackUnpack.UnsafePackVInt(ref bufRef, value, len);
WriteBlock(ref bufRef, len);
return;
}
}
PackUnpack.UnsafePackVInt(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, (int)len), value, len);
}
[SkipLocalsInit]
public void WriteVUInt64(ulong value)
{
var len = PackUnpack.LengthVUInt(value);
if ((uint)Buf.Length < len)
{
if (!Resize(len))
{
Span<byte> buf = stackalloc byte[(int)len];
ref var bufRef = ref MemoryMarshal.GetReference(buf);
PackUnpack.UnsafePackVUInt(ref bufRef, value, len);
WriteBlock(ref bufRef, len);
return;
}
}
PackUnpack.UnsafePackVUInt(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, (int)len), value, len);
}
[SkipLocalsInit]
public void WriteInt64(long value)
{
if ((uint)Buf.Length < 8u)
{
if (!Resize(8))
{
Span<byte> buf = stackalloc byte[8];
ref var bufRef = ref MemoryMarshal.GetReference(buf);
Unsafe.As<byte, ulong>(ref bufRef) = PackUnpack.AsBigEndian((ulong)value);
WriteBlock(ref bufRef, 8);
return;
}
}
Unsafe.As<byte, ulong>(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, 8)) =
PackUnpack.AsBigEndian((ulong)value);
}
[SkipLocalsInit]
public void WriteInt32(int value)
{
if ((uint)Buf.Length < 4u)
{
if (!Resize(4))
{
Span<byte> buf = stackalloc byte[4];
ref var bufRef = ref MemoryMarshal.GetReference(buf);
Unsafe.As<byte, uint>(ref bufRef) = PackUnpack.AsBigEndian((uint)value);
WriteBlock(ref bufRef, 4);
return;
}
}
Unsafe.As<byte, uint>(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, 4)) =
PackUnpack.AsBigEndian((uint)value);
}
[SkipLocalsInit]
public void WriteInt16(int value)
{
if ((uint)Buf.Length < 2u)
{
if (!Resize(2))
{
Span<byte> buf = stackalloc byte[2];
ref var bufRef = ref MemoryMarshal.GetReference(buf);
Unsafe.As<byte, ushort>(ref bufRef) = PackUnpack.AsBigEndian((ushort)value);
WriteBlock(ref bufRef, 2);
return;
}
}
Unsafe.As<byte, ushort>(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, 2)) =
PackUnpack.AsBigEndian((ushort)value);
}
[SkipLocalsInit]
public void WriteInt32LE(int value)
{
if ((uint)Buf.Length < 4u)
{
if (!Resize(4))
{
Span<byte> buf = stackalloc byte[4];
ref var bufRef = ref MemoryMarshal.GetReference(buf);
Unsafe.As<byte, uint>(ref bufRef) = PackUnpack.AsLittleEndian((uint)value);
WriteBlock(ref bufRef, 4);
return;
}
}
Unsafe.As<byte, uint>(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, 4)) =
PackUnpack.AsLittleEndian((uint)value);
}
public void WriteDateTime(DateTime value)
{
WriteInt64(value.ToBinary());
}
public void WriteDateTimeForbidUnspecifiedKind(DateTime value)
{
if (value.Kind == DateTimeKind.Unspecified)
{
if (value == DateTime.MinValue)
value = DateTime.MinValue.ToUniversalTime();
else if (value == DateTime.MaxValue)
value = DateTime.MaxValue.ToUniversalTime();
else
throw new ArgumentOutOfRangeException(nameof(value),
"DateTime.Kind cannot be stored as Unspecified");
}
WriteDateTime(value);
}
public void WriteDateTimeOffset(DateTimeOffset value)
{
WriteVInt64(value.Ticks);
WriteTimeSpan(value.Offset);
}
public void WriteTimeSpan(TimeSpan value)
{
WriteVInt64(value.Ticks);
}
public unsafe void WriteString(string? value)
{
if (value == null)
{
WriteByteZero();
return;
}
var l = value.Length;
if (l == 0)
{
WriteUInt8(1);
return;
}
fixed (char* strPtrStart = value)
{
var strPtr = strPtrStart;
var strPtrEnd = strPtrStart + l;
var toEncode = (uint)(l + 1);
doEncode:
WriteVUInt32(toEncode);
while (strPtr != strPtrEnd)
{
var c = *strPtr++;
if (c < 0x80)
{
if (Buf.IsEmpty)
{
Resize(1);
}
PackUnpack.UnsafeGetAndAdvance(ref Buf, 1) = (byte)c;
}
else
{
if (char.IsHighSurrogate(c) && strPtr != strPtrEnd)
{
var c2 = *strPtr;
if (char.IsLowSurrogate(c2))
{
toEncode = (uint)((c - 0xD800) * 0x400 + (c2 - 0xDC00) + 0x10000);
strPtr++;
goto doEncode;
}
}
toEncode = c;
goto doEncode;
}
}
}
}
public void WriteStringOrdered(string? value)
{
if (value == null)
{
WriteVUInt32(0x110001);
return;
}
var l = value.Length;
var i = 0;
while (i < l)
{
var c = value[i];
if (char.IsHighSurrogate(c) && i + 1 < l)
{
var c2 = value[i + 1];
if (char.IsLowSurrogate(c2))
{
WriteVUInt32((uint)((c - 0xD800) * 0x400 + (c2 - 0xDC00) + 0x10000) + 1);
i += 2;
continue;
}
}
WriteVUInt32((uint)c + 1);
i++;
}
WriteByteZero();
}
public void WriteStringOrderedPrefix(string value)
{
var l = value.Length;
var i = 0;
while (i < l)
{
var c = value[i];
if (char.IsHighSurrogate(c) && i + 1 < l)
{
var c2 = value[i + 1];
if (char.IsLowSurrogate(c2))
{
WriteVUInt32((uint)((c - 0xD800) * 0x400 + (c2 - 0xDC00) + 0x10000) + 1);
i += 2;
continue;
}
}
WriteVUInt32((uint)c + 1);
i++;
}
}
public unsafe void WriteStringInUtf8(string value)
{
var l = Encoding.UTF8.GetByteCount(value);
WriteVUInt32((uint)l);
if ((uint)l <= (uint)Buf.Length)
{
PackUnpack.UnsafeAdvance(ref Buf, Encoding.UTF8.GetBytes(value.AsSpan(), Buf));
return;
}
Span<byte> buf = l <= 512 ? stackalloc byte[l] : new byte[l];
Encoding.UTF8.GetBytes(value.AsSpan(), buf);
WriteBlock(ref MemoryMarshal.GetReference(buf), (uint)buf.Length);
}
public void WriteBlock(ReadOnlySpan<byte> data)
{
WriteBlock(ref MemoryMarshal.GetReference(data), (uint)data.Length);
}
public void WriteBlock(ref byte buffer, uint length)
{
if ((uint)Buf.Length < length)
{
if (Controller != null)
{
if (HeapBuffer != null)
{
var bufLength = HeapBuffer.Length;
if (length < bufLength || !Controller.Flush(ref this))
{
Unsafe.CopyBlockUnaligned(ref MemoryMarshal.GetReference(Buf), ref buffer,
(uint)Buf.Length);
buffer = ref Unsafe.AddByteOffset(ref buffer, (IntPtr)Buf.Length);
length -= (uint)Buf.Length;
Buf = new Span<byte>();
Controller.Flush(ref this); // must return true because Buf is empty
}
if (length < bufLength)
{
Unsafe.CopyBlockUnaligned(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, (int)length),
ref buffer, length);
return;
}
}
Controller.WriteBlock(ref this, ref buffer, length);
return;
}
Resize(length); // returns always success because it is without controller
}
Unsafe.CopyBlockUnaligned(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, (int)length), ref buffer,
length);
}
public void WriteBlock(byte[] buffer, int offset, int length)
{
WriteBlock(buffer.AsSpan(offset, length));
}
public unsafe void WriteBlock(IntPtr data, int length)
{
WriteBlock(ref Unsafe.AsRef<byte>((void*)data), (uint)length);
}
public void WriteBlock(byte[] data)
{
WriteBlock(data.AsSpan());
}
public void WriteGuid(Guid value)
{
WriteBlock(ref Unsafe.As<Guid, byte>(ref Unsafe.AsRef(value)), 16);
}
public void WriteSingle(float value)
{
WriteInt32(BitConverter.SingleToInt32Bits(value));
}
public void WriteDouble(double value)
{
WriteInt64(BitConverter.DoubleToInt64Bits(value));
}
public void WriteHalf(Half value)
{
WriteInt16(Unsafe.As<Half, short>(ref Unsafe.AsRef(value)));
}
public void WriteDecimal(decimal value)
{
var ints = decimal.GetBits(value);
var header = (byte)((ints[3] >> 16) & 31);
if (ints[3] < 0) header |= 128;
var first = (uint)ints[0] + ((ulong)ints[1] << 32);
if (ints[2] == 0)
{
if (first == 0)
{
WriteUInt8(header);
}
else
{
header |= 32;
WriteUInt8(header);
WriteVUInt64(first);
}
}
else
{
if ((uint)ints[2] < 0x10000000)
{
header |= 64;
WriteUInt8(header);
WriteVUInt32((uint)ints[2]);
WriteInt64((long)first);
}
else
{
header |= 64 | 32;
WriteUInt8(header);
WriteInt32(ints[2]);
WriteInt64((long)first);
}
}
}
public void WriteByteArray(byte[]? value)
{
if (value == null)
{
WriteByteZero();
return;
}
WriteVUInt32((uint)(value.Length + 1));
WriteBlock(value);
}
public void WriteByteArray(ByteBuffer value)
{
WriteVUInt32((uint)(value.Length + 1));
WriteBlock(value);
}
public void WriteByteArray(ReadOnlySpan<byte> value)
{
WriteVUInt32((uint)(value.Length + 1));
WriteBlock(value);
}
public void WriteByteArrayRaw(byte[]? value)
{
if (value == null) return;
WriteBlock(value);
}
public void WriteBlock(ByteBuffer data)
{
WriteBlock(data.AsSyncReadOnlySpan());
}
[SkipLocalsInit]
public void WriteIPAddress(IPAddress? value)
{
if (value == null)
{
WriteUInt8(3);
return;
}
if (value.AddressFamily == AddressFamily.InterNetworkV6)
{
if (value.ScopeId != 0)
{
Span<byte> buf = stackalloc byte[16];
ref var bufRef = ref MemoryMarshal.GetReference(buf);
value.TryWriteBytes(buf, out _);
WriteUInt8(2);
WriteBlock(ref bufRef, 16);
WriteVUInt64((ulong)value.ScopeId);
}
else
{
Span<byte> buf = stackalloc byte[16];
ref var bufRef = ref MemoryMarshal.GetReference(buf);
value.TryWriteBytes(buf, out _);
WriteUInt8(1);
WriteBlock(ref bufRef, 16);
}
}
else
{
WriteUInt8(0);
#pragma warning disable 612, 618
WriteInt32LE((int)value.Address);
#pragma warning restore 612, 618
}
}
public void WriteVersion(Version? value)
{
if (value == null)
{
WriteUInt8(0);
return;
}
WriteVUInt32((uint)value.Major + 1);
WriteVUInt32((uint)value.Minor + 1);
if (value.Minor == -1) return;
WriteVUInt32((uint)value.Build + 1);
if (value.Build == -1) return;
WriteVUInt32((uint)value.Revision + 1);
}
public void WriteStringValues(StringValues value)
{
WriteVUInt32((uint)value.Count);
foreach (var s in value)
{
WriteString(s);
}
}
uint NoControllerGetCurrentPosition()
{
if (HeapBuffer != null)
{
return (uint)(HeapBuffer.Length - Buf.Length);
}
return (uint)(InitialBuffer.Length - Buf.Length);
}
public uint StartWriteByteArray()
{
if (Controller != null) ThrowCannotBeUsedWithController();
WriteByteZero();
return NoControllerGetCurrentPosition();
}
public void FinishWriteByteArray(uint start)
{
var end = NoControllerGetCurrentPosition();
var len = end - start + 1;
var lenOfLen = PackUnpack.LengthVUInt(len);
if (lenOfLen == 1)
{
if (HeapBuffer != null)
{
HeapBuffer[start - 1] = (byte)len;
return;
}
InitialBuffer[(int)(start - 1)] = (byte)len;
return;
}
// Reserve space at end
Resize(lenOfLen - 1);
PackUnpack.UnsafeAdvance(ref Buf, (int)lenOfLen - 1);
// Make Space By Moving Memory
InternalGetSpan(start, len - 1).CopyTo(InternalGetSpan(start + lenOfLen - 1, len - 1));
// Update Length at start
PackUnpack.UnsafePackVUInt(ref MemoryMarshal.GetReference(InternalGetSpan(start - 1, lenOfLen)), len, lenOfLen);
}
Span<byte> InternalGetSpan(uint start, uint len)
{
if (HeapBuffer != null)
{
return HeapBuffer.AsSpan((int)start, (int)len);
}
return InitialBuffer.Slice((int)start, (int)len);
}
public void UpdateBuffer(ReadOnlySpan<byte> writtenBuffer)
{
if (Unsafe.AreSame(ref MemoryMarshal.GetReference(InitialBuffer), ref MemoryMarshal.GetReference(writtenBuffer)))
{
Buf = InitialBuffer.Slice(writtenBuffer.Length);
HeapBuffer = null;
}
else
{
Reset();
WriteBlock(writtenBuffer);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using CorruptIndexException = Lucene.Net.Index.CorruptIndexException;
using QueryParser = Lucene.Net.QueryParsers.QueryParser;
using Explanation = Lucene.Net.Search.Explanation;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using Query = Lucene.Net.Search.Query;
using QueryUtils = Lucene.Net.Search.QueryUtils;
using TopDocs = Lucene.Net.Search.TopDocs;
using Lucene.Net.Search;
using Lucene.Net.Index;
namespace Lucene.Net.Search.Function
{
/// <summary> Test CustomScoreQuery search.</summary>
[TestFixture]
public class TestCustomScoreQuery:FunctionTestSetup
{
/* @override constructor */
public TestCustomScoreQuery(System.String name):base(name, true)
{
}
public TestCustomScoreQuery()
: base()
{
}
/// <summary>Test that CustomScoreQuery of Type.BYTE returns the expected scores. </summary>
[Test]
public virtual void TestCustomScoreByte()
{
// INT field values are small enough to be parsed as byte
DoTestCustomScore(INT_FIELD, FieldScoreQuery.Type.BYTE, 1.0);
DoTestCustomScore(INT_FIELD, FieldScoreQuery.Type.BYTE, 2.0);
}
/// <summary>Test that CustomScoreQuery of Type.SHORT returns the expected scores. </summary>
[Test]
public virtual void TestCustomScoreShort()
{
// INT field values are small enough to be parsed as short
DoTestCustomScore(INT_FIELD, FieldScoreQuery.Type.SHORT, 1.0);
DoTestCustomScore(INT_FIELD, FieldScoreQuery.Type.SHORT, 3.0);
}
/// <summary>Test that CustomScoreQuery of Type.INT returns the expected scores. </summary>
[Test]
public virtual void TestCustomScoreInt()
{
DoTestCustomScore(INT_FIELD, FieldScoreQuery.Type.INT, 1.0);
DoTestCustomScore(INT_FIELD, FieldScoreQuery.Type.INT, 4.0);
}
/// <summary>Test that CustomScoreQuery of Type.FLOAT returns the expected scores. </summary>
[Test]
public virtual void TestCustomScoreFloat()
{
// INT field can be parsed as float
DoTestCustomScore(INT_FIELD, FieldScoreQuery.Type.FLOAT, 1.0);
DoTestCustomScore(INT_FIELD, FieldScoreQuery.Type.FLOAT, 5.0);
// same values, but in float format
DoTestCustomScore(FLOAT_FIELD, FieldScoreQuery.Type.FLOAT, 1.0);
DoTestCustomScore(FLOAT_FIELD, FieldScoreQuery.Type.FLOAT, 6.0);
}
// must have static class otherwise serialization tests fail
[Serializable]
private class CustomAddQuery:CustomScoreQuery
{
// constructor
internal CustomAddQuery(Query q, ValueSourceQuery qValSrc):base(q, qValSrc)
{
}
/*(non-Javadoc) @see Lucene.Net.Search.Function.CustomScoreQuery#name() */
public override System.String Name()
{
return "customAdd";
}
protected override CustomScoreProvider GetCustomScoreProvider(IndexReader reader)
{
return new AnonymousCustomScoreProvider(reader);
}
class AnonymousCustomScoreProvider : CustomScoreProvider
{
IndexReader reader;
public AnonymousCustomScoreProvider(IndexReader reader) : base(reader)
{
this.reader = reader;
}
public override float CustomScore(int doc, float subQueryScore, float valSrcScore)
{
return subQueryScore + valSrcScore;
}
public override Explanation CustomExplain(int doc, Explanation subQueryExpl, Explanation valSrcExpl)
{
float valSrcScore = valSrcExpl == null ? 0 : valSrcExpl.GetValue();
Explanation exp = new Explanation(valSrcScore + subQueryExpl.GetValue(), "custom score: sum of:");
exp.AddDetail(subQueryExpl);
if (valSrcExpl != null)
{
exp.AddDetail(valSrcExpl);
}
return exp;
}
}
}
// must have static class otherwise serialization tests fail
[Serializable]
private class CustomMulAddQuery:CustomScoreQuery
{
// constructor
internal CustomMulAddQuery(Query q, ValueSourceQuery qValSrc1, ValueSourceQuery qValSrc2):base(q, new ValueSourceQuery[]{qValSrc1, qValSrc2})
{
}
/*(non-Javadoc) @see Lucene.Net.Search.Function.CustomScoreQuery#name() */
public override System.String Name()
{
return "customMulAdd";
}
/*(non-Javadoc) @see Lucene.Net.Search.Function.CustomScoreQuery#customScore(int, float, float) */
protected override CustomScoreProvider GetCustomScoreProvider(IndexReader reader)
{
return new AnonymousCustomScoreProvider(reader);
}
class AnonymousCustomScoreProvider : CustomScoreProvider
{
IndexReader reader;
public AnonymousCustomScoreProvider(IndexReader reader) : base(reader)
{
this.reader = reader;
}
public override float CustomScore(int doc, float subQueryScore, float[] valSrcScores)
{
if (valSrcScores.Length == 0)
{
return subQueryScore;
}
if (valSrcScores.Length == 1)
{
return subQueryScore + valSrcScores[0];
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
}
return (subQueryScore + valSrcScores[0]) * valSrcScores[1]; // we know there are two
}
public override Explanation CustomExplain(int doc, Explanation subQueryExpl, Explanation[] valSrcExpls)
{
if (valSrcExpls.Length == 0)
{
return subQueryExpl;
}
Explanation exp = new Explanation(valSrcExpls[0].GetValue() + subQueryExpl.GetValue(), "sum of:");
exp.AddDetail(subQueryExpl);
exp.AddDetail(valSrcExpls[0]);
if (valSrcExpls.Length == 1)
{
exp.SetDescription("CustomMulAdd, sum of:");
return exp;
}
Explanation exp2 = new Explanation(valSrcExpls[1].GetValue() * exp.GetValue(), "custom score: product of:");
exp2.AddDetail(valSrcExpls[1]);
exp2.AddDetail(exp);
return exp2;
}
}
}
private class CustomExternalQuery : CustomScoreQuery
{
protected override CustomScoreProvider GetCustomScoreProvider(IndexReader reader)
{
int[] values = FieldCache_Fields.DEFAULT.GetInts(reader, INT_FIELD);
return new AnonymousCustomScoreProvider(reader,values);
}
class AnonymousCustomScoreProvider : CustomScoreProvider
{
IndexReader reader;
int[] values = null;
public AnonymousCustomScoreProvider(IndexReader reader, int[] values) : base(reader)
{
this.reader = reader;
this.values = values;
}
public override float CustomScore(int doc, float subScore, float valSrcScore)
{
Assert.IsTrue(doc <= reader.MaxDoc());
return (float)values[doc];
}
}
public CustomExternalQuery(Query q) : base(q)
{ }
}
[Test]
public void TestCustomExternalQuery()
{
QueryParser qp = new QueryParser(TEXT_FIELD,anlzr);
String qtxt = "first aid text"; // from the doc texts in FunctionQuerySetup.
Query q1 = qp.Parse(qtxt);
Query q = new CustomExternalQuery(q1);
Log(q);
IndexSearcher s = new IndexSearcher(dir);
TopDocs hits = s.Search(q, 1000);
Assert.AreEqual(N_DOCS, hits.TotalHits);
for(int i=0;i<N_DOCS;i++)
{
int doc = hits.ScoreDocs[i].doc;
float score = hits.ScoreDocs[i].score;
Assert.AreEqual(score, (float)1 + (4 * doc) % N_DOCS, 0.0001, "doc=" + doc);
}
s.Close();
}
// Test that FieldScoreQuery returns docs with expected score.
private void DoTestCustomScore(System.String field, FieldScoreQuery.Type tp, double dboost)
{
float boost = (float) dboost;
IndexSearcher s = new IndexSearcher(dir);
FieldScoreQuery qValSrc = new FieldScoreQuery(field, tp); // a query that would score by the field
QueryParser qp = new QueryParser(TEXT_FIELD, anlzr);
System.String qtxt = "first aid text"; // from the doc texts in FunctionQuerySetup.
// regular (boolean) query.
Query q1 = qp.Parse(qtxt);
Log(q1);
// custom query, that should score the same as q1.
CustomScoreQuery q2CustomNeutral = new CustomScoreQuery(q1);
q2CustomNeutral.SetBoost(boost);
Log(q2CustomNeutral);
// custom query, that should (by default) multiply the scores of q1 by that of the field
CustomScoreQuery q3CustomMul = new CustomScoreQuery(q1, qValSrc);
q3CustomMul.SetStrict(true);
q3CustomMul.SetBoost(boost);
Log(q3CustomMul);
// custom query, that should add the scores of q1 to that of the field
CustomScoreQuery q4CustomAdd = new CustomAddQuery(q1, qValSrc);
q4CustomAdd.SetStrict(true);
q4CustomAdd.SetBoost(boost);
Log(q4CustomAdd);
// custom query, that multiplies and adds the field score to that of q1
CustomScoreQuery q5CustomMulAdd = new CustomMulAddQuery(q1, qValSrc, qValSrc);
q5CustomMulAdd.SetStrict(true);
q5CustomMulAdd.SetBoost(boost);
Log(q5CustomMulAdd);
// do al the searches
TopDocs td1 = s.Search(q1, null, 1000);
TopDocs td2CustomNeutral = s.Search(q2CustomNeutral, null, 1000);
TopDocs td3CustomMul = s.Search(q3CustomMul, null, 1000);
TopDocs td4CustomAdd = s.Search(q4CustomAdd, null, 1000);
TopDocs td5CustomMulAdd = s.Search(q5CustomMulAdd, null, 1000);
// put results in map so we can verify the scores although they have changed
System.Collections.Hashtable h1 = TopDocsToMap(td1);
System.Collections.Hashtable h2CustomNeutral = TopDocsToMap(td2CustomNeutral);
System.Collections.Hashtable h3CustomMul = TopDocsToMap(td3CustomMul);
System.Collections.Hashtable h4CustomAdd = TopDocsToMap(td4CustomAdd);
System.Collections.Hashtable h5CustomMulAdd = TopDocsToMap(td5CustomMulAdd);
VerifyResults(boost, s, h1, h2CustomNeutral, h3CustomMul, h4CustomAdd, h5CustomMulAdd, q1, q2CustomNeutral, q3CustomMul, q4CustomAdd, q5CustomMulAdd);
}
// verify results are as expected.
private void VerifyResults(float boost, IndexSearcher s, System.Collections.Hashtable h1, System.Collections.Hashtable h2customNeutral, System.Collections.Hashtable h3CustomMul, System.Collections.Hashtable h4CustomAdd, System.Collections.Hashtable h5CustomMulAdd, Query q1, Query q2, Query q3, Query q4, Query q5)
{
// verify numbers of matches
Log("#hits = " + h1.Count);
Assert.AreEqual(h1.Count, h2customNeutral.Count, "queries should have same #hits");
Assert.AreEqual(h1.Count, h3CustomMul.Count, "queries should have same #hits");
Assert.AreEqual(h1.Count, h4CustomAdd.Count, "queries should have same #hits");
Assert.AreEqual(h1.Count, h5CustomMulAdd.Count, "queries should have same #hits");
// verify scores ratios
for (System.Collections.IEnumerator it = h1.Keys.GetEnumerator(); it.MoveNext(); )
{
System.Int32 x = (System.Int32) it.Current;
int doc = x;
Log("doc = " + doc);
float fieldScore = ExpectedFieldScore(s.GetIndexReader().Document(doc).Get(ID_FIELD));
Log("fieldScore = " + fieldScore);
Assert.IsTrue(fieldScore > 0, "fieldScore should not be 0");
float score1 = (float) ((System.Single) h1[x]);
LogResult("score1=", s, q1, doc, score1);
float score2 = (float) ((System.Single) h2customNeutral[x]);
LogResult("score2=", s, q2, doc, score2);
Assert.AreEqual(boost * score1, score2, TEST_SCORE_TOLERANCE_DELTA, "same score (just boosted) for neutral");
float score3 = (float) ((System.Single) h3CustomMul[x]);
LogResult("score3=", s, q3, doc, score3);
Assert.AreEqual(boost * fieldScore * score1, score3, TEST_SCORE_TOLERANCE_DELTA, "new score for custom mul");
float score4 = (float) ((System.Single) h4CustomAdd[x]);
LogResult("score4=", s, q4, doc, score4);
Assert.AreEqual(boost * (fieldScore + score1), score4, TEST_SCORE_TOLERANCE_DELTA, "new score for custom add");
float score5 = (float) ((System.Single) h5CustomMulAdd[x]);
LogResult("score5=", s, q5, doc, score5);
Assert.AreEqual(boost * fieldScore * (score1 + fieldScore), score5, TEST_SCORE_TOLERANCE_DELTA, "new score for custom mul add");
}
}
private void LogResult(System.String msg, IndexSearcher s, Query q, int doc, float score1)
{
QueryUtils.Check(q, s);
Log(msg + " " + score1);
Log("Explain by: " + q);
Log(s.Explain(q, doc));
}
// since custom scoring modifies the order of docs, map results
// by doc ids so that we can later compare/verify them
private System.Collections.Hashtable TopDocsToMap(TopDocs td)
{
System.Collections.Hashtable h = new System.Collections.Hashtable();
for (int i = 0; i < td.TotalHits; i++)
{
h[(System.Int32) td.ScoreDocs[i].doc] = (float) td.ScoreDocs[i].score;
}
return h;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using GuruComponents.Netrix.ComInterop;
using System.Web.UI.Design;
using GuruComponents.Netrix.Events;
using GuruComponents.Netrix.WebEditing.Elements;
using System.ComponentModel.Design;
namespace GuruComponents.Netrix.XmlDesigner
{
/// <summary>
/// The purpose of this class is to deal with the events a control will
/// fire at design time.
/// </summary>
internal sealed class EventSink : Interop.IHTMLGenericEvents
{
public static readonly string DesignTimeLockAttribute;
internal event ElementEventHandler ElementEvent;
private ViewLink _behavior;
private Interop.IHTMLElement _element;
private XmlControl _control;
private ConnectionPointCookie _eventSinkCookie;
private IHtmlEditor _editor;
private Interop.IHTMLDocument2 _document;
private int _oldWidth;
private int _oldHeight;
private Interop.IHTMLEventObj _eventobj;
private bool _elementMoving = false;
private bool _elementLocked = false;
private object _elementLockedTop;
private object _elementLockedLeft;
private bool _allowResize = true;
static EventSink()
{
EventSink.DesignTimeLockAttribute = "Design_Time_Lock";
}
public EventSink(ViewLink behavior)
{
this._behavior = behavior;
}
private ControlDesigner Designer
{
get
{
return (ControlDesigner)_behavior.Designer;
}
}
/// <summary>
/// Connects the specified control and its underlying element to the event sink.
/// </summary>
/// <param name="control">Control to connect.</param>
/// <param name="element">Underlying element of control.</param>
/// <param name="editor"></param>
public void Connect(XmlControl control, Interop.IHTMLElement element, IHtmlEditor editor)
{
if (editor == null || control == null)
{
throw new NullReferenceException("Parameter does not allow null values");
}
this._editor = editor;
this._control = control;
try
{
this._element = element;
this._eventSinkCookie = new ConnectionPointCookie(this._element, this, typeof(Interop.IHTMLElementEvents));
//this._eventSinkCookie = new ConnectionPointCookie(this._element, this, typeof(Interop.IHTMLTextContainerEvents));
}
catch (Exception)
{
}
}
public void Disconnect()
{
if (this._eventSinkCookie != null)
{
this._eventSinkCookie.Disconnect();
this._eventSinkCookie = null;
}
this._element = null;
this._behavior = null;
}
private Interop.IHTMLEventObj GetEventObject()
{
if (_element == null) return null;
try
{
_document = (Interop.IHTMLDocument2)this._element.GetDocument();
Interop.IHTMLWindow2 window1 = _document.GetParentWindow();
return window1.@event;
}
catch
{
return null;
}
}
void Interop.IHTMLGenericEvents.Bogus1()
{
}
void Interop.IHTMLGenericEvents.Bogus2()
{
}
void Interop.IHTMLGenericEvents.Bogus3()
{
}
void Interop.IHTMLGenericEvents.Invoke(int dispid, ref Guid g, int lcid, int dwFlags, Interop.DISPPARAMS pdp, object[] pvarRes, Interop.EXCEPINFO pei, int[] nArgError)
{
nArgError = new int[] { Interop.S_FALSE };
_eventobj = this.GetEventObject();
if (_eventobj != null && _eventobj.srcElement != null)
{
//System.Diagnostics.Debug.WriteLineIf(_eventobj.srcElement != null, _eventobj.type, " EVENTSINK " + _eventobj.srcElement.GetTagName());
if (ElementEvent != null) {
ElementEvent(this, _eventobj);
}
switch (_eventobj.type)
{
case "help":
break;
case "click":
_control.InvokeClick(_eventobj);
break;
case "dblclick":
_control.InvokeDblClick(_eventobj);
break;
case "keypress":
_control.InvokeKeyPress(_eventobj);
break;
case "keydown":
break;
case "keyup":
break;
case "mouseout":
_control.InvokeMouseOut(_eventobj);
break;
case "mouseover":
_control.InvokeMouseOver(_eventobj);
break;
case "mousemove":
_control.InvokeMouseMove(_eventobj);
break;
case "mousedown":
_control.InvokeMouseDown(_eventobj);
break;
case "mouseup":
_control.InvokeMouseUp(_eventobj);
break;
case "selectstart":
_control.InvokeSelectStart(_eventobj);
break;
case "filterchange":
_control.InvokeFilterChange(_eventobj);
break;
case "dragstart":
_control.InvokeDragStart(_eventobj);
break;
case "beforeupdate":
break;
case "afterupdate":
break;
case "errorupdate":
break;
case "rowexit":
break;
case "rowenter":
break;
case "datasetchanged":
break;
case "dataavailable":
break;
case "datasetcomplete":
break;
case "losecapture":
_control.InvokeLoseCapture(_eventobj);
break;
case "propertychange":
_control.InvokePropertyChange(_eventobj);
break;
case "scroll":
_control.InvokeScroll(_eventobj);
break;
case "focus":
_control.InvokeFocus(_eventobj);
break;
case "blur":
_control.InvokeBlur(_eventobj);
break;
case "resize":
_control.InvokeResize(_eventobj);
OnResize();
break;
case "drag":
_control.InvokeDrag(_eventobj);
break;
case "dragend":
_control.InvokeDragEnd(_eventobj);
break;
case "dragenter":
_control.InvokeDragEnter(_eventobj);
break;
case "dragover":
_control.InvokeDragOver(_eventobj);
break;
case "dragleave":
_control.InvokeDragLeave(_eventobj);
break;
case "drop":
_control.InvokeDrop(_eventobj);
break;
case "beforecut":
_control.InvokeBeforeCut(_eventobj);
break;
case "cut":
_control.InvokeCut(_eventobj);
break;
case "beforecopy":
_control.InvokeBeforeCopy(_eventobj);
break;
case "copy":
_control.InvokeCopy(_eventobj);
break;
case "beforepaste":
_control.InvokeBeforePaste(_eventobj);
break;
case "paste":
_control.InvokePaste(_eventobj);
break;
case "contextmenu":
_control.InvokeContextMenu(_eventobj);
break;
case "rowsdelete":
break;
case "rowsinserted":
break;
case "cellchange":
break;
case "readystatechange":
break;
case "beforeeditfocus":
_control.InvokeEditFocus(_eventobj);
break;
case "layoutcomplete":
_control.InvokeLayoutComplete(_eventobj);
break;
case "page":
_control.InvokePage(_eventobj);
break;
case "beforedeactivate":
_control.InvokeBeforeDeactivate(_eventobj);
break;
case "beforeactivate":
_control.InvokeBeforeActivate(_eventobj);
break;
case "move":
_control.InvokeMove(_eventobj);
break;
case "controlselect":
_control.InvokeControlSelect(_eventobj);
break;
case "movestart":
_control.InvokeMoveStart(_eventobj);
OnMoveStart();
break;
case "moveend":
_control.InvokeMoveEnd(_eventobj);
OnMoveEnd();
break;
case "resizestart":
_control.InvokeResizeStart(_eventobj);
OnResizeStart();
break;
case "resizeend":
_control.InvokeResizeEnd(_eventobj);
break;
case "mouseenter":
_control.InvokeMouseEnter(_eventobj);
break;
case "mouseleave":
_control.InvokeMouseLeave(_eventobj);
break;
case "mousewheel":
_control.InvokeMouseWheel(_eventobj);
break;
case "activate":
_control.InvokeActivate(_eventobj);
break;
case "deactivate":
_control.InvokeDeactivate(_eventobj);
break;
case "focusin":
_control.InvokeFocusIn(_eventobj);
break;
case "focusout":
_control.InvokeFocusOut(_eventobj);
break;
case "load":
_control.InvokeLoad(_eventobj);
break;
case "error":
_control.InvokeError(_eventobj);
break;
case "change":
_control.InvokeChange(_eventobj);
break;
case "abort":
_control.InvokeAbort(_eventobj);
break;
case "select":
_control.InvokeSelect(_eventobj);
break;
case "selectionchange":
_control.InvokeSelectionChange(_eventobj);
break;
case "stop":
_control.InvokeStop(_eventobj);
break;
case "reset":
break;
case "submit":
break;
}
}
}
private void OnMoveEnd()
{
if (this._elementMoving)
{
this._elementMoving = false;
if (this._elementLocked)
{
Interop.IHTMLStyle style1 = this._element.GetStyle();
if (style1 != null)
{
style1.SetTop(this._elementLockedTop);
style1.SetLeft(this._elementLockedLeft);
}
this._elementLocked = false;
}
DocumentEventArgs e = new DocumentEventArgs(_eventobj, _control);
_control.OnMoveEnd(e);
}
}
private void OnMoveStart()
{
Interop.IHTMLElement2 element1 = (Interop.IHTMLElement2)this._element;
Interop.IHTMLCurrentStyle style1 = element1.GetCurrentStyle();
string text1 = style1.position;
if ((text1 != null) && (string.Compare(text1, "absolute", true) == 0))
{
this._elementMoving = true;
}
if (this._elementMoving)
{
object[] objArray1 = new object[1];
this._element.GetAttribute(EventSink.DesignTimeLockAttribute, 0, objArray1);
if (objArray1[0] == null)
{
objArray1[0] = style1.getAttribute(EventSink.DesignTimeLockAttribute, 0);
}
if ((objArray1[0] != null) && (objArray1[0] is string))
{
this._elementLocked = true;
this._elementLockedTop = style1.top;
this._elementLockedLeft = style1.left;
}
}
}
private void OnResize()
{
if (!this.AllowResize) return;
Interop.IHTMLStyle style1 = this._element.GetStyle();
int width = style1.GetPixelWidth();
int height = style1.GetPixelHeight();
if (height == 0)
{
height = this._element.GetOffsetHeight();
}
if (width == 0)
{
width = this._element.GetOffsetWidth();
}
if ((height != 0) || (width != 0))
{
//style1.RemoveAttribute("width", 0);
//style1.RemoveAttribute("height", 0);
//System.Web.UI.WebControls.WebControl control1 = this._behavior.Control as System.Web.UI.WebControls.WebControl;
if (this._control != null)
{
if (height != this._oldHeight)
{
this._control.Height = System.Web.UI.WebControls.Unit.Pixel(height);
}
if (width != this._oldWidth)
{
this._control.Width = System.Web.UI.WebControls.Unit.Pixel(width);
}
}
this._oldHeight = height;
this._oldWidth = width;
IComponentChangeService service1 = (IComponentChangeService)this._editor.ServiceProvider.GetService(typeof(IComponentChangeService));
if (service1 != null)
{
service1.OnComponentChanged(this._control, null, null, null);
}
//if (!this.Designer.ReadOnly)
{
style1.SetWidth(width);
style1.SetHeight(height);
}
//((Interop.IHTMLElement2)_element).GetRuntimeStyle().SetOverflow("visible");
//_behavior.OnContentSave();
}
}
private void OnResizeStart()
{
bool canresize = this.AllowResize;
if (!canresize)
{
_eventobj.cancelBubble = true;
_eventobj.returnValue = false;
}
this._oldWidth = ((Interop.IHTMLElement2)this._element).GetClientWidth();
this._oldHeight = ((Interop.IHTMLElement2)this._element).GetClientHeight();
}
/// <summary>
/// Gets <c>true</c>, when resizing is allowed. The property responds
/// to the internally forced setting, if set to <c>false</c>. Otherwise it
/// calls the underlying ControlDesigner to
/// get the appropriate property.
/// </summary>
internal bool AllowResize
{
get
{
bool ar = true;
if (this.Designer != null)
{
ar = this.Designer.AllowResize;
}
if (this._allowResize)
{
return ar;
}
return false;
}
set
{
this._allowResize = value;
}
}
}
}
| |
// <copyright file="LUTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 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>
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Factorization
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// LU factorization tests for a dense matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class LUTests
{
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var factorLU = matrixI.LU();
// Check lower triangular part.
var matrixL = factorLU.L;
Assert.AreEqual(matrixI.RowCount, matrixL.RowCount);
Assert.AreEqual(matrixI.ColumnCount, matrixL.ColumnCount);
for (var i = 0; i < matrixL.RowCount; i++)
{
for (var j = 0; j < matrixL.ColumnCount; j++)
{
Assert.AreEqual(i == j ? Complex.One : Complex.Zero, matrixL[i, j]);
}
}
// Check upper triangular part.
var matrixU = factorLU.U;
Assert.AreEqual(matrixI.RowCount, matrixU.RowCount);
Assert.AreEqual(matrixI.ColumnCount, matrixU.ColumnCount);
for (var i = 0; i < matrixU.RowCount; i++)
{
for (var j = 0; j < matrixU.ColumnCount; j++)
{
Assert.AreEqual(i == j ? Complex.One : Complex.Zero, matrixU[i, j]);
}
}
}
/// <summary>
/// LU factorization fails with a non-square matrix.
/// </summary>
[Test]
public void LUFailsWithNonSquareMatrix()
{
var matrix = new DenseMatrix(3, 2);
Assert.That(() => matrix.LU(), Throws.ArgumentException);
}
/// <summary>
/// Identity determinant is one.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void IdentityDeterminantIsOne(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var lu = matrixI.LU();
Assert.AreEqual(Complex.One, lu.Determinant);
}
/// <summary>
/// Can factorize a random square matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanFactorizeRandomMatrix(int order)
{
var matrixX = Matrix<Complex>.Build.Random(order, order, 1);
var factorLU = matrixX.LU();
var matrixL = factorLU.L;
var matrixU = factorLU.U;
// Make sure the factors have the right dimensions.
Assert.AreEqual(order, matrixL.RowCount);
Assert.AreEqual(order, matrixL.ColumnCount);
Assert.AreEqual(order, matrixU.RowCount);
Assert.AreEqual(order, matrixU.ColumnCount);
// Make sure the L factor is lower triangular.
for (var i = 0; i < matrixL.RowCount; i++)
{
Assert.AreEqual(Complex.One, matrixL[i, i]);
for (var j = i + 1; j < matrixL.ColumnCount; j++)
{
Assert.AreEqual(Complex.Zero, matrixL[i, j]);
}
}
// Make sure the U factor is upper triangular.
for (var i = 0; i < matrixL.RowCount; i++)
{
for (var j = 0; j < i; j++)
{
Assert.AreEqual(Complex.Zero, matrixU[i, j]);
}
}
// Make sure the LU factor times it's transpose is the original matrix.
var matrixXfromLU = matrixL * matrixU;
var permutationInverse = factorLU.P.Inverse();
matrixXfromLU.PermuteRows(permutationInverse);
for (var i = 0; i < matrixXfromLU.RowCount; i++)
{
for (var j = 0; j < matrixXfromLU.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(matrixX[i, j], matrixXfromLU[i, j], 9);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var vectorb = Vector<Complex>.Build.Random(order, 1);
var resultx = factorLU.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixB = Matrix<Complex>.Build.Random(order, order, 1);
var matrixX = factorLU.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var vectorb = Vector<Complex>.Build.Random(order, 1);
var vectorbCopy = vectorb.Clone();
var resultx = new DenseVector(order);
factorLU.Solve(vectorb, resultx);
Assert.AreEqual(vectorb.Count, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="order">Matrix row number.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixB = Matrix<Complex>.Build.Random(order, order, 1);
var matrixBCopy = matrixB.Clone();
var matrixX = new DenseMatrix(order, order);
factorLU.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
/// <summary>
/// Can inverse a matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanInverse(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixAInverse = factorLU.Inverse();
// The inverse dimension is equal A
Assert.AreEqual(matrixAInverse.RowCount, matrixAInverse.RowCount);
Assert.AreEqual(matrixAInverse.ColumnCount, matrixAInverse.ColumnCount);
var matrixIdentity = matrixA * matrixAInverse;
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Check if multiplication of A and AI produced identity matrix.
for (var i = 0; i < matrixIdentity.RowCount; i++)
{
AssertHelpers.AlmostEqualRelative(matrixIdentity[i, i], Complex.One, 9);
}
}
}
}
| |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien ([email protected])
// 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 Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using NHibernate.Criterion;
namespace Rhino.Commons
{
public class RepositoryDecorator<T> : IRepository<T>
{
private IRepository<T> inner;
public RepositoryDecorator()
{
}
public RepositoryDecorator(IRepository<T> inner)
{
Inner = inner;
}
public IRepository<T> Inner
{
get { return inner; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
inner = value;
}
}
public virtual T Get(object id)
{
return inner.Get(id);
}
public virtual T Load(object id)
{
return inner.Load(id);
}
public virtual void Delete(T entity)
{
inner.Delete(entity);
}
public virtual void DeleteAll()
{
inner.DeleteAll();
}
public virtual void DeleteAll(DetachedCriteria criteria)
{
inner.DeleteAll(criteria);
}
public virtual T Save(T entity)
{
return inner.Save(entity);
}
public virtual T SaveOrUpdate(T entity)
{
return inner.SaveOrUpdate(entity);
}
public virtual T SaveOrUpdateCopy(T entity)
{
return inner.SaveOrUpdateCopy(entity);
}
public virtual void Update(T entity)
{
inner.Update(entity);
}
public virtual ICollection<T> FindAll(Order order, params ICriterion[] criteria)
{
return inner.FindAll(order, criteria);
}
public virtual ICollection<T> FindAll(DetachedCriteria criteria, params Order[] orders)
{
return inner.FindAll(criteria, orders);
}
public virtual ICollection<T> FindAll(DetachedCriteria criteria,
int firstResult, int maxResults,
params Order[] orders)
{
return inner.FindAll(criteria, firstResult, maxResults, orders);
}
public virtual ICollection<T> FindAll(Order[] orders, params ICriterion[] criteria)
{
return inner.FindAll(orders, criteria);
}
public virtual ICollection<T> FindAll(params ICriterion[] criteria)
{
return inner.FindAll(criteria);
}
public virtual ICollection<T> FindAll(int firstResult, int numberOfResults, params ICriterion[] criteria)
{
return inner.FindAll(firstResult, numberOfResults, criteria);
}
public virtual ICollection<T> FindAll(int firstResult, int numberOfResults,
Order selectionOrder,
params ICriterion[] criteria)
{
return inner.FindAll(firstResult, numberOfResults, selectionOrder, criteria);
}
public virtual ICollection<T> FindAll(int firstResult, int numberOfResults,
Order[] selectionOrder,
params ICriterion[] criteria)
{
return inner.FindAll(firstResult, numberOfResults, selectionOrder, criteria);
}
public virtual ICollection<T> FindAll(string namedQuery, params Parameter[] parameters)
{
return inner.FindAll(namedQuery, parameters);
}
public virtual ICollection<T> FindAll(int firstResult, int numberOfResults,
string namedQuery, params Parameter[] parameters)
{
return inner.FindAll(firstResult, numberOfResults, namedQuery, parameters);
}
public virtual T FindOne(params ICriterion[] criteria)
{
return inner.FindOne(criteria);
}
public virtual T FindOne(DetachedCriteria criteria)
{
return inner.FindOne(criteria);
}
public virtual T FindOne(string namedQuery, params Parameter[] parameters)
{
return inner.FindOne(namedQuery, parameters);
}
public virtual T FindFirst(DetachedCriteria criteria, params Order[] orders)
{
return inner.FindFirst(criteria, orders);
}
public virtual T FindFirst(params Order[] orders)
{
return inner.FindFirst(orders);
}
public virtual object ExecuteStoredProcedure(string sp_name, params Parameter[] parameters)
{
return inner.ExecuteStoredProcedure(sp_name, parameters);
}
public virtual ICollection<T2> ExecuteStoredProcedure<T2>(Converter<IDataReader, T2> converter,
string sp_name, params Parameter[] parameters)
{
return inner.ExecuteStoredProcedure(converter, sp_name, parameters);
}
public virtual bool Exists(DetachedCriteria criteria)
{
return inner.Exists(criteria);
}
public virtual bool Exists()
{
return inner.Exists();
}
public virtual long Count(DetachedCriteria criteria)
{
return inner.Count(criteria);
}
public virtual long Count()
{
return inner.Count();
}
public virtual ProjT ReportOne<ProjT>(DetachedCriteria criteria,
ProjectionList projectionList)
{
return inner.ReportOne<ProjT>(criteria, projectionList);
}
public virtual ProjT ReportOne<ProjT>(ProjectionList projectionList,
params ICriterion[] criteria)
{
return inner.ReportOne<ProjT>(projectionList, criteria);
}
public virtual ICollection<ProjT> ReportAll<ProjT>(ProjectionList projectionList)
{
return ReportAll<ProjT>(projectionList);
}
public virtual ICollection<ProjT> ReportAll<ProjT>(DetachedCriteria criteria,
ProjectionList projectionList)
{
return inner.ReportAll<ProjT>(criteria, projectionList);
}
public virtual ICollection<ProjT> ReportAll<ProjT>(DetachedCriteria criteria,
ProjectionList projectionList,
params Order[] orders)
{
return inner.ReportAll<ProjT>(criteria, projectionList, orders);
}
public virtual ICollection<ProjT> ReportAll<ProjT>(ProjectionList projectionList,
params ICriterion[] criterion)
{
return inner.ReportAll<ProjT>(projectionList, criterion);
}
public virtual ICollection<ProjT> ReportAll<ProjT>(ProjectionList projectionList,
Order[] orders,
params ICriterion[] criteria)
{
return inner.ReportAll<ProjT>(projectionList, orders, criteria);
}
public virtual ICollection<ProjT> ReportAll<ProjT>(ProjectionList projectionList,
params Order[] orders)
{
return inner.ReportAll<ProjT>(projectionList, orders);
}
public virtual ICollection<ProjT> ReportAll<ProjT>(ProjectionList projectionList,
bool distinctResults)
{
return inner.ReportAll<ProjT>(projectionList, distinctResults);
}
public virtual ICollection<ProjJ> ReportAll<ProjJ>(string namedQuery,
params Parameter[] parameters)
{
return inner.ReportAll<ProjJ>(namedQuery, parameters);
}
public virtual DetachedCriteria CreateDetachedCriteria()
{
return inner.CreateDetachedCriteria();
}
public virtual DetachedCriteria CreateDetachedCriteria(string alias)
{
return inner.CreateDetachedCriteria(alias);
}
public virtual T Create()
{
return inner.Create();
}
public virtual FutureValue<T> FutureGet(object id)
{
return inner.FutureGet(id);
}
public virtual FutureValue<T> FutureLoad(object id)
{
return inner.FutureLoad(id);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Xunit;
namespace System.Linq.Tests
{
public partial class ToLookupTests : EnumerableTests
{
private static void AssertMatches<K, T>(IEnumerable<K> keys, IEnumerable<T> elements, System.Linq.ILookup<K, T> lookup)
{
Assert.NotNull(lookup);
Assert.NotNull(keys);
Assert.NotNull(elements);
int num = 0;
using (IEnumerator<K> keyEnumerator = keys.GetEnumerator())
using (IEnumerator<T> elEnumerator = elements.GetEnumerator())
{
while (keyEnumerator.MoveNext())
{
Assert.True(lookup.Contains(keyEnumerator.Current));
foreach (T e in lookup[keyEnumerator.Current])
{
Assert.True(elEnumerator.MoveNext());
Assert.Equal(e, elEnumerator.Current);
}
++num;
}
Assert.False(elEnumerator.MoveNext());
}
Assert.Equal(num, lookup.Count);
}
[Fact]
public void SameResultsRepeatCall()
{
var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" }
select x1; ;
var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 }
select x2;
var q = from x3 in q1
from x4 in q2
select new { a1 = x3, a2 = x4 };
Assert.Equal(q.ToLookup(e => e.a1), q.ToLookup(e => e.a1));
}
[Fact]
public void NullKeyIncluded()
{
string[] key = { "Chris", "Bob", null, "Tim" };
int[] element = { 50, 95, 55, 90 };
var source = key.Zip(element, (k, e) => new { Name = k, Score = e });
AssertMatches(key, source, source.ToLookup(e => e.Name));
}
[Fact]
public void OneElementCustomComparer()
{
string[] key = { "Chris" };
int[] element = { 50 };
var source = new [] { new {Name = "risCh", Score = 50} };
AssertMatches(key, source, source.ToLookup(e => e.Name, new AnagramEqualityComparer()));
}
[Fact]
public void UniqueElementsElementSelector()
{
string[] key = { "Chris", "Prakash", "Tim", "Robert", "Brian" };
int[] element = { 50, 100, 95, 60, 80 };
var source = new []
{
new { Name = key[0], Score = element[0] },
new { Name = key[1], Score = element[1] },
new { Name = key[2], Score = element[2] },
new { Name = key[3], Score = element[3] },
new { Name = key[4], Score = element[4] }
};
AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score));
}
[Fact]
public void DuplicateKeys()
{
string[] key = { "Chris", "Prakash", "Robert" };
int[] element = { 50, 80, 100, 95, 99, 56 };
var source = new[]
{
new { Name = key[0], Score = element[0] },
new { Name = key[1], Score = element[2] },
new { Name = key[2], Score = element[5] },
new { Name = key[1], Score = element[3] },
new { Name = key[0], Score = element[1] },
new { Name = key[1], Score = element[4] }
};
AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
}
[Fact]
public void RunOnce()
{
string[] key = { "Chris", "Prakash", "Robert" };
int[] element = { 50, 80, 100, 95, 99, 56 };
var source = new[]
{
new { Name = key[0], Score = element[0] },
new { Name = key[1], Score = element[2] },
new { Name = key[2], Score = element[5] },
new { Name = key[1], Score = element[3] },
new { Name = key[0], Score = element[1] },
new { Name = key[1], Score = element[4] }
};
AssertMatches(key, element, source.RunOnce().ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
}
[Fact]
public void Count()
{
string[] key = { "Chris", "Prakash", "Robert" };
int[] element = { 50, 80, 100, 95, 99, 56 };
var source = new[]
{
new { Name = key[0], Score = element[0] },
new { Name = key[1], Score = element[2] },
new { Name = key[2], Score = element[5] },
new { Name = key[1], Score = element[3] },
new { Name = key[0], Score = element[1] },
new { Name = key[1], Score = element[4] }
};
Assert.Equal(3, source.ToLookup(e => e.Name, e => e.Score).Count());
}
[Fact]
public void EmptySource()
{
string[] key = { };
int[] element = { };
var source = key.Zip(element, (k, e) => new { Name = k, Score = e });
AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
}
[Fact]
public void SingleNullKeyAndElement()
{
string[] key = { null };
string[] element = { null };
string[] source = new string[] { null };
AssertMatches(key, element, source.ToLookup(e => e, e => e, EqualityComparer<string>.Default));
}
[Fact]
public void NullSource()
{
IEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10));
}
[Fact]
public void NullSourceExplicitComparer()
{
IEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, EqualityComparer<int>.Default));
}
[Fact]
public void NullSourceElementSelector()
{
IEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, i => i + 2));
}
[Fact]
public void NullSourceElementSelectorExplicitComparer()
{
IEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, i => i + 2, EqualityComparer<int>.Default));
}
[Fact]
public void NullKeySelector()
{
Func<int, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector));
}
[Fact]
public void NullKeySelectorExplicitComparer()
{
Func<int, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, EqualityComparer<int>.Default));
}
[Fact]
public void NullKeySelectorElementSelector()
{
Func<int, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, i => i + 2));
}
[Fact]
public void NullKeySelectorElementSelectorExplicitComparer()
{
Func<int, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, i => i + 2, EqualityComparer<int>.Default));
}
[Fact]
public void NullElementSelector()
{
Func<int, int> elementSelector = null;
AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => Enumerable.Range(0, 1000).ToLookup(i => i / 10, elementSelector));
}
[Fact]
public void NullElementSelectorExplicitComparer()
{
Func<int, int> elementSelector = null;
AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => Enumerable.Range(0, 1000).ToLookup(i => i / 10, elementSelector, EqualityComparer<int>.Default));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void ApplyResultSelectorForGroup(int enumType)
{
//Create test data
var roles = new List<Role>
{
new Role { Id = 1 },
new Role { Id = 2 },
new Role { Id = 3 },
};
var memberships = Enumerable.Range(0, 50).Select(i => new Membership
{
Id = i,
Role = roles[i % 3],
CountMe = i % 3 == 0
});
//Run actual test
var grouping = memberships.GroupBy(
m => m.Role,
(role, mems) => new RoleMetadata
{
Role = role,
CountA = mems.Count(m => m.CountMe),
CountrB = mems.Count(m => !m.CountMe)
});
IEnumerable<RoleMetadata> result;
switch (enumType)
{
case 1:
result = grouping.ToList();
break;
case 2:
result = grouping.ToArray();
break;
default:
result = grouping;
break;
}
var expected = new[]
{
new RoleMetadata {Role = new Role {Id = 1}, CountA = 17, CountrB = 0 },
new RoleMetadata {Role = new Role {Id = 2}, CountA = 0, CountrB = 17 },
new RoleMetadata {Role = new Role {Id = 3}, CountA = 0, CountrB = 16 }
};
Assert.Equal(expected, result);
}
public class Membership
{
public int Id { get; set; }
public Role Role { get; set; }
public bool CountMe { get; set; }
}
public class Role : IEquatable<Role>
{
public int Id { get; set; }
public bool Equals(Role other) => other != null && Id == other.Id;
public override bool Equals(object obj) => Equals(obj as Role);
public override int GetHashCode() => Id;
}
public class RoleMetadata : IEquatable<RoleMetadata>
{
public Role Role { get; set; }
public int CountA { get; set; }
public int CountrB { get; set; }
public bool Equals(RoleMetadata other)
=> other != null && Role.Equals(other.Role) && CountA == other.CountA && CountrB == other.CountrB;
public override bool Equals(object obj) => Equals(obj as RoleMetadata);
public override int GetHashCode() => Role.GetHashCode() * 31 + CountA + CountrB;
}
}
}
| |
//Uncomment the next line to enable debugging (also uncomment it in AstarPath.cs)
//#define ProfileAstar //@SHOWINEDITOR
//#define ASTAR_UNITY_PRO_PROFILER //@SHOWINEDITOR Requires ProfileAstar, profiles section of astar code which will show up in the Unity Pro Profiler.
using System.Collections.Generic;
using System;
using UnityEngine;
namespace Pathfinding {
public class AstarProfiler {
public class ProfilePoint {
//public DateTime lastRecorded;
//public TimeSpan totalTime;
public System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
public int totalCalls;
public long tmpBytes;
public long totalBytes;
}
static readonly Dictionary<string, ProfilePoint> profiles = new Dictionary<string, ProfilePoint>();
static DateTime startTime = DateTime.UtcNow;
public static ProfilePoint[] fastProfiles;
public static string[] fastProfileNames;
private AstarProfiler() {
}
[System.Diagnostics.Conditional("ProfileAstar")]
public static void InitializeFastProfile (string[] profileNames) {
fastProfileNames = new string[profileNames.Length+2];
Array.Copy(profileNames, fastProfileNames, profileNames.Length);
fastProfileNames[fastProfileNames.Length-2] = "__Control1__";
fastProfileNames[fastProfileNames.Length-1] = "__Control2__";
fastProfiles = new ProfilePoint[fastProfileNames.Length];
for (int i = 0; i < fastProfiles.Length; i++) fastProfiles[i] = new ProfilePoint();
}
[System.Diagnostics.Conditional("ProfileAstar")]
public static void StartFastProfile (int tag) {
//profiles.TryGetValue(tag, out point);
fastProfiles[tag].watch.Start();//lastRecorded = DateTime.UtcNow;
}
[System.Diagnostics.Conditional("ProfileAstar")]
public static void EndFastProfile (int tag) {
/*if (!profiles.ContainsKey(tag))
* {
* Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")");
* return;
* }*/
ProfilePoint point = fastProfiles[tag];
point.totalCalls++;
point.watch.Stop();
//DateTime now = DateTime.UtcNow;
//point.totalTime += now - point.lastRecorded;
//fastProfiles[tag] = point;
}
[System.Diagnostics.Conditional("ASTAR_UNITY_PRO_PROFILER")]
public static void EndProfile () {
Profiler.EndSample();
}
[System.Diagnostics.Conditional("ProfileAstar")]
public static void StartProfile (string tag) {
#if ASTAR_UNITY_PRO_PROFILER
Profiler.BeginSample(tag);
#else
//Console.WriteLine ("Profile Start - " + tag);
ProfilePoint point;
profiles.TryGetValue(tag, out point);
if (point == null) {
point = new ProfilePoint();
profiles[tag] = point;
}
point.tmpBytes = GC.GetTotalMemory(false);
point.watch.Start();
//point.lastRecorded = DateTime.UtcNow;
//Debug.Log ("Starting " + tag);
#endif
}
[System.Diagnostics.Conditional("ProfileAstar")]
public static void EndProfile (string tag) {
#if !ASTAR_UNITY_PRO_PROFILER
if (!profiles.ContainsKey(tag)) {
Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")");
return;
}
//Console.WriteLine ("Profile End - " + tag);
//DateTime now = DateTime.UtcNow;
ProfilePoint point = profiles[tag];
//point.totalTime += now - point.lastRecorded;
++point.totalCalls;
point.watch.Stop();
point.totalBytes += GC.GetTotalMemory(false) - point.tmpBytes;
//profiles[tag] = point;
//Debug.Log ("Ending " + tag);
#else
EndProfile();
#endif
}
[System.Diagnostics.Conditional("ProfileAstar")]
public static void Reset () {
profiles.Clear();
startTime = DateTime.UtcNow;
if (fastProfiles != null) {
for (int i = 0; i < fastProfiles.Length; i++) {
fastProfiles[i] = new ProfilePoint();
}
}
}
[System.Diagnostics.Conditional("ProfileAstar")]
public static void PrintFastResults () {
if (fastProfiles == null)
return;
StartFastProfile(fastProfiles.Length-2);
for (int i = 0; i < 1000; i++) {
StartFastProfile(fastProfiles.Length-1);
EndFastProfile(fastProfiles.Length-1);
}
EndFastProfile(fastProfiles.Length-2);
double avgOverhead = fastProfiles[fastProfiles.Length-2].watch.Elapsed.TotalMilliseconds / 1000.0;
TimeSpan endTime = DateTime.UtcNow - startTime;
var output = new System.Text.StringBuilder();
output.Append("============================\n\t\t\t\tProfile results:\n============================\n");
output.Append("Name | Total Time | Total Calls | Avg/Call | Bytes");
//foreach(KeyValuePair<string, ProfilePoint> pair in profiles)
for (int i = 0; i < fastProfiles.Length; i++) {
string name = fastProfileNames[i];
ProfilePoint value = fastProfiles[i];
int totalCalls = value.totalCalls;
double totalTime = value.watch.Elapsed.TotalMilliseconds - avgOverhead*totalCalls;
if (totalCalls < 1) continue;
output.Append("\n").Append(name.PadLeft(10)).Append("| ");
output.Append(totalTime.ToString("0.0 ").PadLeft(10)).Append(value.watch.Elapsed.TotalMilliseconds.ToString("(0.0)").PadLeft(10)).Append("| ");
output.Append(totalCalls.ToString().PadLeft(10)).Append("| ");
output.Append((totalTime / totalCalls).ToString("0.000").PadLeft(10));
/* output.Append("\nProfile");
* output.Append(name);
* output.Append(" took \t");
* output.Append(totalTime.ToString("0.0"));
* output.Append(" ms to complete over ");
* output.Append(totalCalls);
* output.Append(" iteration");
* if (totalCalls != 1) output.Append("s");
* output.Append(", averaging \t");
* output.Append((totalTime / totalCalls).ToString("0.000"));
* output.Append(" ms per call"); */
}
output.Append("\n\n============================\n\t\tTotal runtime: ");
output.Append(endTime.TotalSeconds.ToString("F3"));
output.Append(" seconds\n============================");
Debug.Log(output.ToString());
}
[System.Diagnostics.Conditional("ProfileAstar")]
public static void PrintResults () {
TimeSpan endTime = DateTime.UtcNow - startTime;
var output = new System.Text.StringBuilder();
output.Append("============================\n\t\t\t\tProfile results:\n============================\n");
int maxLength = 5;
foreach (KeyValuePair<string, ProfilePoint> pair in profiles) {
maxLength = Math.Max(pair.Key.Length, maxLength);
}
output.Append(" Name ".PadRight(maxLength)).
Append("|").Append(" Total Time ".PadRight(20)).
Append("|").Append(" Total Calls ".PadRight(20)).
Append("|").Append(" Avg/Call ".PadRight(20));
foreach (var pair in profiles) {
double totalTime = pair.Value.watch.Elapsed.TotalMilliseconds;
int totalCalls = pair.Value.totalCalls;
if (totalCalls < 1) continue;
string name = pair.Key;
output.Append("\n").Append(name.PadRight(maxLength)).Append("| ");
output.Append(totalTime.ToString("0.0").PadRight(20)).Append("| ");
output.Append(totalCalls.ToString().PadRight(20)).Append("| ");
output.Append((totalTime / totalCalls).ToString("0.000").PadRight(20));
output.Append(AstarMath.FormatBytesBinary((int)pair.Value.totalBytes).PadLeft(10));
/*output.Append("\nProfile ");
* output.Append(pair.Key);
* output.Append(" took ");
* output.Append(totalTime.ToString("0"));
* output.Append(" ms to complete over ");
* output.Append(totalCalls);
* output.Append(" iteration");
* if (totalCalls != 1) output.Append("s");
* output.Append(", averaging ");
* output.Append((totalTime / totalCalls).ToString("0.0"));
* output.Append(" ms per call");*/
}
output.Append("\n\n============================\n\t\tTotal runtime: ");
output.Append(endTime.TotalSeconds.ToString("F3"));
output.Append(" seconds\n============================");
Debug.Log(output.ToString());
}
}
}
| |
/* ====================================================================
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 NPOI.HWPF.SPRM;
using NPOI.HWPF.Model;
using System;
namespace NPOI.HWPF.UserModel
{
/**
* This class represents a run of text that share common properties.
*
* @author Ryan Ackley
*/
public class CharacterRun : Range
{
public const short SPRM_FRMARKDEL = (short)0x0800;
public const short SPRM_FRMARK = 0x0801;
public const short SPRM_FFLDVANISH = 0x0802;
public const short SPRM_PICLOCATION = 0x6A03;
public const short SPRM_IBSTRMARK = 0x4804;
public const short SPRM_DTTMRMARK = 0x6805;
public const short SPRM_FDATA = 0x0806;
public const short SPRM_SYMBOL = 0x6A09;
public const short SPRM_FOLE2 = 0x080A;
public const short SPRM_HIGHLIGHT = 0x2A0C;
public const short SPRM_OBJLOCATION = 0x680E;
public const short SPRM_ISTD = 0x4A30;
public const short SPRM_FBOLD = 0x0835;
public const short SPRM_FITALIC = 0x0836;
public const short SPRM_FSTRIKE = 0x0837;
public const short SPRM_FOUTLINE = 0x0838;
public const short SPRM_FSHADOW = 0x0839;
public const short SPRM_FSMALLCAPS = 0x083A;
public const short SPRM_FCAPS = 0x083B;
public const short SPRM_FVANISH = 0x083C;
public const short SPRM_KUL = 0x2A3E;
public const short SPRM_DXASPACE = unchecked((short)0x8840);
public const short SPRM_LID = 0x4A41;
public const short SPRM_ICO = 0x2A42;
public const short SPRM_HPS = 0x4A43;
public const short SPRM_HPSPOS = 0x4845;
public const short SPRM_ISS = 0x2A48;
public const short SPRM_HPSKERN = 0x484B;
public const short SPRM_YSRI = 0x484E;
public const short SPRM_RGFTCASCII = 0x4A4F;
public const short SPRM_RGFTCFAREAST = 0x4A50;
public const short SPRM_RGFTCNOTFAREAST = 0x4A51;
public const short SPRM_CHARSCALE = 0x4852;
public const short SPRM_FDSTRIKE = 0x2A53;
public const short SPRM_FIMPRINT = 0x0854;
public const short SPRM_FSPEC = 0x0855;
public const short SPRM_FOBJ = 0x0856;
public const short SPRM_PROPRMARK = unchecked((short)0xCA57);
public const short SPRM_FEMBOSS = 0x0858;
public const short SPRM_SFXTEXT = 0x2859;
public const short SPRM_DISPFLDRMARK = unchecked((short)0xCA62);
public const short SPRM_IBSTRMARKDEL = 0x4863;
public const short SPRM_DTTMRMARKDEL = 0x6864;
public const short SPRM_BRC = 0x6865;
public const short SPRM_SHD = 0x4866;
public const short SPRM_IDSIRMARKDEL = 0x4867;
public const short SPRM_CPG = 0x486B;
public const short SPRM_NONFELID = 0x486D;
public const short SPRM_FELID = 0x486E;
public const short SPRM_IDCTHINT = 0x286F;
SprmBuffer _chpx;
CharacterProperties _props;
/**
*
* @param chpx The chpx this object is based on.
* @param ss The stylesheet for the document this run belongs to.
* @param istd The style index if this Run's base style.
* @param parent The parent range of this character run (usually a paragraph).
*/
internal CharacterRun(CHPX chpx, StyleSheet ss, short istd, Range parent)
: base(Math.Max(parent._start, chpx.Start), Math.Min(parent._end, chpx.End), parent)
{
_props = chpx.GetCharacterProperties(ss, istd);
_chpx = chpx.GetSprmBuf();
}
/**
* Here for Runtime type determination using a switch statement convenient.
*
* @return TYPE_CHARACTER
*/
public int type()
{
return TYPE_CHARACTER;
}
public bool IsMarkedDeleted()
{
return _props.IsFRMarkDel();
}
public void MarkDeleted(bool mark)
{
_props.SetFRMarkDel(mark);
byte newVal = (byte)(mark ? 1 : 0);
_chpx.UpdateSprm(SPRM_FRMARKDEL, newVal);
}
public bool IsBold()
{
return _props.IsFBold();
}
public void SetBold(bool bold)
{
_props.SetFBold(bold);
byte newVal = (byte)(bold ? 1 : 0);
_chpx.UpdateSprm(SPRM_FBOLD, newVal);
}
public bool IsItalic()
{
return _props.IsFItalic();
}
public void SetItalic(bool italic)
{
_props.SetFItalic(italic);
byte newVal = (byte)(italic ? 1 : 0);
_chpx.UpdateSprm(SPRM_FITALIC, newVal);
}
public bool IsOutlined()
{
return _props.IsFOutline();
}
public void SetOutline(bool outlined)
{
_props.SetFOutline(outlined);
byte newVal = (byte)(outlined ? 1 : 0);
_chpx.UpdateSprm(SPRM_FOUTLINE, newVal);
}
public bool IsFldVanished()
{
return _props.IsFFldVanish();
}
public void SetFldVanish(bool fldVanish)
{
_props.SetFFldVanish(fldVanish);
byte newVal = (byte)(fldVanish ? 1 : 0);
_chpx.UpdateSprm(SPRM_FFLDVANISH, newVal);
}
public bool IsSmallCaps()
{
return _props.IsFSmallCaps();
}
public void SetSmallCaps(bool smallCaps)
{
_props.SetFSmallCaps(smallCaps);
byte newVal = (byte)(smallCaps ? 1 : 0);
_chpx.UpdateSprm(SPRM_FSMALLCAPS, newVal);
}
public bool IsCapitalized()
{
return _props.IsFCaps();
}
public void SetCapitalized(bool caps)
{
_props.SetFCaps(caps);
byte newVal = (byte)(caps ? 1 : 0);
_chpx.UpdateSprm(SPRM_FCAPS, newVal);
}
public bool IsVanished()
{
return _props.IsFVanish();
}
public void SetVanished(bool vanish)
{
_props.SetFVanish(vanish);
byte newVal = (byte)(vanish ? 1 : 0);
_chpx.UpdateSprm(SPRM_FVANISH, newVal);
}
public bool IsMarkedInserted()
{
return _props.IsFRMark();
}
public void MarkInserted(bool mark)
{
_props.SetFRMark(mark);
byte newVal = (byte)(mark ? 1 : 0);
_chpx.UpdateSprm(SPRM_FRMARK, newVal);
}
public bool IsStrikeThrough()
{
return _props.IsFStrike();
}
public void StrikeThrough(bool strike)
{
_props.SetFStrike(strike);
byte newVal = (byte)(strike ? 1 : 0);
_chpx.UpdateSprm(SPRM_FSTRIKE, newVal);
}
public bool IsShadowed()
{
return _props.IsFShadow();
}
public void SetShadow(bool shadow)
{
_props.SetFShadow(shadow);
byte newVal = (byte)(shadow ? 1 : 0);
_chpx.UpdateSprm(SPRM_FSHADOW, newVal);
}
public bool IsEmbossed()
{
return _props.IsFEmboss();
}
public void SetEmbossed(bool emboss)
{
_props.SetFEmboss(emboss);
byte newVal = (byte)(emboss ? 1 : 0);
_chpx.UpdateSprm(SPRM_FEMBOSS, newVal);
}
public bool IsImprinted()
{
return _props.IsFImprint();
}
public void SetImprinted(bool imprint)
{
_props.SetFImprint(imprint);
byte newVal = (byte)(imprint ? 1 : 0);
_chpx.UpdateSprm(SPRM_FIMPRINT, newVal);
}
public bool IsDoubleStrikeThrough()
{
return _props.IsFDStrike();
}
public void SetDoubleStrikethrough(bool dstrike)
{
_props.SetFDStrike(dstrike);
byte newVal = (byte)(dstrike ? 1 : 0);
_chpx.UpdateSprm(SPRM_FDSTRIKE, newVal);
}
public void SetFtcAscii(int ftcAscii)
{
_props.SetFtcAscii(ftcAscii);
_chpx.UpdateSprm(SPRM_RGFTCASCII, (short)ftcAscii);
}
public void SetFtcFE(int ftcFE)
{
_props.SetFtcFE(ftcFE);
_chpx.UpdateSprm(SPRM_RGFTCFAREAST, (short)ftcFE);
}
public void SetFtcOther(int ftcOther)
{
_props.SetFtcOther(ftcOther);
_chpx.UpdateSprm(SPRM_RGFTCNOTFAREAST, (short)ftcOther);
}
public int GetFontSize()
{
return _props.GetHps();
}
public void SetFontSize(int halfPoints)
{
_props.SetHps(halfPoints);
_chpx.UpdateSprm(SPRM_HPS, (short)halfPoints);
}
public int GetCharacterSpacing()
{
return _props.GetDxaSpace();
}
public void SetCharacterSpacing(int twips)
{
_props.SetDxaSpace(twips);
_chpx.UpdateSprm(SPRM_DXASPACE, twips);
}
public short GetSubSuperScriptIndex()
{
return _props.GetIss();
}
public void SetSubSuperScriptIndex(short iss)
{
_props.SetDxaSpace(iss);
_chpx.UpdateSprm(SPRM_DXASPACE, iss);
}
public int GetUnderlineCode()
{
return _props.GetKul();
}
public void SetUnderlineCode(int kul)
{
_props.SetKul((byte)kul);
_chpx.UpdateSprm(SPRM_KUL, (byte)kul);
}
public int GetColor()
{
return _props.GetIco();
}
public void SetColor(int color)
{
_props.SetIco((byte)color);
_chpx.UpdateSprm(SPRM_ICO, (byte)color);
}
public int GetVerticalOffset()
{
return _props.GetHpsPos();
}
public void SetVerticalOffset(int hpsPos)
{
_props.SetHpsPos(hpsPos);
_chpx.UpdateSprm(SPRM_HPSPOS, (byte)hpsPos);
}
public int GetKerning()
{
return _props.GetHpsKern();
}
public void SetKerning(int kern)
{
_props.SetHpsKern(kern);
_chpx.UpdateSprm(SPRM_HPSKERN, (short)kern);
}
public bool IsHighlighted()
{
return _props.IsFHighlight();
}
public void SetHighlighted(byte color)
{
_props.SetFHighlight(true);
_props.SetIcoHighlight(color);
_chpx.UpdateSprm(SPRM_HIGHLIGHT, color);
}
public String GetFontName()
{
return _doc.GetFontTable().GetMainFont(_props.GetFtcAscii());
}
public bool IsSpecialCharacter()
{
return _props.IsFSpec();
}
public void SetSpecialCharacter(bool spec)
{
_props.SetFSpec(spec);
byte newVal = (byte)(spec ? 1 : 0);
_chpx.UpdateSprm(SPRM_FSPEC, newVal);
}
public bool IsObj()
{
return _props.IsFObj();
}
public void SetObj(bool obj)
{
_props.SetFObj(obj);
byte newVal = (byte)(obj ? 1 : 0);
_chpx.UpdateSprm(SPRM_FOBJ, newVal);
}
public int GetPicOffset()
{
return _props.GetFcPic();
}
public void SetPicOffset(int offset)
{
_props.SetFcPic(offset);
_chpx.UpdateSprm(SPRM_PICLOCATION, offset);
}
/**
* Does the picture offset represent picture
* or binary data?
* If it's Set, then the picture offset refers to
* a NilPICFAndBinData structure, otherwise to a
* PICFAndOfficeArtData
*/
public bool IsData()
{
return _props.IsFData();
}
public void SetData(bool data)
{
_props.SetFData(data);
byte newVal = (byte)(data ? 1 : 0);
_chpx.UpdateSprm(SPRM_FOBJ, newVal);
}
public bool IsOle2()
{
return _props.IsFOle2();
}
public void SetOle2(bool ole)
{
_props.SetFOle2(ole);
byte newVal = (byte)(ole ? 1 : 0);
_chpx.UpdateSprm(SPRM_FOBJ, newVal);
}
public int GetObjOffset()
{
return _props.GetFcObj();
}
public void SetObjOffset(int obj)
{
_props.SetFcObj(obj);
_chpx.UpdateSprm(SPRM_OBJLOCATION, obj);
}
/**
* Get the ico24 field for the CHP record.
*/
public int GetIco24()
{
return _props.GetIco24();
}
/**
* Set the ico24 field for the CHP record.
*/
public void SetIco24(int colour24)
{
_props.SetIco24(colour24);
}
/**
* clone the CharacterProperties object associated with this
* characterRun so that you can apply it to another CharacterRun
*/
public CharacterProperties CloneProperties()
{
return (CharacterProperties)_props.Clone();
}
/**
* Used to create a deep copy of this object.
*
* @return A deep copy.
* @throws CloneNotSupportedException never
*/
public override Object Clone()
{
CharacterRun cp = (CharacterRun)base.Clone();
cp._props.SetDttmRMark((DateAndTime)_props.GetDttmRMark().Clone());
cp._props.SetDttmRMarkDel((DateAndTime)_props.GetDttmRMarkDel().Clone());
cp._props.SetDttmPropRMark((DateAndTime)_props.GetDttmPropRMark().Clone());
cp._props.SetDttmDispFldRMark((DateAndTime)_props.GetDttmDispFldRMark().
Clone());
cp._props.SetXstDispFldRMark((byte[])_props.GetXstDispFldRMark().Clone());
cp._props.SetShd((ShadingDescriptor)_props.GetShd().Clone());
return cp;
}
/**
* Returns true, if the CharacterRun is a special character run Containing a symbol, otherwise false.
*
* <p>In case of a symbol, the {@link #text()} method always returns a single character 0x0028, but word actually stores
* the character in a different field. Use {@link #GetSymbolCharacter()} to get that character and {@link #GetSymbolFont()}
* to determine its font.
*/
public bool IsSymbol()
{
return IsSpecialCharacter() && Text.Equals("\u0028");
}
/**
* Returns the symbol character, if this is a symbol character Run.
*
* @see #isSymbol()
* @throws InvalidOperationException If this is not a symbol character Run: call {@link #isSymbol()} first.
*/
public char GetSymbolCharacter()
{
if (IsSymbol())
{
return (char)_props.GetXchSym();
}
else
throw new InvalidOperationException("Not a symbol CharacterRun");
}
/**
* Returns the symbol font, if this is a symbol character Run. Might return null, if the font index is not found in the font table.
*
* @see #isSymbol()
* @throws InvalidOperationException If this is not a symbol character Run: call {@link #isSymbol()} first.
*/
public Ffn GetSymbolFont()
{
if (IsSymbol())
{
Ffn[] fontNames = _doc.GetFontTable().GetFontNames();
if (fontNames.Length <= _props.GetFtcSym())
return null;
return fontNames[_props.GetFtcSym()];
}
else
throw new InvalidOperationException("Not a symbol CharacterRun");
}
public BorderCode GetBorder()
{
return _props.GetBrc();
}
public bool isHighlighted()
{
return _props.IsFHighlight();
}
public byte GetHighlightedColor()
{
return _props.GetIcoHighlight();
}
public void setHighlighted(byte color)
{
_props.SetFHighlight(true);
_props.SetIcoHighlight(color);
_chpx.UpdateSprm(SPRM_HIGHLIGHT, color);
}
public int getLanguageCode()
{
return _props.GetLidDefault();
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Networking;
using UnityEngine.Events;
using Zeltex.AI;
using Zeltex.Items;
using Zeltex.Voxels;
using Zeltex.WorldUtilities;
using Zeltex.Skeletons;
using Zeltex.Game;
using Zeltex.Dialogue;
using Zeltex.Guis;
using Zeltex.Combat;
using Zeltex.Util;
using Zeltex.Quests;
using Zeltex.Physics;
namespace Zeltex.Characters
{
/// <summary>
/// Character class
/// Attached to every moving object that has interactions with items and the world.
/// NPC's class
/// Contains movement State
/// Raytrace for other characters and quest items
/// To Do:
/// - Manage the updating better. Only update when data updates
///
/// - Seperate out interaction part of the character
///
/// </summary>
[ExecuteInEditMode]
public class Character : NetworkBehaviour
{
#region Variables
[Header("Actions")]
[SerializeField]
private EditorAction ActionSaveToLevel = new EditorAction();
[SerializeField]
private EditorAction ActionImportVox = new EditorAction();
[SerializeField]
private EditorAction PushVoxToDataManager = new EditorAction();
[SerializeField]
private Transform ActionBone = null;
[Header("Data")]
[SerializeField]
private CharacterData Data = new CharacterData();
// The level the character is loaded in
[Header("Character")]
public bool IsPlayer;
private int KillCount = 0;
[HideInInspector]
public GameObject MySummonedCharacter;
// Raycasting
private static float RaycastRange = 5;
[HideInInspector]
public Vector3 LastHitNormal;
[HideInInspector]
public UnityEvent OnEndTalkEvent;
[HideInInspector]
public EventObject OnReturnToPool;
// Components
private DialogueHandler MyDialogueHandler;
private Skillbar MySkillbar;
private SkeletonHandler MySkeleton;
private Bot MyBot;
private Rigidbody MyRigidbody;
//private BasicController MyController;
private Mover MyMover;
private CapsuleCollider MyCollider;
// Saving?
private bool HasInitialized;
private Zeltine DeathHandle;
#endregion
#region Mono
public Vector3 GetForwardDirection()
{
if (Data.MySkeleton.GetCameraBone())
{
return Data.MySkeleton.GetCameraBone().transform.forward;
}
else
{
return transform.forward;
}
}
public CharacterData GetData()
{
return Data;
}
public void SetGuisActive(bool NewState)
{
Data.MyGuis.SetGuisActive(NewState);
}
public void ToggleGuis()
{
Data.MyGuis.ToggleGuis();
}
/// <summary>
/// Teleports the character and any attached guis
/// </summary>
public void Teleport(Vector3 NewPosition)
{
Vector3 DifferencePosition = NewPosition - transform.position;
transform.position = NewPosition;
for (int i = 0; i < Data.MyGuis.GetSize(); i++)
{
ZelGui MyZelGui = Data.MyGuis.GetZelGui(i);
if (MyZelGui)
{
MyZelGui.transform.position += DifferencePosition;
}
}
}
private void OnGUI()
{
Data.MyStatsHandler.OnGUI();
}
/*private void Awake()
{
if (gameObject.activeSelf)
{
Initialize(true);
}
}*/
private void Update()
{
if (Application.isPlaying)
{
Data.MyStatsHandler.SetCharacter(this);
Data.MyStatsHandler.UpdateScript();
}
if (ActionSaveToLevel.IsTriggered())
{
Data.Position.InLevel.SaveCharacter(this, "", true);
}
if (ActionImportVox.IsTriggered())
{
ImportVoxToBone(ActionBone);
}
if (PushVoxToDataManager.IsTriggered())
{
PushBoneVoxelModel(ActionBone);
}
if (Data.MyStats != null && Data.MyStatsHandler.ActionLoadStats.IsTriggered())
{
string LoadStatsName = Data.MyStatsHandler.ActionStatsName;
Stats DataStats = DataManager.Get().GetElement(DataFolderNames.StatGroups, 0) as Stats;
if (DataStats != null)
{
Data.MyStats = Data.MyStats.Load(DataStats.GetSerial(), typeof(Stats)) as Stats;
}
else
{
Debug.LogError("Cannot find: " + LoadStatsName);
}
}
if (Data.MyGuis != null)
{
if (Application.isPlaying == false)
{
Data.MyGuis.SetCharacter(this);
}
Data.MyGuis.Update();
}
}
private void PushBoneVoxelModel(Transform ActionBone)
{
ActionBone = GetActionBone(ActionBone);
if (ActionBone != null)
{
Bone MyBone = MySkeleton.GetSkeleton().GetBone(ActionBone);
if (MyBone != null)
{
VoxelModel MyModel = MyBone.GetVoxelModel();
if (MyModel != null)
{
DataManager.Get().PushElement(DataFolderNames.VoxelModels, MyModel);
}
else
{
Debug.LogError("Model is null. Bone has no mesh: " + MyBone.Name);
}
}
}
}
private Transform GetActionBone(Transform ActionBone)
{
if (ActionBone == null && GetSkeleton().GetSkeleton().MyBones.Count > 0)
{
ActionBone = GetSkeleton().GetSkeleton().MyBones[0].MyTransform;
}
return ActionBone;
}
private void ImportVoxToBone(Transform ActionBone)
{
ActionBone = GetActionBone(ActionBone);
if (ActionBone != null)
{
Bone MyBone = MySkeleton.GetSkeleton().GetBone(ActionBone);
if (MyBone != null)
{
World BoneWorld = MyBone.VoxelMesh.gameObject.GetComponent<World>();
RoutineManager.Get().StartCoroutine(DataManager.Get().LoadVoxFile(BoneWorld));
MyBone.MeshName = BoneWorld.name;
MyBone.OnModified();
GetSkeleton().GetSkeleton().OnModified();
GetData().OnModified();
// Also push to datamanager, to make sure it can be reloaded again
VoxelModel MyModel = MyBone.GetVoxelModel();
DataManager.Get().PushElement(DataFolderNames.VoxelModels, MyModel);
}
else
{
Debug.LogError(name + " bone is null.");
}
}
else
{
Debug.LogError(name + " Has no bones.");
}
}
public void ForceInitialize()
{
Data.MySkeleton.ForceStopLoad();
StopAllCoroutines();
Initialize(true);
}
public void SetPlayer(bool NewState)
{
IsPlayer = NewState;
MyMover.IsPlayer = NewState;
if (MyBot)
{
MyBot.enabled = !IsPlayer;
}
}
/// <summary>
/// Once character is loaded into a world
/// </summary>
public void OnActivated()
{
World MyWorld = Data.Position.GetInWorld();
if (MyWorld == null)
{
//Debug.LogError(name + " has a null world, so cannot position.");
return;
}
//Debug.LogError("[" + name + "] has been loaded into world of [" + MyWorld.name + "]");
// Scale its position - for now until i fixed the current levels stuff
//transform.position = new Vector3(transform.position.x * MyWorld.GetUnit().x, transform.position.y * MyWorld.GetUnit().y, transform.position.z * MyWorld.GetUnit().z);
if (GetSkeleton() != null && GetSkeleton().GetSkeleton() != null)
{
Bounds MyBounds = GetSkeleton().GetSkeleton().GetBounds();
int MaxChecks = 100;
int ChecksCount = 0;
transform.position = new Vector3(transform.position.x, transform.position.y - MyBounds.extents.y + MyBounds.center.y, transform.position.z);
Vector3 VoxelPosition = MyWorld.RealToBlockPosition(transform.position).GetVector();
// find new voxel position that is air or non block
while (true)
{
Voxel MyVoxel = MyWorld.GetVoxel(VoxelPosition.ToInt3());
if (MyVoxel == null)
{
break;
}
int VoxelType = MyVoxel.GetVoxelType();
if (VoxelType == 0)
{
break;
}
VoxelMeta MyMeta = MyWorld.GetVoxelMeta(VoxelType);
if (MyMeta == null)
{
break;
}
if (MyMeta.ModelID != "Block")
{
break;
}
VoxelPosition.y++;
ChecksCount++;
if (ChecksCount >= MaxChecks)
{
Debug.LogError("Could not find a new position for " + name);
break;
}
}
// Convert position to real world
VoxelPosition = MyWorld.BlockToRealPosition(VoxelPosition);// new Vector3(VoxelPosition.x * MyWorld.GetUnit().x, VoxelPosition.y * MyWorld.GetUnit().y, VoxelPosition.z * MyWorld.GetUnit().z);
LogManager.Get().Log("[" + name + "] has bounds of [" + MyBounds.center.ToString() + " - " + MyBounds.size.ToString() + "] at position [" + VoxelPosition.ToString() + "]", "CharacterLoading");
transform.position = new Vector3(VoxelPosition.x, VoxelPosition.y + MyBounds.extents.y - MyBounds.center.y - MyWorld.GetUnit().y / 2f, VoxelPosition.z);
}
else
{
Debug.LogError("No bounds in skeleton of: " + name);
}
}
public void SetData(CharacterData NewData, Level MyLevel = null, bool IsClone = true, bool IsSpawnGuis = true)
{
RoutineManager.Get().StartCoroutine(SetDataRoutine(NewData, MyLevel, IsClone, IsSpawnGuis));
}
public IEnumerator SetDataRoutine(CharacterData NewData,
Level MyLevel = null, bool IsClone = true, bool IsSpawnGuis = true, bool IsActivateSkeleton = true)
{
if (Data != NewData && NewData != null)
{
if (IsClone)
{
Data = NewData.Clone<CharacterData>();
if (Data == null)
{
Debug.LogError("Cloned data is null");
yield break;
}
}
else
{
Data = NewData;
}
Data.OnInitialized();
name = Data.Name;
RefreshComponents();
Data.MyStatsHandler.SetCharacter(this);
Data.MyQuestLog.Initialise(this);
Data.SetCharacter(this, MyLevel);
MyMover.IsPlayer = IsPlayer;
MySkeleton.SetSkeletonData(Data.MySkeleton);
if (!IsActivateSkeleton)
{
SetMovement(false);
}
if (IsPlayer == false)
{
if (MyBot == null)
{
MyBot = gameObject.AddComponent<Bot>();
GetComponent<Mover>().SetBot(MyBot);
}
}
// Set in chunk
// Unhide Skeleton
//MySkeleton.gameObject.SetActive(true);
if (IsActivateSkeleton)
{
Data.MyGuis.SetCharacter(this, false);
yield return ActivateCharacter();
}
else
{
Data.MyGuis.SetCharacter(this, IsSpawnGuis);
if (IsSpawnGuis)
{
RoutineManager.Get().StartCoroutine(SetGuiStatesAfter());
}
}
}
else if (NewData == null)
{
Debug.LogError("New Data is null inside " + name);
}
}
/// <summary>
/// Activates a character after a chunk finishes building
/// </summary>
public IEnumerator ActivateCharacter()
{
yield return MySkeleton.GetSkeleton().ActivateRoutine();
if (GetComponent<Shooter>())
{
GetComponent<Shooter>().SetCameraBone(GetCameraBone());
}
MyMover.SetCameraBone(GetCameraBone());
Data.MyGuis.SpawnAllGuis();
OnActivated(); // Fix position
RoutineManager.Get().StartCoroutine(SetGuiStatesAfter());
SetMovement(true);
}
/// <summary>
/// Has to wait for spawning of guis before i set them
/// </summary>
private IEnumerator SetGuiStatesAfter()
{
for (int i = 0; i < 300; i++)
{
yield return null;
}
Data.MyGuis.SetGuiStates();
}
/// <summary>
/// Called after spawning a character by CharacterManager
/// Set on the network to ensure data updated accross all machines
/// -only updates on the players character - when updating a character into a controlled one
/// </summary>
public void Initialize(bool IsForce = false) //string Name = "Character"
{
if (!HasInitialized || IsForce)
//&& CharacterManager.Get() && gameObject.activeInHierarchy)
{
HasInitialized = true;
/*if (Name == "Character")
{
Name = "Character_" + Random.Range(1, 10000);
}*/
//name = Name;
LogManager.Get().Log("Initialised character: " + name, "Characters");
RefreshComponents();
Data.MyStatsHandler.SetCharacter(this);
Data.MyQuestLog.Initialise(this);
Data.MyGuis.SetCharacter(this);
// spawn guis
//if (LayerManager.Get())
{
//LayerManager.Get().SetLayerCharacter(gameObject);
}
// Default character to load!
//if (Data.Class == "" && DataManager.Get())
{
//LogManager.Get().Log("Loading new class and skeleton for character: " + name + " - " + 0, "Characters");
//RunScript(Zeltex.Util.FileUtil.ConvertToList(DataManager.Get().Get(DataFolderNames.Classes, 0)));
//GetSkeleton().RunScript(Zeltex.Util.FileUtil.ConvertToList(DataManager.Get().Get(DataFolderNames.Skeletons, 0)));
}
//CharacterManager.Get().Register(this);
}
}
private void OnEnable()
{
if (MyCollider)
{
MyCollider.enabled = true;
}
}
#endregion
#region Combat
public bool IsAlive()
{
if (Data.MyStats != null)
{
return !Data.MyStatsHandler.IsDead();
}
else
{
return true;
}
}
/// <summary>
/// Sets the character to not respawn, using the character respawner class
/// </summary>
public void DontRespawn()
{
Data.CanRespawn = false;
}
/// <summary>
/// Called when stats health reaches 0
/// -Disable Bot and Player Controls
/// Need to add reviving functionality
/// </summary>
public void OnDeath(GameObject MyCharacter = null)
{
if (MyCharacter == null)
{
MyCharacter = gameObject; // killed yourself
}
if (Application.isPlaying)
{
StartCoroutine(DeathRoutine());
}
else
{
if (DeathHandle == null)
{
//UniversalCoroutine.CoroutineManager.StopCoroutine(DeathHandle);
DeathHandle = RoutineManager.Get().StartCoroutine(DeathRoutine());
}
else
{
Debug.LogError(name + " cannot die as already dying?");
}
}
}
public IEnumerator DeathRoutine()
{
//Debug.LogError(name + " Has started dying.");
float DeathTime = 6 + Random.Range(0,8);
/*if (IsPlayer)
{
DeathTime = 13;
}*/
yield return null;
if (MyBot)
{
MyBot.StopFollowing();
}
if (IsPlayer)
{
CameraManager.Get().GetMainCamera().GetComponent<Player>().SetMouse(false);
}
Data.MyGuis.SaveStates();
Data.MyGuis.HideAll();
MySkillbar.OnDeath();
if (MyBot)
{
MyBot.Disable();
}
SetMovement(false);
// Apply Animations on death - fade effect
if (MySkeleton != null)
{
Zanimator MyAnimator = MySkeleton.GetComponent<Zanimator>();
if (MyAnimator)
{
MyAnimator.Stop();
}
Ragdoll MyRagDoll = MySkeleton.GetComponent<Ragdoll>();
if (MyRagDoll)
{
MyRagDoll.RagDoll();
}
MySkeleton.GetSkeleton().DestroyBodyCubes();
}
else
{
Debug.LogError(name + " Has no skeleton");
}
// burnt, sliced, crushed, chocolified, decapitated, exploded
if (!Data.CanRespawn)
{
gameObject.name += "'s Corpse"; // burnt, sliced, crushed, chocolified, decapitated, exploded
}
float ReviveTime = 10;
if (IsPlayer)
{
System.Action<ZelGui> OnFinishSpawning = (RespawnZelGui) =>
{
if (RespawnZelGui)
{
RespawnZelGui.TurnOn(); // turn gui on when reviving begins
RespawnGui MyRespawner = RespawnZelGui.GetComponent<RespawnGui>();
if (MyRespawner)
{
StartCoroutine(MyRespawner.CountDown(() => { GetGuis().GetZelGui("RespawnGui").TurnOff(); }, (int)(ReviveTime + DeathTime)));
}
else
{
Debug.LogError("Respawn gui doesn't have respawn gui.");
}
}
else
{
Debug.LogError("Could not find RespawnGui in guis for: " + name);
}
if (RespawnZelGui)
{
RespawnZelGui.gameObject.SetActive(true); // turn gui on when reviving begins
}
};
GetGuis().Spawn("RespawnGui", OnFinishSpawning);
}
float TimeBeginRespawn = Time.time;
while (Time.time - TimeBeginRespawn < DeathTime)
{
yield return null;
}
// if (Data.CanRespawn)
{
yield return RoutineManager.Get().StartCoroutine(Respawn(ReviveTime));
}
/*else
{
if (IsPlayer)
{
Camera.main.gameObject.GetComponent<Player>().RemoveCharacter();
}
Data.MyGuis.Clear();
CharacterManager.Get().ReturnObject(this);
}*/
DeathHandle = null;
}
private IEnumerator Respawn(float ReviveTime)
{
yield return null;
MySkeleton.GetComponent<Ragdoll>().ReverseRagdoll(ReviveTime);
float TimeStarted = Time.time;
while (Time.time - TimeStarted <= ReviveTime)
{
yield return null;
}
yield return null;
Debug.Log("Reviving Character [" + name + "].");
Data.MyGuis.RestoreStates();
Data.MyStatsHandler.RestoreFullHealth();
SetMovement(true);
if (IsPlayer)
{
CameraManager.Get().GetMainCamera().transform.localPosition = Vector3.zero;
CameraManager.Get().GetMainCamera().transform.localRotation = Quaternion.identity;
CameraManager.Get().GetMainCamera().GetComponent<Player>().SetMouse(true);
}
else
{
if (MyBot)
{
MyBot.EnableBot();
}
}
MySkillbar.SetItem(-1);
MySkillbar.SetItem(0);
DeathHandle = null;
}
public bool StopDeath()
{
if (DeathHandle != null)
{
RoutineManager.Get().StopCoroutine(DeathHandle);
DeathHandle = null;
return true;
}
else
{
return false;
}
}
public void KilledCharacter(GameObject DeadCharacter)
{
Debug.Log(name + " has killed " + DeadCharacter.name);
AddScore(1);
Data.MyStatsHandler.AddExperience(1);
}
#endregion
#region GameModeScores
// Add To Log Class - used to log events
// quick score system, put it somewhere else later
public void AddScore(int Addition)
{
KillCount += Addition;
OnScoreChange();
}
public void SetScore(int NewScore)
{
KillCount = NewScore;
}
public int GetScore()
{
return KillCount;
}
void OnScoreChange()
{
if (GameMode.Get())
{
GameMode.Get().CheckKillCondition(GetScore());
}
}
#endregion
#region Collision
/// <summary>
/// When player collides with something
/// </summary>
void OnTriggerEnter(Collider MyCollider)
{
ItemHandler MyItem = MyCollider.gameObject.GetComponent<ItemHandler>();
if (MyItem)
{
MyItem.OnContact(gameObject);
}
Teleporter MyTeleporter = MyCollider.gameObject.GetComponent<Teleporter>();
if (MyTeleporter)
{
MyTeleporter.OnContact(gameObject);
}
}
#endregion
#region RayTrace
public void RayTrace(int SelectionType = 0)
{
Debug.Log(name + " is raytracing " + SelectionType);
if (IsRayHitGui() == false && MySkeleton)
{
RayTraceSelections(Data.MySkeleton.MyCameraBone, SelectionType);
}
else
{
Debug.LogError(name + " could not interact with anything.");
}
}
private bool RayTraceSelections(Transform CameraBone, int SelectionType)
{
RaycastHit MyHit;
if (UnityEngine.Physics.Raycast(CameraBone.position, CameraBone.forward, out MyHit, RaycastRange, LayerManager.Get().GetInteractLayer()))
{
Debug.Log(name + " has interacted with: " + MyHit.collider.gameObject.name);
if (LayerManager.AreLayersEqual(LayerManager.Get().GetItemsLayer(), MyHit.collider.gameObject.layer))
{
ItemHandler HitItemHandler = MyHit.collider.gameObject.GetComponent<ItemHandler>();
if (HitItemHandler != null)
{
Debug.Log(name + " has picked up item: " + HitItemHandler.name);
return PickupItem(HitItemHandler, SelectionType);
}
Chunk ItemChunk = MyHit.collider.gameObject.GetComponent<Chunk>();
if (ItemChunk)
{
ItemHandler HitItemHandler2 = ItemChunk.transform.parent.gameObject.GetComponent<ItemHandler>();
if (HitItemHandler2 != null)
{
Debug.Log(name + " has picked up Voxel Item: " + HitItemHandler2.name);
return PickupItem(HitItemHandler2, SelectionType);
}
}
Debug.Log(name + " Hit a items layer without item object");
}
else if (LayerManager.AreLayersEqual(LayerManager.Get().GetSkeletonLayer(), MyHit.collider.gameObject.layer))
{
Character MyCharacter = MyHit.collider.transform.FindRootCharacter();
if (MyCharacter)
{
Debug.Log(name + " Hit a character [" + MyCharacter.name + "]");
//Character HitCharacter = MyCharacter.GetComponent<Character>();// MyHit.collider.gameObject.GetComponent<Character>();
Debug.Log(name + " has talked to character: " + MyCharacter.name);
return TalkToCharacter(MyCharacter, SelectionType);
}
else
{
Debug.Log(name + " Hit a characters layer without character root.");
}
}
else if (LayerManager.AreLayersEqual(LayerManager.Get().GetWorldsLayer(), MyHit.collider.gameObject.layer))
{
/*Door MyDoor = MyHit.collider.gameObject.GetComponent<Door>();
if (MyDoor)
{
//Debug.Log("Toggling door!");
Debug.Log(name + " has toggled door: " + MyDoor.name);
MyDoor.ToggleDoor();
return true;
}*/
Vector3 BlockPosition = World.RayHitToBlockPosition(MyHit);
World MyWorld = RayHitToWorld(MyHit);
if (MyWorld != null)
{
Debug.Log(name + " Hit a world [" + MyWorld.name + "]");
Voxel MyVoxel = MyWorld.GetVoxel(new Int3(BlockPosition));
//VoxelManager MetaData = MyWorld.MyDataBase;
if (MyVoxel != null)// && MyVoxel.GetVoxelType() >= 0 && MyVoxel.GetVoxelType() < MetaData.Data.Count)
{
// Get the meta data from the index
VoxelMeta MyMeta = MyWorld.GetVoxelMeta(MyVoxel.GetVoxelType());// MetaData.Data[MyVoxel.GetVoxelType()];
if (MyMeta != null && MyHit.collider != null)
{
//Debug.LogError("Activated Voxel: " + MyMeta.Name + ": " + MyMeta.IsMultipleBlockModel() + ":" + BlockPosition.ToString());
Chunk MyChunk = MyHit.collider.GetComponent<Chunk>();// MetaData,
MyMeta.CharacterActivate(this, MyChunk, BlockPosition, MyVoxel);
}
}
return true;
}
else
{
Debug.Log(name + " Hit a worlds layer without world component.");
}
}
else
{
Debug.Log(name + " Has not selected anything");
}
}
else
{
Debug.Log(name + " Has not selected anything");
}
return false;
}
public static World RayHitToWorld(RaycastHit MyHit)
{
World MyWorld;
Chunk HitChunk = MyHit.collider.GetComponent<Chunk>();
if (HitChunk)
{
MyWorld = HitChunk.GetWorld();
}
else
{
MyWorld = MyHit.collider.GetComponent<World>();
}
return MyWorld;
}
/// <summary>
/// Checks to see if the mouse is hitting the gui
/// </summary>
public static bool IsRayHitGui()
{
var pointer = new PointerEventData(EventSystem.current);
pointer.position = (Input.mousePosition);
List<RaycastResult> raycastResults = new List<RaycastResult>();
if (EventSystem.current)
{
EventSystem.current.RaycastAll(pointer, raycastResults);
if (raycastResults.Count > 0)
{
return true;
}
}
return false;
}
/// <summary>
/// Dialogue begins!
/// </summary>
public bool TalkToCharacter(Character OtherCharacter, int InteractType)
{
if (OtherCharacter.GetData().MyDialogue.GetSize() > 0)
{
System.Action<ZelGui> OnFinishSpawning = (MyDialogueGui) =>
{
if (MyDialogueGui)
{
Debug.Log(name + " Is Talking to" + OtherCharacter.name + " with " +
OtherCharacter.GetData().MyDialogue.GetSize() + " dialogue sections.");
OnBeginTalk(OtherCharacter);
OtherCharacter.OnBeginTalk(this);
MyDialogueGui.TurnOn();
DialogueHandler MyCharacterDialogue = MyDialogueGui.GetComponent<DialogueHandler>();
MyCharacterDialogue.MyTree = OtherCharacter.GetData().MyDialogue; // set gui tree as talked to characters dialogue
MyCharacterDialogue.SetCharacters(this, OtherCharacter);
//MyCharacterDialogue.OtherCharacter = OtherCharacter;
MyCharacterDialogue.OnConfirm();//begin the talk
}
else
{
Debug.LogError(name + " does not have Dialogue Gui");
}
};
Data.MyGuis.Spawn("Dialogue", OnFinishSpawning);
}
else
{
Debug.Log(name + " cannot talk to " + OtherCharacter.name + " due to 0 size.");
}
return true;
}
/// <summary>
/// Called on the character
/// </summary>
public void OnBeginTalk(Character Character2)
{
// Hide all guis
this.Data.MyGuis.SaveStates();
this.Data.MyGuis.HideAll();
if (MyBot)
{
MyBot.FollowTarget(Character2.gameObject);
}
this.OnEndTalkEvent.SetEvent(OnEndTalk);
SetMovement(false);
if (IsPlayer && CameraManager.Get() && CameraManager.Get().GetMainCamera())
{
Player MyPlayer = CameraManager.Get().GetMainCamera().GetComponent<Player>();
if (MyPlayer)
{
MyPlayer.SetFreeze(true);
}
}
}
public void OnEndTalk()
{
SetMovement(true);
if (IsPlayer && CameraManager.Get() && CameraManager.Get().GetMainCamera())
{
Player MyPlayer = CameraManager.Get().GetMainCamera().GetComponent<Player>();
if (MyPlayer)
{
MyPlayer.SetFreeze(false);
}
}
Data.MyGuis.RestoreStates();
Bot OtherBot = gameObject.GetComponent<Bot>();
if (OtherBot && OtherBot.enabled)
{
OtherBot.Wander();
}
ZelGui MyDialogueGui = Data.MyGuis.GetZelGui("Dialogue");
if (MyDialogueGui)
{
MyDialogueGui.TurnOff();
}
}
/// <summary>
/// When activate button pressed on item object
/// </summary>
public bool PickupItem(ItemHandler HitItemHandler, int InteractType)
{
if (InteractType == 0)
{
// passes in a ray object for any kind of picking action
// does things like destroy, activates the special function
HitItemHandler.CharacterPickup(this);
}
else if (InteractType == 1)
{
HitItemHandler.ToggleGui();
}
return true;
}
#endregion
#region Controls
/// <summary>
/// Enable and disable movement
/// </summary>
public void SetMovement(bool NewState)
{
if (MyRigidbody)
{
MyRigidbody.isKinematic = !NewState;
}
else
{
Debug.LogError(name + " has no rigidbody..");
}
if (MyMover)
{
MyMover.enabled = NewState;
}
else
{
Debug.LogError(name + " has no Movement..");
}
enabled = NewState;
}
#endregion
#region Utility
public bool CanRespawn()
{
return Data.CanRespawn;
}
public Stats GetStats()
{
return Data.MyStats;
}
public Guis.Characters.CharacterGuis GetGuis()
{
return Data.MyGuis;
}
/// <summary>
/// Sets new race name and sets it to nonunique
/// </summary>
public void SetRace(string NewRaceName)
{
Data.Race = NewRaceName;
//IsStaticRace = !string.IsNullOrEmpty(Data.Race); // sets true if not null string
}
/// <summary>
/// A race name used for cosmetic purposes
/// Saves the characters race uniquelly
/// </summary>
public void SetRaceUnique(string NewRaceName)
{
Data.Race = NewRaceName;
//IsStaticRace = false;
}
private void SetClass(string NewClassName)
{
Data.Class = NewClassName;
//IsStaticClass = !string.IsNullOrEmpty(Data.Class);
}
/// <summary>
/// Sets the guis target
/// </summary>
public void SetGuisTarget(Transform NewTarget)
{
for (int i = 0; i < Data.MyGuis.GetSize(); i++)
{
Transform MyGui = Data.MyGuis.GetZelGui(i).transform;
if (MyGui.GetComponent<Orbitor>())
{
MyGui.GetComponent<Orbitor>().SetTarget(NewTarget);
}
if (MyGui.GetComponent<Billboard>())
{
MyGui.GetComponent<Billboard>().SetTarget(NewTarget);
}
}
}
/// <summary>
/// Returns players inventory
/// </summary>
public Inventory GetSkillbarItems()
{
return Data.Skillbar;
}
public Inventory GetBackpackItems()
{
return Data.Backpack;
}
public Inventory GetEquipment()
{
return Data.GetEquipment();
}
public QuestLog GetQuestLog()
{
return Data.MyQuestLog;
}
/// <summary>
/// Gets a characters skeleton
/// </summary>
public SkeletonHandler GetSkeleton()
{
if (MySkeleton == null)
{
Debug.LogError("Set Skeleton Handler in Editor: " + name);
}
return MySkeleton;
}
public Transform GetCameraBone()
{
if (MySkeleton)
{
return Data.MySkeleton.GetCameraBone();
}
else
{
return transform;
}
}
/// <summary>
/// Refresh all the references to components and datamanager
/// </summary>
private void RefreshComponents()
{
if (MyBot == null)
{
MyBot = GetComponent<Bot>();
if (MyBot == null)
{
MyBot = gameObject.AddComponent<Bot>();
}
}
if (MyRigidbody == null)
{
MyRigidbody = GetComponent<Rigidbody>();
if (MyRigidbody == null)
{
MyRigidbody = gameObject.AddComponent<Rigidbody>();
}
}
if (MyMover == null)
{
MyMover = GetComponent<Mover>();
if (MyMover == null)
{
MyMover = gameObject.AddComponent<Mover>();
}
}
if (MyDialogueHandler == null)
{
MyDialogueHandler = gameObject.GetComponent<DialogueHandler>();
}
if (MyCollider == null)
{
MyCollider = GetComponent<CapsuleCollider>();
if (MyCollider == null)
{
MyCollider = gameObject.AddComponent<CapsuleCollider>();
}
}
if (MySkillbar == null)
{
MySkillbar = GetComponent<Skillbar>();
if (MySkillbar == null)
{
MySkillbar = gameObject.AddComponent<Skillbar>();
}
}
if (MySkeleton == null)
{
MySkeleton = transform.GetComponentInChildren<SkeletonHandler>();
}
if (MySkeleton == null)
{
Transform BodyTransform = null;
if (BodyTransform == null)
{
Debug.Log("Creating body for character: " + name);
GameObject NewBody = new GameObject();
NewBody.transform.SetParent(transform);
NewBody.transform.localPosition = Vector3.zero;
NewBody.transform.eulerAngles = Vector3.zero;
NewBody.name = "Body";
MySkeleton = NewBody.AddComponent<SkeletonHandler>();
}
}
}
public Skillbar GetSkillbar()
{
return MySkillbar;
}
#endregion
#region Naming
public void UpdateName(string NewName)
{
transform.name = NewName;
}
#endregion
/// <summary>
/// Clears character data
/// </summary>
private void Clear()
{
Data.Clear();
}
public List<string> GetStatistics()
{
List<string> MyData = new List<string>();
MyData.Add("Character [" + name + "]\n" +
" Stats: " + Data.MyStats.GetSize() + "\n" +
" Skillbar Items: " + GetSkillbarItems().GetSize() + "\n" +
" Backpack Items: " + GetBackpackItems().GetSize() + "\n" +
" Quests: " + Data.MyQuestLog.GetSize() + "\n" +
" Dialogue: " + MyDialogueHandler.MyTree.GetSize() + "\n" +
" Skeleton: " + Data.MySkeleton.MyBones.Count + "\n");
MyData.Add(" Equipment: " + Data.Equipment.GetSize() + "\n");
return MyData;
}
#region Positioning
public World GetInWorld()
{
return Data.Position.GetInWorld();
}
public Int3 GetChunkPosition()
{
return Data.Position.GetChunkPosition();
}
public Chunk GetInChunk()
{
return Data.Position.GetInChunk();
}
/// <summary>
/// Sets a new world for a character
/// </summary>
public void SetWorld(World NewWorld)
{
Data.Position.SetWorld(NewWorld);
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Sql.Database.Model;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Collections;
namespace Microsoft.Azure.Commands.Sql.Database.Cmdlet
{
/// <summary>
/// Cmdlet to create a new Azure Sql Database
/// </summary>
[Cmdlet(VerbsCommon.New, "AzureRmSqlDatabase", SupportsShouldProcess = true,
ConfirmImpact = ConfirmImpact.Low)]
public class NewAzureSqlDatabase : AzureSqlDatabaseCmdletBase<AzureSqlDatabaseCreateOrUpdateModel>
{
/// <summary>
/// Gets or sets the name of the database to create.
/// </summary>
[Parameter(Mandatory = true,
HelpMessage = "The name of the Azure SQL Database to create.")]
[ValidateNotNullOrEmpty]
public string DatabaseName { get; set; }
/// <summary>
/// Gets or sets the name of the Azure SQL Database collation to use
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The name of the Azure SQL Database collation to use.")]
[ValidateNotNullOrEmpty]
public string CollationName { get; set; }
/// <summary>
/// Gets or sets the name of the Azure SQL Database catalog collation to use
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The name of the Azure SQL Database catalog collation to use.")]
[ValidateNotNullOrEmpty]
public string CatalogCollation { get; set; }
/// <summary>
/// Gets or sets the maximum size of the Azure SQL Database in bytes
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The maximum size of the Azure SQL Database in bytes.")]
[ValidateNotNullOrEmpty]
public long MaxSizeBytes { get; set; }
/// <summary>
/// Gets or sets the edition to assign to the Azure SQL Database
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The edition to assign to the Azure SQL Database.")]
[ValidateNotNullOrEmpty]
public DatabaseEdition Edition { get; set; }
/// <summary>
/// Gets or sets the name of the service objective to assign to the Azure SQL Database
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The name of the service objective to assign to the Azure SQL Database.")]
[ValidateNotNullOrEmpty]
public string RequestedServiceObjectiveName { get; set; }
/// <summary>
/// Gets or sets the name of the Elastic Pool to put the database in
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The name of the Elastic Pool to put the database in.")]
[ValidateNotNullOrEmpty]
public string ElasticPoolName { get; set; }
/// <summary>
/// Gets or sets the read scale option to assign to the Azure SQL Database
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The read scale option to assign to the Azure SQL Database.(Enabled/Disabled)")]
[ValidateNotNullOrEmpty]
public DatabaseReadScale ReadScale { get; set; }
/// <summary>
/// Gets or sets the tags associated with the Azure Sql Database
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The tags to associate with the Azure Sql Database Server")]
[Alias("Tag")]
public Hashtable Tags { get; set; }
[Parameter(Mandatory = false,
HelpMessage = "The name of the sample schema to apply when creating this database.")]
[ValidateSet(Management.Sql.Models.SampleName.AdventureWorksLT)]
public string SampleName { get; set; }
/// <summary>
/// Overriding to add warning message
/// </summary>
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
}
/// <summary>
/// Get the entities from the service
/// </summary>
/// <returns>The list of entities</returns>
protected override AzureSqlDatabaseCreateOrUpdateModel GetEntity()
{
// We try to get the database. Since this is a create, we don't want the database to exist
try
{
ModelAdapter.GetDatabase(this.ResourceGroupName, this.ServerName, this.DatabaseName);
}
catch (Hyak.Common.CloudException ex) // when using Hyak SDK
{
if (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// This is what we want. We looked and there is no database with this name.
return null;
}
// Unexpected exception encountered
throw;
}
catch (Microsoft.Rest.Azure.CloudException ex) // when using AutoRest SDK
{
if (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// This is what we want. We looked and there is no database with this name.
return null;
}
// Unexpected exception encountered
throw;
}
// The database already exists
throw new PSArgumentException(
string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.DatabaseNameExists, this.DatabaseName, this.ServerName),
"DatabaseName");
}
/// <summary>
/// Create the model from user input
/// </summary>
/// <param name="model">Model retrieved from service</param>
/// <returns>The model that was passed in</returns>
protected override AzureSqlDatabaseCreateOrUpdateModel ApplyUserInputToModel(AzureSqlDatabaseCreateOrUpdateModel model)
{
string location = ModelAdapter.GetServerLocation(ResourceGroupName, ServerName);
return new AzureSqlDatabaseCreateOrUpdateModel
{
Database = new AzureSqlDatabaseModel()
{
Location = location,
ResourceGroupName = ResourceGroupName,
ServerName = ServerName,
CatalogCollation = CatalogCollation,
CollationName = CollationName,
DatabaseName = DatabaseName,
Edition = Edition,
MaxSizeBytes = MaxSizeBytes,
RequestedServiceObjectiveName = RequestedServiceObjectiveName,
Tags = TagsConversionHelper.CreateTagDictionary(Tags, validate: true),
ElasticPoolName = ElasticPoolName,
ReadScale = ReadScale
},
SampleName = SampleName
};
}
/// <summary>
/// Create the new database
/// </summary>
/// <param name="entity">The output of apply user input to model</param>
/// <returns>The input entity</returns>
protected override AzureSqlDatabaseCreateOrUpdateModel PersistChanges(AzureSqlDatabaseCreateOrUpdateModel entity)
{
return new AzureSqlDatabaseCreateOrUpdateModel
{
Database = ModelAdapter.UpsertDatabase(this.ResourceGroupName, this.ServerName, entity)
};
}
/// <summary>
/// Strips away the create or update properties from the model so that just the regular properties
/// are written to cmdlet output.
/// </summary>
protected override object TransformModelToOutputObject(AzureSqlDatabaseCreateOrUpdateModel model)
{
return model.Database;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using CoreGraphics;
using Foundation;
using UIKit;
using static TouchCanvas.CGRectHelpers;
namespace TouchCanvas {
public partial class CanvasView : UIView {
bool isPredictionEnabled = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad;
bool needsFullRedraw = true;
// List containing all line objects that need to be drawn in Draw(CGRect rect)
readonly List<Line> lines = new List<Line> ();
// List containing all line objects that have been completely drawn into the frozenContext.
readonly List<Line> finishedLines = new List<Line> ();
// Holds a map of UITouch objects to Line objects whose touch has not ended yet.
readonly Dictionary<UITouch, Line> activeLines = new Dictionary<UITouch, Line> ();
// Holds a map of UITouch objects to Line objects whose touch has ended but still has points awaiting updates.
readonly Dictionary<UITouch, Line> pendingLines = new Dictionary<UITouch, Line> ();
bool isDebuggingEnabled;
public bool IsDebuggingEnabled {
get {
return isDebuggingEnabled;
}
set {
isDebuggingEnabled = value;
needsFullRedraw = true;
SetNeedsDisplay ();
}
}
bool usePreciseLocations;
public bool UsePreciseLocations {
get {
return usePreciseLocations;
}
set {
usePreciseLocations = value;
needsFullRedraw = true;
SetNeedsDisplay ();
}
}
// An CGImage containing the last representation of lines no longer receiving updates.
CGImage frozenImage;
CGBitmapContext frozenContext;
public CGBitmapContext FrozenContext {
get {
if (frozenContext == null) {
var scale = Window.Screen.Scale;
var size = Bounds.Size;
size.Width *= scale;
size.Height *= scale;
var colorSpace = CGColorSpace.CreateDeviceRGB ();
frozenContext = new CGBitmapContext (null, (nint)size.Width, (nint)size.Height, 8, 0, colorSpace, CGImageAlphaInfo.PremultipliedLast);
frozenContext.SetLineCap (CGLineCap.Round);
frozenContext.ConcatCTM (CGAffineTransform.MakeScale (scale, scale));
}
return frozenContext;
}
}
[Export ("initWithCoder:")]
public CanvasView (NSCoder coder) : base (coder)
{
}
[Export ("initWithFrame:")]
public CanvasView (CGRect frame) : base (frame)
{
}
public CanvasView (IntPtr handle) : base (handle)
{
}
public override void Draw (CGRect rect)
{
var context = UIGraphics.GetCurrentContext ();
context.SetLineCap (CGLineCap.Round);
if (needsFullRedraw) {
SetFrozenImageNeedsUpdate ();
FrozenContext.ClearRect (Bounds);
foreach (var line in finishedLines)
line.DrawCommitedPointsInContext (FrozenContext, IsDebuggingEnabled, UsePreciseLocations);
needsFullRedraw = false;
}
frozenImage = frozenImage ?? FrozenContext.ToImage ();
if(frozenImage != null)
context.DrawImage (Bounds, frozenImage);
foreach (var line in lines)
line.DrawInContext (context, IsDebuggingEnabled, UsePreciseLocations);
}
void SetFrozenImageNeedsUpdate ()
{
frozenImage?.Dispose ();
frozenImage = null;
}
public void Clear ()
{
activeLines.Clear ();
pendingLines.Clear ();
lines.Clear ();
finishedLines.Clear ();
needsFullRedraw = true;
SetNeedsDisplay ();
}
public void DrawTouches (NSSet touches, UIEvent evt)
{
var updateRect = CGRectNull ();
foreach (var touch in touches.Cast<UITouch> ()) {
Line line;
// Retrieve a line from activeLines. If no line exists, create one.
if (!activeLines.TryGetValue (touch, out line))
line = AddActiveLineForTouch (touch);
// Remove prior predicted points and update the updateRect based on the removals. The touches
// used to create these points are predictions provided to offer additional data. They are stale
// by the time of the next event for this touch.
updateRect = updateRect.UnionWith (line.RemovePointsWithType (PointType.Predicted));
// Incorporate coalesced touch data. The data in the last touch in the returned array will match
// the data of the touch supplied to GetCoalescedTouches
var coalescedTouches = evt.GetCoalescedTouches (touch) ?? new UITouch[0];
var coalescedRect = AddPointsOfType (PointType.Coalesced, coalescedTouches, line);
updateRect = updateRect.UnionWith (coalescedRect);
// Incorporate predicted touch data. This sample draws predicted touches differently; however,
// you may want to use them as inputs to smoothing algorithms rather than directly drawing them.
// Points derived from predicted touches should be removed from the line at the next event for this touch.
if (isPredictionEnabled) {
var predictedTouches = evt.GetPredictedTouches (touch) ?? new UITouch[0];
var predictedRect = AddPointsOfType (PointType.Predicted, predictedTouches, line);
updateRect = updateRect.UnionWith (predictedRect);
}
}
SetNeedsDisplayInRect (updateRect);
}
Line AddActiveLineForTouch (UITouch touch)
{
var newLine = new Line ();
activeLines.Add (touch, newLine);
lines.Add (newLine);
return newLine;
}
CGRect AddPointsOfType (PointType type, UITouch[] touches, Line line)
{
var accumulatedRect = CGRectNull ();
for (int i = 0; i < touches.Length; i++) {
var touch = touches [i];
// The visualization displays non-`.Stylus` touches differently.
if (touch.Type != UITouchType.Stylus)
type |= PointType.Finger;
// Touches with estimated properties require updates; add this information to the `PointType`.
if (touch.EstimatedProperties != 0)
type |= PointType.NeedsUpdate;
// The last touch in a set of .Coalesced touches is the originating touch. Track it differently.
bool isLast = (i == touches.Length - 1);
if (type.HasFlag (PointType.Coalesced) && isLast) {
type &= ~PointType.Coalesced;
type |= PointType.Standard;
}
var touchRect = line.AddPointOfType (type, touch);
accumulatedRect = accumulatedRect.UnionWith (touchRect);
CommitLine (line);
}
return accumulatedRect;
}
public void EndTouches (NSSet touches, bool cancel)
{
var updateRect = CGRectNull ();
foreach (var touch in touches.Cast<UITouch> ()) {
// Skip over touches that do not correspond to an active line.
Line line;
if (!activeLines.TryGetValue (touch, out line))
continue;
// If this is a touch cancellation, cancel the associated line.
if (cancel)
updateRect = updateRect.UnionWith (line.Cancel ());
// If the line is complete (no points needing updates) or updating isn't enabled, move the line to the frozenImage.
if (line.IsComplete)
FinishLine (line);
else
pendingLines.Add (touch, line);
// This touch is ending, remove the line corresponding to it from `activeLines`.
activeLines.Remove (touch);
}
SetNeedsDisplayInRect (updateRect);
}
public void UpdateEstimatedPropertiesForTouches (NSSet touches)
{
foreach (var touch in touches.Cast<UITouch> ()) {
bool isPending = false;
// Look to retrieve a line from `activeLines`. If no line exists, look it up in `pendingLines`.
Line possibleLine;
if (!activeLines.TryGetValue (touch, out possibleLine))
isPending = pendingLines.TryGetValue (touch, out possibleLine);
// If no line is related to the touch, return as there is no additional work to do.
if (possibleLine == null)
return;
CGRect rect;
if (possibleLine.UpdateWithTouch (touch, out rect))
SetNeedsDisplayInRect (rect);
// If this update updated the last point requiring an update, move the line to the `frozenImage`.
if (isPending && possibleLine.IsComplete) {
FinishLine (possibleLine);
pendingLines.Remove (touch);
} else {
CommitLine (possibleLine);
}
}
}
void CommitLine (Line line)
{
// Have the line draw any segments between points no longer being updated into the frozenContext and remove them from the line.
line.DrawFixedPointsInContext (FrozenContext, IsDebuggingEnabled, UsePreciseLocations);
SetFrozenImageNeedsUpdate ();
}
void FinishLine (Line line)
{
line.DrawFixedPointsInContext (FrozenContext, IsDebuggingEnabled, UsePreciseLocations, true);
SetFrozenImageNeedsUpdate ();
lines.Remove (line);
finishedLines.Add (line);
}
}
}
| |
using System;
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.
*/
/// <summary>
/// Floating point numbers smaller than 32 bits.
/// <para/>
/// NOTE: This was SmallFloat in Lucene
/// <para/>
/// @lucene.internal
/// </summary>
public class SmallSingle
{
/// <summary>
/// No instance </summary>
private SmallSingle()
{
}
/// <summary>
/// Converts a 32 bit <see cref="float"/> to an 8 bit <see cref="float"/>.
/// <para/>Values less than zero are all mapped to zero.
/// <para/>Values are truncated (rounded down) to the nearest 8 bit value.
/// <para/>Values between zero and the smallest representable value
/// are rounded up.
/// </summary>
/// <param name="f"> The 32 bit <see cref="float"/> to be converted to an 8 bit <see cref="float"/> (<see cref="byte"/>). </param>
/// <param name="numMantissaBits"> The number of mantissa bits to use in the byte, with the remainder to be used in the exponent. </param>
/// <param name="zeroExp"> The zero-point in the range of exponent values. </param>
/// <returns> The 8 bit float representation. </returns>
// LUCENENET specific overload for CLS compliance
public static byte SingleToByte(float f, int numMantissaBits, int zeroExp)
{
return (byte)SingleToSByte(f, numMantissaBits, zeroExp);
}
/// <summary>
/// Converts a 32 bit <see cref="float"/> to an 8 bit <see cref="float"/>.
/// <para/>Values less than zero are all mapped to zero.
/// <para/>Values are truncated (rounded down) to the nearest 8 bit value.
/// <para/>Values between zero and the smallest representable value
/// are rounded up.
/// <para/>
/// NOTE: This was floatToByte() in Lucene
/// </summary>
/// <param name="f"> The 32 bit <see cref="float"/> to be converted to an 8 bit <see cref="float"/> (<see cref="sbyte"/>). </param>
/// <param name="numMantissaBits"> The number of mantissa bits to use in the byte, with the remainder to be used in the exponent. </param>
/// <param name="zeroExp"> The zero-point in the range of exponent values. </param>
/// <returns> The 8 bit float representation. </returns>
[CLSCompliant(false)]
public static sbyte SingleToSByte(float f, int numMantissaBits, int zeroExp)
{
// Adjustment from a float zero exponent to our zero exponent,
// shifted over to our exponent position.
int fzero = (63 - zeroExp) << numMantissaBits;
int bits = J2N.BitConversion.SingleToRawInt32Bits(f);
int smallfloat = bits >> (24 - numMantissaBits);
if (smallfloat <= fzero)
{
return (bits <= 0) ? (sbyte)0 : (sbyte)1; // underflow is mapped to smallest non-zero number. - negative numbers and zero both map to 0 byte
}
else if (smallfloat >= fzero + 0x100)
{
return -1; // overflow maps to largest number
}
else
{
return (sbyte)(smallfloat - fzero);
}
}
/// <summary>
/// Converts an 8 bit <see cref="float"/> to a 32 bit <see cref="float"/>.
/// <para/>
/// NOTE: This was byteToFloat() in Lucene
/// </summary>
// LUCENENET specific overload for CLS compliance
public static float ByteToSingle(byte b, int numMantissaBits, int zeroExp)
{
return SByteToSingle((sbyte)b, numMantissaBits, zeroExp);
}
/// <summary>
/// Converts an 8 bit <see cref="float"/> to a 32 bit <see cref="float"/>.
/// <para/>
/// NOTE: This was byteToFloat() in Lucene
/// </summary>
[CLSCompliant(false)]
public static float SByteToSingle(sbyte b, int numMantissaBits, int zeroExp)
{
// on Java1.5 & 1.6 JVMs, prebuilding a decoding array and doing a lookup
// is only a little bit faster (anywhere from 0% to 7%)
if (b == 0)
{
return 0.0f;
}
int bits = (b & 0xff) << (24 - numMantissaBits);
bits += (63 - zeroExp) << 24;
return J2N.BitConversion.Int32BitsToSingle(bits);
}
//
// Some specializations of the generic functions follow.
// The generic functions are just as fast with current (1.5)
// -server JVMs, but still slower with client JVMs.
//
/// <summary>
/// SingleToSByte((byte)b, mantissaBits=3, zeroExponent=15)
/// <para/>smallest non-zero value = 5.820766E-10
/// <para/>largest value = 7.5161928E9
/// <para/>epsilon = 0.125
/// <para/>
/// NOTE: This was floatToByte315() in Lucene
/// </summary>
// LUCENENET specific overload for CLS compliance
public static byte SingleToByte315(float f)
{
return (byte)SingleToSByte315(f);
}
/// <summary>
/// SingleToSByte(b, mantissaBits=3, zeroExponent=15)
/// <para/>smallest non-zero value = 5.820766E-10
/// <para/>largest value = 7.5161928E9
/// <para/>epsilon = 0.125
/// <para/>
/// NOTE: This was floatToByte315() in Lucene
/// </summary>
[CLSCompliant(false)]
public static sbyte SingleToSByte315(float f)
{
int bits = J2N.BitConversion.SingleToRawInt32Bits(f);
int smallfloat = bits >> (24 - 3);
if (smallfloat <= ((63 - 15) << 3))
{
return (bits <= 0) ? (sbyte)0 : (sbyte)1;
}
if (smallfloat >= ((63 - 15) << 3) + 0x100)
{
return -1;
}
return (sbyte)(smallfloat - ((63 - 15) << 3));
}
/// <summary>
/// ByteToSingle(b, mantissaBits=3, zeroExponent=15)
/// <para/>
/// NOTE: This was byte315ToFloat() in Lucene
/// </summary>
// LUCENENET specific overload for CLS compliance
public static float Byte315ToSingle(byte b)
{
return SByte315ToSingle((sbyte)b);
}
/// <summary>
/// SByteToSingle(b, mantissaBits=3, zeroExponent=15)
/// <para/>
/// NOTE: This was byte315ToFloat() in Lucene
/// </summary>
[CLSCompliant(false)]
public static float SByte315ToSingle(sbyte b)
{
// on Java1.5 & 1.6 JVMs, prebuilding a decoding array and doing a lookup
// is only a little bit faster (anywhere from 0% to 7%)
if (b == 0)
{
return 0.0f;
}
int bits = (b & 0xff) << (24 - 3);
bits += (63 - 15) << 24;
return J2N.BitConversion.Int32BitsToSingle(bits);
}
/// <summary>
/// SingleToByte(b, mantissaBits=5, zeroExponent=2)
/// <para/>smallest nonzero value = 0.033203125
/// <para/>largest value = 1984.0
/// <para/>epsilon = 0.03125
/// <para/>
/// NOTE: This was floatToByte52() in Lucene
/// </summary>
// LUCENENET specific overload for CLS compliance
public static byte SingleToByte52(float f)
{
return (byte)SingleToSByte315(f);
}
/// <summary>
/// SingleToSByte(b, mantissaBits=5, zeroExponent=2)
/// <para/>smallest nonzero value = 0.033203125
/// <para/>largest value = 1984.0
/// <para/>epsilon = 0.03125
/// <para/>
/// NOTE: This was floatToByte52() in Lucene
/// </summary>
[CLSCompliant(false)]
public static sbyte SingleToSByte52(float f)
{
int bits = J2N.BitConversion.SingleToRawInt32Bits(f);
int smallfloat = bits >> (24 - 5);
if (smallfloat <= (63 - 2) << 5)
{
return (bits <= 0) ? (sbyte)0 : (sbyte)1;
}
if (smallfloat >= ((63 - 2) << 5) + 0x100)
{
return -1;
}
return (sbyte)(smallfloat - ((63 - 2) << 5));
}
/// <summary>
/// ByteToFloat(b, mantissaBits=5, zeroExponent=2)
/// <para/>
/// NOTE: This was byte52ToFloat() in Lucene
/// </summary>
// LUCENENET specific overload for CLS compliance
public static float Byte52ToSingle(byte b)
{
return SByte52ToSingle((sbyte)b);
}
/// <summary>
/// SByteToFloat(b, mantissaBits=5, zeroExponent=2)
/// <para/>
/// NOTE: This was byte52ToFloat() in Lucene
/// </summary>
[CLSCompliant(false)]
public static float SByte52ToSingle(sbyte b)
{
// on Java1.5 & 1.6 JVMs, prebuilding a decoding array and doing a lookup
// is only a little bit faster (anywhere from 0% to 7%)
if (b == 0)
{
return 0.0f;
}
int bits = (b & 0xff) << (24 - 5);
bits += (63 - 2) << 24;
return J2N.BitConversion.Int32BitsToSingle(bits);
}
}
}
| |
using System.Diagnostics;
using System;
using System.Management;
using System.Collections;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Web.UI.Design;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Runtime;
using System.Globalization;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
// POP3 Email Client
// =================
//
// copyright by Peter Huber, Singapore, 2006
// this code is provided as is, bugs are probable, free for any use at own risk, no
// responsibility accepted. All rights, title and interest in and to the accompanying content retained. :-)
//
// based on Standard for ARPA Internet Text Messages, http://rfc.net/rfc822.html
// based on MIME Standard, Internet Message Bodies, http://rfc.net/rfc2045.html
// based on MIME Standard, Media Types, http://rfc.net/rfc2046.html
// based on QuotedPrintable Class from ASP emporium, http://www.aspemporium.com/classes.aspx?cid=6
// based on MIME Standard, E-mail Encapsulation of HTML (MHTML), http://rfc.net/rfc2110.html
// based on MIME Standard, Multipart/Related Content-type, http://rfc.net/rfc2112.html
// ?? RFC 2557 MIME Encapsulation of Aggregate Documents http://rfc.net/rfc2557.html
namespace ACSGhana.Web.Framework
{
namespace Mail
{
namespace Pop3
{
// POP3 Client Email
// =================
/// <summary>
/// Reads POP3 / MIME based emails
/// </summary>
public class Pop3MimeClient : Pop3MailClient
{
//character array 'constants' used for analysing POP3 / MIME
//----------------------------------------------------------
private static char[] BlankChars = {' '};
private static char[] BracketChars = {'(', ')'};
private static char[] ColonChars = {':'};
private static char[] CommaChars = {','};
private static char[] EqualChars = {'='};
private static char[] ForwardSlashChars = {'/'};
private static char[] SemiColonChars = {';'};
private static char[] WhiteSpaceChars = {' ', ControlChars.Tab};
private static char[] NonValueChars = {'\"', '(', ')'};
//Help for debugging
//------------------
/// <summary>
/// used for debugging. Collects all unknown header lines for all (!) emails received
/// </summary>
public static bool isCollectUnknowHeaderLines = true;
/// <summary>
/// list of all unknown header lines received, for all (!) emails
/// </summary>
public static List<string> AllUnknowHeaderLines;
/// <summary>
/// Set this flag, if you would like to get also the email in the raw US-ASCII format
/// as received.
/// Good for debugging, but takes quiet some space.
/// </summary>
public bool IsCollectRawEmail
{
get
{
return isGetRawEmail;
}
set
{
isGetRawEmail = value;
}
}
private bool isGetRawEmail = false;
// Pop3MimeClient Constructor
//---------------------------
/// <summary>
/// constructor
/// </summary>
public Pop3MimeClient(string PopServer, int Port, bool useSSL, string Username, string Password) : base(PopServer, Port, useSSL, Username, Password)
{
AllUnknowHeaderLines = new List<string>();
}
/// <summary>
/// Gets 1 email from POP3 server and processes it.
/// </summary>
/// <param name="MessageNo">Email Id to be fetched from POP3 server</param>
/// <param name="Message">decoded email</param>
/// <returns>false: no email received or email not properly formatted</returns>
public bool GetEmail(int MessageNo, ref RxMailMessage Message)
{
Message = null;
//request email, send RETRieve command to POP3 server
if (! SendRetrCommand(MessageNo))
{
return false;
}
//prepare message, set defaults as specified in RFC 2046
//although they get normally overwritten, we have to make sure there are at least defaults
Message = new RxMailMessage();
Message.ContentTransferEncoding = TransferEncoding.SevenBit;
Message.TransferType = "7bit";
this.m_messageNo = MessageNo;
//raw email tracing
if (isGetRawEmail)
{
isTraceRawEmail = true;
if (RawEmailSB == null)
{
RawEmailSB = new StringBuilder(100000);
}
else
{
RawEmailSB.Length = 0;
}
}
//convert received email into RxMailMessage
MimeEntityReturnCode MessageMimeReturnCode = ProcessMimeEntity(Message, "");
if (isGetRawEmail)
{
//add raw email version to message
Message.RawContent = RawEmailSB.ToString();
isTraceRawEmail = false;
}
if (MessageMimeReturnCode == MimeEntityReturnCode.bodyComplete || MessageMimeReturnCode == MimeEntityReturnCode.parentBoundaryEndFound)
{
TraceFrom("email with {0} body chars received", Message.Body.Length);
return true;
}
return false;
}
private int m_messageNo;
private void callGetEmailWarning(string warningText, params object[] warningParameters)
{
string warningString;
try
{
warningString = string.Format(warningText, warningParameters);
}
catch (System.Exception)
{
//some strange email address can give string.Format() a problem
warningString = warningText;
}
CallWarning("GetEmail", "", "Problem EmailNo {0}: " + warningString, m_messageNo);
}
/// <summary>
/// indicates the reason how a MIME entity processing has terminated
/// </summary>
private enum MimeEntityReturnCode
{
undefined = 0, //meaning like null
bodyComplete, //end of message line found
parentBoundaryStartFound,
parentBoundaryEndFound,
problem //received message doesn't follow MIME specification
}
//buffer used by every ProcessMimeEntity() to store MIME entity
private StringBuilder MimeEntitySB = new StringBuilder(100000);
/// <summary>
/// Process a MIME entity
///
/// A MIME entity consists of header and body.
/// Separator lines in the body might mark children MIME entities
/// </summary>
private MimeEntityReturnCode ProcessMimeEntity(RxMailMessage message, string parentBoundaryStart)
{
bool hasParentBoundary = parentBoundaryStart.Length > 0;
string parentBoundaryEnd = parentBoundaryStart + "--";
MimeEntityReturnCode boundaryMimeReturnCode;
//some format fields are inherited from parent, only the default for
//ContentType needs to be set here, otherwise the boundary parameter would be
//inherited too !
message.SetContentTypeFields("text/plain; charset=us-ascii");
//get header
//----------
string completeHeaderField = null; //consists of one start line and possibly several continuation lines
string response = Constants.vbNullString;
// read header lines until empty line is found (end of header)
while (true)
{
if (! readMultiLine(ref response))
{
//POP3 server has not send any more lines
callGetEmailWarning("incomplete MIME entity header received", null);
//empty this message
while (readMultiLine(ref response))
{
}
System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
return MimeEntityReturnCode.problem;
}
if (response.Length < 1)
{
//empty line found => end of header
if (completeHeaderField != null)
{
ProcessHeaderField(message, completeHeaderField);
}
else
{
//there was only an empty header.
}
break;
}
//check if there is a parent boundary in the header (wrong format!)
if (hasParentBoundary && parentBoundaryFound(response, parentBoundaryStart, parentBoundaryEnd, ref boundaryMimeReturnCode))
{
callGetEmailWarning("MIME entity header prematurely ended by parent boundary", null);
//empty this message
while (readMultiLine(ref response))
{
}
System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
return boundaryMimeReturnCode;
}
//read header field
//one header field can extend over one start line and multiple continuation lines
//a continuation line starts with at least 1 blank (' ') or tab
if (response[0] == ' ' || response[0] == ControlChars.Tab)
{
//continuation line found.
if (completeHeaderField == null)
{
callGetEmailWarning("Email header starts with continuation line", null);
//empty this message
while (readMultiLine(ref response))
{
}
System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
return MimeEntityReturnCode.problem;
}
else
{
// append space, if needed, and continuation line
if (completeHeaderField[completeHeaderField.Length - 1] != ' ')
{
//previous line did not end with a whitespace
//need to replace CRLF with a ' '
completeHeaderField += ' ' + response.TrimStart(WhiteSpaceChars);
}
else
{
//previous line did end with a whitespace
completeHeaderField += response.TrimStart(WhiteSpaceChars);
}
}
}
else
{
//a new header field line found
if (completeHeaderField == null)
{
//very first field, just copy it and then check for continuation lines
completeHeaderField = response;
}
else
{
//new header line found
ProcessHeaderField(message, completeHeaderField);
//save the beginning of the next line
completeHeaderField = response;
}
}
} //end while read header lines
//process body
//------------
MimeEntitySB.Length = 0; //empty StringBuilder. For speed reasons, reuse StringBuilder defined as member of class
string BoundaryDelimiterLineStart = null;
bool isBoundaryDefined = false;
if (message.ContentType.Boundary != null)
{
isBoundaryDefined = true;
BoundaryDelimiterLineStart = "--" + message.ContentType.Boundary;
}
//prepare return code for the case there is no boundary in the body
boundaryMimeReturnCode = MimeEntityReturnCode.bodyComplete;
//read body lines
while (readMultiLine(ref response))
{
//check if there is a boundary line from this entity itself in the body
if (isBoundaryDefined && response.TrimEnd(null) == BoundaryDelimiterLineStart)
{
//boundary line found.
//stop the processing here and start a delimited body processing
return ProcessDelimitedBody(message, BoundaryDelimiterLineStart, parentBoundaryStart, parentBoundaryEnd);
}
//check if there is a parent boundary in the body
if (hasParentBoundary && parentBoundaryFound(response, parentBoundaryStart, parentBoundaryEnd, ref boundaryMimeReturnCode))
{
//a parent boundary is found. Decode the content of the body received so far, then end this MIME entity
//note that boundaryMimeReturnCode is set here, but used in the return statement
break;
}
//process next line
MimeEntitySB.Append(response + CRLF);
}
//a complete MIME body read
//convert received US ASCII characters to .NET string (Unicode)
string TransferEncodedMessage = MimeEntitySB.ToString();
bool isAttachmentSaved = false;
switch (message.ContentTransferEncoding)
{
case TransferEncoding.SevenBit:
//nothing to do
saveMessageBody(message, TransferEncodedMessage);
break;
case TransferEncoding.Base64:
//convert base 64 -> byte[]
byte[] bodyBytes = System.Convert.FromBase64String(TransferEncodedMessage);
message.ContentStream = new MemoryStream(bodyBytes, false);
if (message.MediaMainType == "text")
{
//convert byte[] -> string
message.Body = DecodeByteArryToString(bodyBytes, message.BodyEncoding);
}
else if (message.MediaMainType == "image" || message.MediaMainType == "application")
{
SaveAttachment(message);
isAttachmentSaved = true;
}
break;
case TransferEncoding.QuotedPrintable:
saveMessageBody(message, QuotedPrintable.Decode(TransferEncodedMessage));
break;
default:
saveMessageBody(message, TransferEncodedMessage);
break;
//no need to raise a warning here, the warning was done when analising the header
}
if (message.ContentDisposition != null&& message.ContentDisposition.DispositionType.ToLowerInvariant() == "attachment" && (! isAttachmentSaved))
{
SaveAttachment(message);
isAttachmentSaved = true;
}
return boundaryMimeReturnCode;
}
/// <summary>
/// Check if the response line received is a parent boundary
/// </summary>
private bool parentBoundaryFound(string response, string parentBoundaryStart, string parentBoundaryEnd, [System.Runtime.InteropServices.Out()]ref MimeEntityReturnCode boundaryMimeReturnCode)
{
boundaryMimeReturnCode = MimeEntityReturnCode.undefined;
if (response == null || response.Length < 2 || response[0] != '-' || response[1] != '-')
{
//quick test: reponse doesn't start with "--", so cannot be a separator line
return false;
}
if (response == parentBoundaryStart)
{
boundaryMimeReturnCode = MimeEntityReturnCode.parentBoundaryStartFound;
return true;
}
else if (response == parentBoundaryEnd)
{
boundaryMimeReturnCode = MimeEntityReturnCode.parentBoundaryEndFound;
return true;
}
return false;
}
/// <summary>
/// Convert one MIME header field and update message accordingly
/// </summary>
private void ProcessHeaderField(RxMailMessage message, string headerField)
{
string headerLineType;
string headerLineContent;
int separatorPosition = headerField.IndexOf(':');
if (separatorPosition < 1)
{
// header field type not found, skip this line
callGetEmailWarning("character \':\' missing in header format field: \'{0}\'", headerField);
}
else
{
//process header field type
headerLineType = headerField.Substring(0, separatorPosition).ToLowerInvariant();
headerLineContent = headerField.Substring(separatorPosition + 1).Trim(WhiteSpaceChars);
if (headerLineType == "" || headerLineContent == "")
{
//1 of the 2 parts missing, drop the line
return;
}
// add header line to headers
message.Headers.Add(headerLineType, headerLineContent);
//interpret if possible
switch (headerLineType)
{
case "bcc":
AddMailAddresses(headerLineContent, message.Bcc);
break;
case "cc":
AddMailAddresses(headerLineContent, message.CC);
break;
case "content-description":
message.ContentDescription = headerLineContent;
break;
case "content-disposition":
message.ContentDisposition = new ContentDisposition(headerLineContent);
break;
case "content-id":
message.ContentId = headerLineContent;
break;
case "content-transfer-encoding":
message.TransferType = headerLineContent;
message.ContentTransferEncoding = ConvertToTransferEncoding(headerLineContent);
break;
case "content-type":
message.SetContentTypeFields(headerLineContent);
break;
case "date":
message.DeliveryDate = ConvertToDateTime(headerLineContent);
break;
case "delivered-to":
message.DeliveredTo = ConvertToMailAddress(headerLineContent);
break;
case "from":
MailAddress address = ConvertToMailAddress(headerLineContent);
if (address != null)
{
message.From = address;
}
break;
case "message-id":
message.MessageId = headerLineContent;
break;
case "mime-version":
message.MimeVersion = headerLineContent;
break;
//message.BodyEncoding = new Encoding();
case "sender":
message.Sender = ConvertToMailAddress(headerLineContent);
break;
case "subject":
message.Subject = headerLineContent;
break;
case "received":
break;
//throw mail routing information away
case "reply-to":
message.ReplyTo = ConvertToMailAddress(headerLineContent);
break;
case "return-path":
message.ReturnPath = ConvertToMailAddress(headerLineContent);
break;
case "to":
AddMailAddresses(headerLineContent, message.To);
break;
default:
Message.UnknowHeaderlines.Add(headerField);
if (isCollectUnknowHeaderLines)
{
AllUnknowHeaderLines.Add(headerField);
}
break;
}
}
}
/// <summary>
/// find individual addresses in the string and add it to address collection
/// </summary>
/// <param name="Addresses">string with possibly several email addresses</param>
/// <param name="AddressCollection">parsed addresses</param>
private void AddMailAddresses(string Addresses, MailAddressCollection AddressCollection)
{
MailAddress adr;
try
{
string[] AddressSplit = Addresses.Split(',');
foreach (string adrString in AddressSplit)
{
adr = ConvertToMailAddress(adrString);
if (adr != null)
{
AddressCollection.Add(adr);
}
}
}
catch
{
System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
}
}
/// <summary>
/// Tries to convert a string into an email address
/// </summary>
public MailAddress ConvertToMailAddress(string address)
{
address = address.Trim();
if (address == "<>")
{
//empty email address, not recognised a such by .NET
return null;
}
try
{
return new MailAddress(address);
}
catch
{
callGetEmailWarning("address format not recognised: \'" + address.Trim() + "\'", null);
}
return null;
}
private IFormatProvider culture = new CultureInfo("en-US", true);
/// <summary>
/// Tries to convert string to date, following POP3 rules
/// If there is a run time error, the smallest possible date is returned
/// <example>Wed, 04 Jan 2006 07:58:08 -0800</example>
/// </summary>
public DateTime ConvertToDateTime(string @DateTime)
{
DateTime ReturnDateTime;
try
{
//sample; 'Wed, 04 Jan 2006 07:58:08 -0800 (PST)'
//remove day of the week before ','
//remove date zone in '()', -800 indicates the zone already
//remove day of week
string cleanDateTime = DateTime;
string[] DateSplit = cleanDateTime.Split(CommaChars, 2);
if (DateSplit.Length > 1)
{
cleanDateTime = DateSplit[1];
}
//remove time zone (PST)
DateSplit = cleanDateTime.Split(BracketChars);
if (DateSplit.Length > 1)
{
cleanDateTime = DateSplit[0];
}
//convert to DateTime
if (! DateTime.TryParse(cleanDateTime, culture, DateTimeStyles.AdjustToUniversal || DateTimeStyles.AllowWhiteSpaces, ref ReturnDateTime))
{
//try just to convert the date
int DateLength = cleanDateTime.IndexOf(':') - 3;
cleanDateTime = cleanDateTime.Substring(0, DateLength);
if (DateTime.TryParse(cleanDateTime, culture, DateTimeStyles.AdjustToUniversal || DateTimeStyles.AllowWhiteSpaces, ref ReturnDateTime))
{
callGetEmailWarning("got only date, time format not recognised: \'" + DateTime + "\'", null);
}
else
{
callGetEmailWarning("date format not recognised: \'" + DateTime + "\'", null);
System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
return DateTime.MinValue;
}
}
}
catch
{
callGetEmailWarning("date format not recognised: \'" + DateTime + "\'", null);
return DateTime.MinValue;
}
return ReturnDateTime;
}
/// <summary>
/// converts TransferEncoding as defined in the RFC into a .NET TransferEncoding
///
/// .NET doesn't know the type "bit8". It is translated here into "bit7", which
/// requires the same kind of processing (none).
/// </summary>
/// <param name="TransferEncodingString"></param>
/// <returns></returns>
private TransferEncoding ConvertToTransferEncoding(string TransferEncodingString)
{
// here, "bit8" is marked as "bit7" (i.e. no transfer encoding needed)
// "binary" is illegal in SMTP
// something like "7bit" / "8bit" / "binary" / "quoted-printable" / "base64"
if ((TransferEncodingString.Trim().ToLowerInvariant() == "7bit") || (TransferEncodingString.Trim().ToLowerInvariant() == "8bit"))
{
return TransferEncoding.SevenBit;
}
else if (TransferEncodingString.Trim().ToLowerInvariant() == "quoted-printable")
{
return TransferEncoding.QuotedPrintable;
}
else if (TransferEncodingString.Trim().ToLowerInvariant() == "base64")
{
return TransferEncoding.Base64;
}
else if (TransferEncodingString.Trim().ToLowerInvariant() == "binary")
{
throw (new Pop3Exception("SMPT does not support binary transfer encoding"));
}
else
{
callGetEmailWarning("not supported content-transfer-encoding: " + TransferEncodingString, null);
return TransferEncoding.Unknown;
}
}
/// <summary>
/// Copies the content found for the MIME entity to the RxMailMessage body and creates
/// a stream which can be used to create attachements, alternative views, ...
/// </summary>
private void saveMessageBody(RxMailMessage message, string contentString)
{
message.Body = contentString;
MemoryStream bodyStream = new MemoryStream();
StreamWriter bodyStreamWriter = new StreamWriter(bodyStream);
bodyStreamWriter.Write(contentString);
int l = contentString.Length;
bodyStreamWriter.Flush();
message.ContentStream = bodyStream;
}
/// <summary>
/// each attachement is stored in its own MIME entity and read into this entity's
/// ContentStream. SaveAttachment creates an attachment out of the ContentStream
/// and attaches it to the parent MIME entity.
/// </summary>
private void SaveAttachment(RxMailMessage message)
{
if (message.Parent == null)
{
System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
}
else
{
Attachment thisAttachment = new Attachment(message.ContentStream, message.ContentType);
//no idea why ContentDisposition is read only. on the other hand, it is anyway redundant
if (message.ContentDisposition != null)
{
ContentDisposition messageContentDisposition = message.ContentDisposition;
ContentDisposition AttachmentContentDisposition = thisAttachment.ContentDisposition;
if (messageContentDisposition.CreationDate > DateTime.MinValue)
{
AttachmentContentDisposition.CreationDate = messageContentDisposition.CreationDate;
}
AttachmentContentDisposition.DispositionType = messageContentDisposition.DispositionType;
AttachmentContentDisposition.FileName = messageContentDisposition.FileName;
AttachmentContentDisposition.Inline = messageContentDisposition.Inline;
if (messageContentDisposition.ModificationDate > DateTime.MinValue)
{
AttachmentContentDisposition.ModificationDate = messageContentDisposition.ModificationDate;
}
AttachmentContentDisposition.Parameters.Clear();
if (messageContentDisposition.ReadDate > DateTime.MinValue)
{
AttachmentContentDisposition.ReadDate = messageContentDisposition.ReadDate;
}
if (messageContentDisposition.Size > 0)
{
AttachmentContentDisposition.Size = messageContentDisposition.Size;
}
foreach (string key in messageContentDisposition.Parameters.Keys)
{
AttachmentContentDisposition.Parameters.Add(key, messageContentDisposition.Parameters[key]);
}
}
//get ContentId
string contentIdString = message.ContentId;
if (contentIdString != null)
{
thisAttachment.ContentId = RemoveBrackets(contentIdString);
}
thisAttachment.TransferEncoding = message.ContentTransferEncoding;
message.Parent.Attachments.Add(thisAttachment);
}
}
/// <summary>
/// removes leading '<' and trailing '>' if both exist
/// </summary>
/// <param name="parameterString"></param>
/// <returns></returns>
private string RemoveBrackets(string parameterString)
{
if (parameterString == null)
{
return null;
}
if (parameterString.Length < 1 || parameterString[0] != '<' || parameterString[parameterString.Length - 1] != '>')
{
System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
return parameterString;
}
else
{
return parameterString.Substring(1, parameterString.Length - 2);
}
}
private MimeEntityReturnCode ProcessDelimitedBody(RxMailMessage message, string BoundaryStart, string parentBoundaryStart, string parentBoundaryEnd)
{
string response = Constants.vbNullString;
if (BoundaryStart.Trim() == parentBoundaryStart.Trim())
{
//Mime entity boundaries have to be unique
callGetEmailWarning("new boundary same as parent boundary: \'{0}\'", parentBoundaryStart);
//empty this message
while (readMultiLine(ref response))
{
}
return MimeEntityReturnCode.problem;
}
//
MimeEntityReturnCode ReturnCode;
do
{
//empty StringBuilder
MimeEntitySB.Length = 0;
RxMailMessage ChildPart = message.CreateChildEntity();
//recursively call MIME part processing
ReturnCode = ProcessMimeEntity(ChildPart, BoundaryStart);
if (ReturnCode == MimeEntityReturnCode.problem)
{
//it seems the received email doesn't follow the MIME specification. Stop here
return MimeEntityReturnCode.problem;
}
//add the newly found child MIME part to the parent
AddChildPartsToParent(ChildPart, message);
} while (ReturnCode != MimeEntityReturnCode.parentBoundaryEndFound);
//disregard all future lines until parent boundary is found or end of complete message
MimeEntityReturnCode boundaryMimeReturnCode;
bool hasParentBoundary = parentBoundaryStart.Length > 0;
while (readMultiLine(ref response))
{
if (hasParentBoundary && parentBoundaryFound(response, parentBoundaryStart, parentBoundaryEnd, ref boundaryMimeReturnCode))
{
return boundaryMimeReturnCode;
}
}
return MimeEntityReturnCode.bodyComplete;
}
/// <summary>
/// Add all attachments and alternative views from child to the parent
/// </summary>
private void AddChildPartsToParent(RxMailMessage child, RxMailMessage parent)
{
//add the child itself to the parent
parent.Entities.Add(child);
//add the alternative views of the child to the parent
if (child.AlternateViews != null)
{
foreach (AlternateView childView in child.AlternateViews)
{
parent.AlternateViews.Add(childView);
}
}
//add the body of the child as alternative view to parent
//this should be the last view attached here, because the POP 3 MIME client
//is supposed to display the last alternative view
if (child.MediaMainType == "text" && child.ContentStream != null&& child.Parent.ContentType != null&& child.Parent.ContentType.MediaType.ToLowerInvariant() == "multipart/alternative")
{
AlternateView thisAlternateView = new AlternateView(child.ContentStream);
thisAlternateView.ContentId = RemoveBrackets(child.ContentId);
thisAlternateView.ContentType = child.ContentType;
thisAlternateView.TransferEncoding = child.ContentTransferEncoding;
parent.AlternateViews.Add(thisAlternateView);
}
//add the attachments of the child to the parent
if (child.Attachments != null)
{
foreach (Attachment childAttachment in child.Attachments)
{
parent.Attachments.Add(childAttachment);
}
}
}
/// <summary>
/// Converts byte array to string, using decoding as requested
/// </summary>
public string DecodeByteArryToString(byte[] ByteArry, Encoding ByteEncoding)
{
if (ByteArry == null)
{
//no bytes to convert
return null;
}
Decoder byteArryDecoder;
if (ByteEncoding == null)
{
//no encoding indicated. Let's try UTF7
System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
byteArryDecoder = Encoding.UTF7.GetDecoder();
}
else
{
byteArryDecoder = ByteEncoding.GetDecoder();
}
int charCount = byteArryDecoder.GetCharCount(ByteArry, 0, ByteArry.Length);
char[] bodyChars = new char[charCount - 1+ 1];
int charsDecodedCount = byteArryDecoder.GetChars(ByteArry, 0, ByteArry.Length, bodyChars, 0);
//convert char[] to string
return new string(bodyChars);
}
}
}
}
}
| |
//
// Copyright 2010 Ekon Benefits
//
// 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.Dynamic;
using System.Linq;
using System.Runtime.Serialization;
using ImpromptuInterface.Build;
using ImpromptuInterface.Internal.Support;
using System.Reflection;
namespace ImpromptuInterface.Dynamic
{
/// <summary>
/// Dynamic Object that knows about the Impromtu Interface return types;
/// Override Typical Dynamic Object methods, and use TypeForName to get the return type of an interface member.
/// </summary>
[Serializable]
public abstract class ImpromptuObject : DynamicObject, IDynamicKnowLike, IActLike,ISerializable,ICustomTypeProvider
{
/// <summary>
/// Initializes a new instance of the <see cref="ImpromptuObject"/> class.
/// </summary>
protected ImpromptuObject()
{
}
#if !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the <see cref="ImpromptuObject"/> class. when deserializing
/// </summary>
/// <param name="info">The info.</param>
/// <param name="context">The context.</param>
protected ImpromptuObject(SerializationInfo info,
StreamingContext context)
{
}
/// <summary>
/// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> to populate with data.</param>
/// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for this serialization.</param>
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission. </exception>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
}
#endif
/// <summary>
/// Cache to avoid refelection for same Interfaces.
/// </summary>
protected static readonly IDictionary<TypeHash, IDictionary<string, Type>> _returnTypHash =
new Dictionary<TypeHash, IDictionary<string, Type>>();
private static readonly object TypeHashLock = new object();
/// <summary>
/// Hash for this instance to lookup cached values from <see cref="_returnTypHash"/>
/// </summary>
protected TypeHash _hash;
/// <summary>
/// Keep Track of Known Property Spec
/// </summary>
protected IDictionary<string, Type> PropertySpec;
IEnumerable<Type> IDynamicKnowLike.KnownInterfaces
{
set { KnownInterfaces = value; }
}
/// <summary>
/// Gets or sets the known interfaces.
/// Set should only be called be the factory methood
/// </summary>
/// <value>The known interfaces.</value>
protected virtual IEnumerable<Type> KnownInterfaces
{
get
{
if (PropertySpec != null)
return Enumerable.Empty<Type>();
if (_hash == null)
{
return Enumerable.Empty<Type>();
}
return _hash.Types.Cast<Type>();
}
set
{
lock (TypeHashLock)
{
PropertySpec = null;
_hash = TypeHash.Create(value);
if (_returnTypHash.ContainsKey(_hash)) return;
var tPropReturType = value.SelectMany(@interface => @interface.GetProperties())
.Where(property=>property.GetGetMethod() !=null)
.Select(property=>new{property.Name, property.GetGetMethod().ReturnType});
//If type can be determined by name
var tMethodReturnType = value.SelectMany(@interface => @interface.GetMethods())
.Where(method=>!method.IsSpecialName)
.GroupBy(method=>method.Name)
.Where(group=>group.Select(method=>method.ReturnType).Distinct().Count() ==1 )
.Select(group => new
{
Name =group.Key,
ReturnType =group.Select(method=>method.ReturnType).Distinct().Single()
});
var tDict = tPropReturType.Concat(tMethodReturnType)
.ToDictionary(info => info.Name, info => info.ReturnType);
_returnTypHash.Add(_hash, tDict);
}
}
}
IDictionary<string, Type> IDynamicKnowLike.KnownPropertySpec
{
set { KnownPropertySpec = value; }
}
/// <summary>
/// Gets or sets the known fake interface (string method name to return type mapping).
/// </summary>
/// <value>The known fake interface.</value>
protected virtual IDictionary<string, Type> KnownPropertySpec
{
get { return PropertySpec; }
set { PropertySpec = value; }
}
/// <summary>
/// Returns the enumeration of all dynamic member names.
/// </summary>
/// <returns>
/// A sequence that contains dynamic member names.
/// </returns>
public override IEnumerable<string> GetDynamicMemberNames()
{
var tHash = HashForThisType();
return tHash == null
? new String[] { }
: tHash.Select(it => it.Key);
}
private IDictionary<string, Type> HashForThisType()
{
if (PropertySpec != null)
return PropertySpec;
IDictionary<string, Type> tOut;
if (_hash == null || !_returnTypHash.TryGetValue(_hash, out tOut))
return null;
return tOut;
}
/// <summary>
/// Tries to get the type for the property name from the interface.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="returnType">The return Type.</param>
/// <returns></returns>
public virtual bool TryTypeForName(string name, out Type returnType)
{
var tHash = HashForThisType();
if (tHash == null || !tHash.TryGetValue(name, out returnType))
{
returnType = null;
return false;
}
return true;
}
/// <summary>
/// Allows ActLike to be called via dyanmic invocation
/// </summary>
/// <typeparam name="TInterface">The type of the interface.</typeparam>
/// <param name="otherInterfaces">The other interfaces.</param>
/// <returns></returns>
public virtual TInterface ActLike<TInterface>(params Type[] otherInterfaces) where TInterface:class
{
return Impromptu.ActLike<TInterface>(this, otherInterfaces);
}
#if SILVERLIGHT5
/// <summary>
/// Gets the custom Type.
/// </summary>
/// <returns></returns>
public Type GetCustomType()
{
return this.GetDynamicCustomType();
}
#endif
}
}
| |
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
[RequireComponent(typeof(ParticleSystem))]
public class AtomizerEffectGroup : MonoBehaviour
{
#if UNITY_ANDROID || UNITY_IPHONE
public static readonly int DefaultMaxParticleCount = 8192;
public static readonly float DefaultParticleSize = 0.01f;
#else
public static readonly float DefaultParticleSize = 0.04f;
public static readonly int DefaultMaxParticleCount = 32768;
#endif
public static readonly bool DefaultForceParticleSize = true;
private static readonly Camera DefaultSceneCamera = Camera.main;
public float ParticleSize
{ get; set; }
public float MaxParticleCount
{ get; set; }
public bool ForceParticleSize
{ get; set; }
protected int ParticleCount
{ get; set; }
protected ParticleSystem.Particle[] Particles
{ get; set; }
public Camera SceneCamera
{ get; set; }
protected float ActiveTime
{ get; set; }
protected bool IsPlaying
{ get; set; }
protected bool IsFinished
{ get; set; }
public Action OnFinish;
private void Awake()
{
chainedEffectIndex = 0;
currentEffectIndex = 0;
SceneCamera = DefaultSceneCamera;
ActiveTime = 0.0f;
IsPlaying = false;
allEffects = new Dictionary<int, List<AtomizerEffect>>();
}
public AtomizerEffectGroup Combine(AtomizerEffect effect)
{
if (allEffects.ContainsKey(chainedEffectIndex))
{
List<AtomizerEffect> effects = allEffects[chainedEffectIndex];
effects.Add(effect);
}
else
{
List<AtomizerEffect> effects = new List<AtomizerEffect>();
effects.Add(effect);
allEffects.Add(chainedEffectIndex, effects);
}
return this;
}
public AtomizerEffectGroup Chain(AtomizerEffect effect)
{
if (allEffects.ContainsKey(chainedEffectIndex))
{
++chainedEffectIndex;
}
return Combine(effect);
}
public void Play()
{
if (allEffects.ContainsKey(currentEffectIndex))
{
foreach (AtomizerEffect effect in allEffects[currentEffectIndex])
{
effect.IsPlaying = true;
}
IsPlaying = true;
}
}
private void Update()
{
if (IsPlaying)
{
ActiveTime += Time.deltaTime;
if (IsFinished)
{
if (OnFinish != null)
{
OnFinish();
}
Destroy(gameObject);
}
else
{
bool finishedThisCombination = true;
if (allEffects.ContainsKey(currentEffectIndex))
{
foreach (AtomizerEffect effect in allEffects[currentEffectIndex])
{
if (!effect.IsFinished)
{
finishedThisCombination = false;
if (effect.IsReady)
{
effect.Update(Particles, ActiveTime);
effect.UpdateParticleSkipIndex();
}
}
}
}
if (finishedThisCombination)
{
ActiveTime = 0.0f;
++currentEffectIndex;
if (allEffects.ContainsKey(currentEffectIndex))
{
SetParticles(Particles);
Play();
}
else
{
IsFinished = true;
}
}
if (!IsFinished)
{
particleSystem.SetParticles(Particles, ParticleCount);
}
}
}
}
private void BuildCanvasEffect(Snapshot snapshot, Camera atomizerCamera, GameObject atomizerTarget)
{
if (MaxParticleCount < 1)
{
MaxParticleCount = 1;
}
Color32[] validPixels = GetValidPixels(snapshot.Image);
int imageResizeRatio = Mathf.RoundToInt(Mathf.Pow(2.0f, mipLevel));
if (imageResizeRatio < 1)
{
imageResizeRatio = 1;
}
int imageHeight = snapshot.Image.height / imageResizeRatio;
int imageWidth = snapshot.Image.width / imageResizeRatio;
Color32[] colourData = snapshot.ColourData.GetPixels32();
int vScale = Mathf.RoundToInt((float)snapshot.Image.width / snapshot.ColourData.width);
int hScale = Mathf.RoundToInt((float)snapshot.Image.height / snapshot.ColourData.height);
vScale = Mathf.Clamp(vScale, 1, int.MaxValue);
hScale = Mathf.Clamp(hScale, 1, int.MaxValue);
int invScale = Mathf.RoundToInt(vScale * hScale);
int pixelsLength = colourData.Length;
int colourDataWidth = snapshot.ColourData.width;
int validPixelCount = 0;
for (int i = 0; i < colourData.Length; ++i)
{
if (colourData[i].a > 0)
{
validPixelCount += invScale;
}
}
ParticleSystem.Particle[] particles = EmitParticles(validPixelCount);
float adjustedParticleSize = ParticleSize;
if (!ForceParticleSize)
{
adjustedParticleSize = ParticleSize * imageResizeRatio;
adjustedParticleSize = Mathf.Clamp(adjustedParticleSize, 0.01f, 1.0f);
}
float minDistance = Vector3.Distance(atomizerCamera.transform.position, atomizerTarget.transform.position);
Color32 color = new Color32(0, 0, 0, 0);
Vector3 screenPoint = new Vector3(0.0f, 0.0f, minDistance - 1.0f);
int validPixelIndex = 0;
int midPoint = colourDataWidth / 2;
for (int i = 0; i < imageHeight; ++i)
{
float screenPointY = snapshot.ScreenRect.yMin + i * imageResizeRatio;
screenPoint.y = screenPointY;
for (int j = 0; j < imageWidth; ++j)
{
int index = j + i * imageWidth;
int sourceIndex = j / hScale + (i / vScale) * colourDataWidth;
if (snapshot.ReflectOnYAxis)
{
int temp = sourceIndex % colourDataWidth;
temp -= (2 * (temp - midPoint) + 1);
sourceIndex = temp + (i / vScale) * colourDataWidth;
}
if (sourceIndex < pixelsLength && colourData[sourceIndex].a > 0 && validPixelIndex < particles.Length)
{
ParticleSystem.Particle particle = particles[validPixelIndex];
color = validPixels[index];
color.a = 255;
particle.color = color;
particle.size = adjustedParticleSize;
screenPoint.x = snapshot.ScreenRect.xMin + j * imageResizeRatio;
particle.position = atomizerCamera.ScreenToWorldPoint(screenPoint);
particles[validPixelIndex] = particle;
++validPixelIndex;
}
}
}
Destroy(snapshot.Image);
Destroy(snapshot.ColourData);
SetParticles(particles);
}
private void BuildEffect(Snapshot snapshot, Camera atomizerCamera, GameObject atomizerTarget)
{
if (MaxParticleCount < 1)
{
MaxParticleCount = 1;
}
Color32[] validPixels = GetValidPixels(snapshot.Image);
int imageResizeRatio = Mathf.RoundToInt(Mathf.Pow(2.0f, mipLevel));
if (imageResizeRatio < 1)
{
imageResizeRatio = 1;
}
int imageHeight = snapshot.Image.height / imageResizeRatio;
int imageWidth = snapshot.Image.width / imageResizeRatio;
int pixelsLength = validPixels.Length;
int validPixelCount = 0;
for (int i = 0; i < pixelsLength; ++i)
{
if (validPixels[i].a > 0 && validPixels[i].r > 0 &&
validPixels[i].g > 0 && validPixels[i].b > 0)
{
++validPixelCount;
}
}
ParticleSystem.Particle[] particles = EmitParticles(validPixelCount);
int validPixelIndex = 0;
float adjustedParticleSize = ParticleSize;
if (false == ForceParticleSize)
{
adjustedParticleSize = ParticleSize * imageResizeRatio;
adjustedParticleSize = Mathf.Clamp(adjustedParticleSize, 0.01f, 1.0f);
}
float minDistance = Vector3.Distance(atomizerCamera.transform.position, atomizerTarget.transform.position);
Color32 color = new Color32(0, 0, 0, 0);
Vector3 screenPoint = new Vector3(0.0f, 0.0f, minDistance);
for (int i = 0; i < imageHeight; ++i)
{
float screenPointY = snapshot.ScreenRect.yMin + i * imageResizeRatio;
screenPoint.y = screenPointY;
for (int j = 0; j < imageWidth; ++j)
{
int index = j + i * imageWidth;
if (index < pixelsLength && validPixels[index].a > 0 && validPixels[index].r > 0 &&
validPixels[index].g > 0 && validPixels[index].b > 0)
{
ParticleSystem.Particle particle = particles[validPixelIndex];
color = validPixels[index];
color.a = 255;
particle.color = color;
particle.size = adjustedParticleSize;
screenPoint.x = snapshot.ScreenRect.xMin + j * imageResizeRatio;
particle.position = atomizerCamera.ScreenToWorldPoint(screenPoint);
particles[validPixelIndex] = particle;
++validPixelIndex;
}
}
}
Destroy(snapshot.Image);
SetParticles(particles);
}
private Color32[] GetValidPixels(Texture2D image)
{
mipLevel = image.mipmapCount > 0 ? image.mipmapCount - 1 : 0;
Color32[] pixels = image.GetPixels32(mipLevel);
Color32[] validPixels = pixels;
while (pixels.Length < MaxParticleCount && mipLevel > 0)
{
--mipLevel;
validPixels = pixels;
pixels = image.GetPixels32(mipLevel);
if (pixels.Length > MaxParticleCount)
{
++mipLevel;
break;
}
if (mipLevel == 0)
{
validPixels = pixels;
}
}
return validPixels;
}
public void Build(Snapshot snapshot, Camera atomizerCamera, GameObject atomizerTarget)
{
if (snapshot.ColourData != null)
{
BuildCanvasEffect(snapshot, atomizerCamera, atomizerTarget);
}
else
{
BuildEffect(snapshot, atomizerCamera, atomizerTarget);
}
}
public ParticleSystem.Particle[] EmitParticles(int particleCount)
{
ParticleSystem.Particle[] emittedParticles = new ParticleSystem.Particle[particleCount];
particleSystem.Emit(particleCount);
particleSystem.GetParticles(emittedParticles);
return emittedParticles;
}
public void SetParticles(ParticleSystem.Particle[] particles)
{
if (!IsFinished)
{
Particles = particles;
ParticleCount = particles.Length;
particleSystem.SetParticles(Particles, ParticleCount);
if (allEffects.ContainsKey(currentEffectIndex))
{
foreach (AtomizerEffect effect in allEffects[currentEffectIndex])
{
StartCoroutine(effect.SetParticles(Particles));
}
}
}
}
public void Initialize()
{
ParticleSize = DefaultParticleSize;
MaxParticleCount = DefaultMaxParticleCount;
ForceParticleSize = DefaultForceParticleSize;
particleSystem.Stop();
particleSystem.Clear();
ParticleCount = 0;
}
private Dictionary<int, List<AtomizerEffect>> allEffects;
private int chainedEffectIndex;
private int currentEffectIndex;
private int mipLevel;
}
| |
using Lucene.Net.Analysis;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Util;
using NUnit.Framework;
using System.IO;
using Assert = Lucene.Net.TestFramework.Assert;
using Version = Lucene.Net.Util.LuceneVersion;
#pragma warning disable 612, 618
namespace Lucene.Net.Support
{
/*
* 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.
*/
[SuppressCodecs("Lucene3x")] // Suppress non-writable codecs
[TestFixture]
public class TestOldPatches : LuceneTestCase
{
////-------------------------------------------
//[Test]
//[Description("LUCENENET-183")]
//public void Test_SegmentTermVector_IndexOf()
//{
// Lucene.Net.Store.RAMDirectory directory = new Lucene.Net.Store.RAMDirectory();
// Lucene.Net.Analysis.Analyzer analyzer = new Lucene.Net.Analysis.Core.WhitespaceAnalyzer(Version.LUCENE_CURRENT);
// var conf = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
// Lucene.Net.Index.IndexWriter writer = new Lucene.Net.Index.IndexWriter(directory, conf /*analyzer, Lucene.Net.Index.IndexWriter.MaxFieldLength.LIMITED*/);
// Lucene.Net.Documents.Document document = new Lucene.Net.Documents.Document();
// document.Add(new Lucene.Net.Documents.Field("contents", new System.IO.StreamReader(new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes("a_ a0"))), Lucene.Net.Documents.Field.TermVector.WITH_OFFSETS));
// writer.AddDocument(document);
// Lucene.Net.Index.IndexReader reader = writer.GetReader();
// Lucene.Net.Index.TermPositionVector tpv = reader.GetTermFreqVector(0, "contents") as Lucene.Net.Index.TermPositionVector;
// //Console.WriteLine("tpv: " + tpv);
// int index = tpv.IndexOf("a_", StringComparison.Ordinal);
// Assert.AreEqual(index, 1, "See the issue: LUCENENET-183");
//}
//-------------------------------------------
#if FEATURE_SERIALIZABLE
[Test]
[Description("LUCENENET-170")]
public void Test_Util_Parameter()
{
Lucene.Net.Search.BooleanQuery queryPreSerialized = new Lucene.Net.Search.BooleanQuery();
queryPreSerialized.Add(new Lucene.Net.Search.TermQuery(new Lucene.Net.Index.Term("country", "Russia")), Occur.MUST);
queryPreSerialized.Add(new Lucene.Net.Search.TermQuery(new Lucene.Net.Index.Term("country", "France")), Occur.MUST);
//now serialize it
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
serializer.Serialize(memoryStream, queryPreSerialized);
//now deserialize
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
Lucene.Net.Search.BooleanQuery queryPostSerialized = (Lucene.Net.Search.BooleanQuery)serializer.Deserialize(memoryStream);
memoryStream.Close();
Assert.AreEqual(queryPreSerialized, queryPostSerialized, "See the issue: LUCENENET-170");
}
#endif
// LUCENENENET: Microsoft no longer considers it good practice to use binary serialization
// in new applications. Therefore, we are no longer marking RAMDirectory serializable
// (It isn't serializable in Lucene 4.8.0 anymore anyway).
// See: https://github.com/dotnet/corefx/issues/23584
// //-------------------------------------------
//#if FEATURE_SERIALIZABLE
// [Test]
// [Description("LUCENENET-174")]
// public void Test_Store_RAMDirectory()
// {
// Lucene.Net.Store.RAMDirectory ramDIR = new Lucene.Net.Store.RAMDirectory();
// //Index 1 Doc
// Lucene.Net.Analysis.Analyzer analyzer = new Lucene.Net.Analysis.Core.WhitespaceAnalyzer(Version.LUCENE_CURRENT);
// var conf = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
// Lucene.Net.Index.IndexWriter wr = new Lucene.Net.Index.IndexWriter(ramDIR, conf /*new Lucene.Net.Analysis.WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED*/);
// Lucene.Net.Documents.Document doc = new Lucene.Net.Documents.Document();
// doc.Add(new Lucene.Net.Documents.Field("field1", "value1 value11", Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED));
// wr.AddDocument(doc);
// wr.Dispose();
// //now serialize it
// System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
// System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
// serializer.Serialize(memoryStream, ramDIR);
// //Close DIR
// ramDIR.Dispose();
// ramDIR = null;
// //now deserialize
// memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
// Lucene.Net.Store.RAMDirectory ramDIR2 = (Lucene.Net.Store.RAMDirectory)serializer.Deserialize(memoryStream);
// //Add 1 more doc
// Lucene.Net.Analysis.Analyzer analyzer2 = new Lucene.Net.Analysis.Core.WhitespaceAnalyzer(Version.LUCENE_CURRENT);
// var conf2 = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
// wr = new Lucene.Net.Index.IndexWriter(ramDIR2, conf2 /*new Lucene.Net.Analysis.WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.UNLIMITED*/);
// doc = new Lucene.Net.Documents.Document();
// doc.Add(new Lucene.Net.Documents.Field("field1", "value1 value11", Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED));
// wr.AddDocument(doc);
// wr.Dispose();
// Lucene.Net.Search.TopDocs topDocs;
// //Search
// using (var reader = DirectoryReader.Open(ramDIR2))
// {
// Lucene.Net.Search.IndexSearcher s = new Lucene.Net.Search.IndexSearcher(reader);
// Lucene.Net.QueryParsers.Classic.QueryParser qp = new Lucene.Net.QueryParsers.Classic.QueryParser(Version.LUCENE_CURRENT, "field1", new Lucene.Net.Analysis.Standard.StandardAnalyzer(Version.LUCENE_CURRENT));
// Lucene.Net.Search.Query q = qp.Parse("value1");
// topDocs = s.Search(q, 100);
// }
// Assert.AreEqual(topDocs.TotalHits, 2, "See the issue: LUCENENET-174");
// }
//#endif
//-------------------------------------------
[Test]
[Description("LUCENENET-150")]
public void Test_Index_ReusableStringReader()
{
var conf = new IndexWriterConfig(Version.LUCENE_CURRENT, new TestAnalyzer());
Lucene.Net.Index.IndexWriter wr = new Lucene.Net.Index.IndexWriter(new Lucene.Net.Store.RAMDirectory(), conf /*new TestAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED*/);
Lucene.Net.Documents.Document doc = new Lucene.Net.Documents.Document();
Lucene.Net.Documents.Field f1 = new Lucene.Net.Documents.Field("f1", TEST_STRING, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED);
doc.Add(f1);
wr.AddDocument(doc);
wr.Dispose();
}
private const string TEST_STRING = "First Line\nSecond Line";
private class TestAnalyzer : Lucene.Net.Analysis.Analyzer
{
public TestAnalyzer()
//: base(new TestReuseStrategy())
{ }
// Lucene.Net 3.0.3:
//public override Lucene.Net.Analysis.TokenStream TokenStream(string fieldName, System.IO.TextReader reader)
//{
// return new TestTokenizer(reader);
//}
protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
return new TokenStreamComponents(new TestTokenizer(reader));
}
protected internal override TextReader InitReader(string fieldName, TextReader reader)
{
var r = new ReusableStringReader();
r.SetValue(reader.ReadToEnd());
return r;
}
}
//class TestReuseStrategy : Lucene.Net.Analysis.ReuseStrategy
//{
// public override TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName)
// {
// return null;
// }
// public override void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components)
// {
// throw new NotImplementedException();
// }
//}
private class TestTokenizer : Lucene.Net.Analysis.Tokenizer
{
public TestTokenizer(System.IO.TextReader reader)
: base(reader)
{
//Caution: "Reader" is actually of type "ReusableStringReader" and some
//methods (for ex. "ReadToEnd", "Peek", "ReadLine") is not implemented.
Assert.AreEqual("ReusableStringReader", reader.GetType().Name);
Assert.AreEqual("First Line", reader.ReadLine(), "\"ReadLine\" method is not implemented");
Assert.AreEqual("Second Line", reader.ReadToEnd(), "\"ReadToEnd\" method is not implemented");
}
public override sealed bool IncrementToken()
{
return false;
}
}
// There is no IsCurrent() on IndexReader in Lucene 4.8.0
//[Test]
//[Description("LUCENENET-374")]
//public void Test_IndexReader_IsCurrent()
//{
// RAMDirectory ramDir = new RAMDirectory();
// var conf = new IndexWriterConfig(Version.LUCENE_CURRENT, new Analysis.Core.KeywordAnalyzer());
// IndexWriter writer = new IndexWriter(ramDir, conf /*new KeywordAnalyzer(), true, new IndexWriter.MaxFieldLength(1000)*/);
// Field field = new Field("TEST", "mytest", Field.Store.YES, Field.Index.ANALYZED);
// Document doc = new Document();
// doc.Add(field);
// writer.AddDocument(doc);
// IndexReader reader = writer.GetReader();
// writer.DeleteDocuments(new Lucene.Net.Index.Term("TEST", "mytest"));
// Assert.IsFalse(reader.IsCurrent());
// int resCount1 = new IndexSearcher(reader).Search(new TermQuery(new Term("TEST", "mytest")),100).TotalHits;
// Assert.AreEqual(1, resCount1);
// writer.Commit();
// Assert.IsFalse(reader.IsCurrent());
// int resCount2 = new IndexSearcher(reader).Search(new TermQuery(new Term("TEST", "mytest")),100).TotalHits;
// Assert.AreEqual(1, resCount2, "Reopen not invoked yet, resultCount must still be 1.");
// reader = reader.Reopen();
// Assert.IsTrue(reader.IsCurrent());
// int resCount3 = new IndexSearcher(reader).Search(new TermQuery(new Term("TEST", "mytest")), 100).TotalHits;
// Assert.AreEqual(0, resCount3, "After reopen, resultCount must be 0.");
// reader.Close();
// writer.Dispose();
//}
// LUCENENET TODO: Should IndexSearcher really implement MarshalByrefObj?
////-------------------------------------------
//int ANYPORT = 0;
//[Test]
//[Description("LUCENENET-100")]
//public void Test_Search_FieldDoc()
//{
// ANYPORT = new Random((int)(DateTime.Now.Ticks & 0x7fffffff)).Next(50000) + 10000;
// LUCENENET_100_CreateIndex();
// try
// {
// System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(new System.Runtime.Remoting.Channels.Tcp.TcpChannel(ANYPORT),false);
// }
// catch (Exception ex)
// {
// Console.WriteLine(ex.Message);
// }
// var reader = DirectoryReader.Open(LUCENENET_100_Dir);
// Lucene.Net.Search.IndexSearcher indexSearcher = new Lucene.Net.Search.IndexSearcher(reader);
// System.Runtime.Remoting.RemotingServices.Marshal(indexSearcher, "Searcher");
// LUCENENET_100_ClientSearch();
// //Wait Client to finish
// while (LUCENENET_100_testFinished == false) System.Threading.Thread.Sleep(10);
// if (LUCENENET_100_Exception != null) throw LUCENENET_100_Exception;
//}
//Lucene.Net.Store.RAMDirectory LUCENENET_100_Dir = new Lucene.Net.Store.RAMDirectory();
//bool LUCENENET_100_testFinished = false;
//Exception LUCENENET_100_Exception = null;
//void LUCENENET_100_ClientSearch()
//{
// try
// {
// Lucene.Net.Search.Searchable s = (Lucene.Net.Search.Searchable)Activator.GetObject(typeof(Lucene.Net.Search.Searchable), @"tcp://localhost:" + ANYPORT + "/Searcher");
// Lucene.Net.Search.MultiSearcher searcher = new Lucene.Net.Search.MultiSearcher(new Lucene.Net.Search.Searchable[] { s });
// Lucene.Net.Search.Query q = new Lucene.Net.Search.TermQuery(new Lucene.Net.Index.Term("field1", "moon"));
// Lucene.Net.Search.Sort sort = new Lucene.Net.Search.Sort();
// sort.SetSort(new Lucene.Net.Search.SortField("field2", Lucene.Net.Search.SortField.INT));
// Lucene.Net.Search.TopDocs h = searcher.Search(q, null, 100, sort);
// if (h.ScoreDocs.Length != 2) LUCENENET_100_Exception = new SupportClassException("Test_Search_FieldDoc Error. ");
// }
// catch (SupportClassException ex)
// {
// LUCENENET_100_Exception = ex;
// }
// catch (Exception ex)
// {
// Console.WriteLine(ex);
// }
// finally
// {
// LUCENENET_100_testFinished = true;
// }
//}
//void LUCENENET_100_CreateIndex()
//{
// Lucene.Net.Index.IndexWriter w = new Lucene.Net.Index.IndexWriter(LUCENENET_100_Dir, new Lucene.Net.Analysis.Standard.StandardAnalyzer(Version.LUCENE_CURRENT), true, IndexWriter.MaxFieldLength.UNLIMITED);
// Lucene.Net.Documents.Field f1 = new Lucene.Net.Documents.Field("field1", "dark side of the moon", Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED);
// Lucene.Net.Documents.Field f2 = new Lucene.Net.Documents.Field("field2", "123", Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.NOT_ANALYZED);
// Lucene.Net.Documents.Document d = new Lucene.Net.Documents.Document();
// d.Add(f1);
// d.Add(f2);
// w.AddDocument(d);
// f1 = new Lucene.Net.Documents.Field("field1", "Fly me to the moon", Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED);
// f2 = new Lucene.Net.Documents.Field("field2", "456", Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.NOT_ANALYZED);
// d = new Lucene.Net.Documents.Document();
// d.Add(f1);
// d.Add(f2);
// w.AddDocument(d);
// w.Dispose();
//}
////-------------------------------------------
}
}
#pragma warning restore 612, 618
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.AzureStack.Management
{
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for
/// more information)
/// </summary>
internal partial class ResourceProviderOperations : IServiceOperations<AzureStackClient>, IResourceProviderOperations
{
/// <summary>
/// Initializes a new instance of the ResourceProviderOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ResourceProviderOperations(AzureStackClient client)
{
this._client = client;
}
private AzureStackClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.AzureStack.Management.AzureStackClient.
/// </summary>
public AzureStackClient Client
{
get { return this._client; }
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Required. Your documentation here.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public async Task<ResourceProviderGetResult> GetAsync(string resourceProviderNamespace, CancellationToken cancellationToken)
{
// Validate
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
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 + "/providers/";
url = url + Uri.EscapeDataString(resourceProviderNamespace);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
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
ResourceProviderGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceProviderGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ResourceProviderDefinition resourceProviderInstance = new ResourceProviderDefinition();
result.ResourceProvider = resourceProviderInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceProviderInstance.Id = idInstance;
}
JToken namespaceValue = responseDoc["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
resourceProviderInstance.Namespace = namespaceInstance;
}
JToken resourceTypesArray = responseDoc["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
resourceProviderInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.ResourceType = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
JToken apiVersionsArray = resourceTypesValue["apiVersions"];
if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
{
foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
{
providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
}
}
JToken propertiesValue = resourceTypesValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented);
providerResourceTypeInstance.Properties = propertiesInstance;
}
}
}
JToken registrationStateValue = responseDoc["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
SubscriptionRegistrationState registrationStateInstance = ((SubscriptionRegistrationState)Enum.Parse(typeof(SubscriptionRegistrationState), ((string)registrationStateValue), true));
resourceProviderInstance.RegistrationState = registrationStateInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public async Task<ResourceProviderListResult> ListAsync(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>();
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 + "/providers";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
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
ResourceProviderListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceProviderListResult();
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))
{
ResourceProviderDefinition resourceProviderDefinitionInstance = new ResourceProviderDefinition();
result.ResourceProviders.Add(resourceProviderDefinitionInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceProviderDefinitionInstance.Id = idInstance;
}
JToken namespaceValue = valueValue["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
resourceProviderDefinitionInstance.Namespace = namespaceInstance;
}
JToken resourceTypesArray = valueValue["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
resourceProviderDefinitionInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.ResourceType = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
JToken apiVersionsArray = resourceTypesValue["apiVersions"];
if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
{
foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
{
providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
}
}
JToken propertiesValue = resourceTypesValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented);
providerResourceTypeInstance.Properties = propertiesInstance;
}
}
}
JToken registrationStateValue = valueValue["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
SubscriptionRegistrationState registrationStateInstance = ((SubscriptionRegistrationState)Enum.Parse(typeof(SubscriptionRegistrationState), ((string)registrationStateValue), true));
resourceProviderDefinitionInstance.RegistrationState = registrationStateInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='nextLink'>
/// Required. Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public async Task<ResourceProviderListResult> 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 + Uri.EscapeDataString(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
ResourceProviderListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceProviderListResult();
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))
{
ResourceProviderDefinition resourceProviderDefinitionInstance = new ResourceProviderDefinition();
result.ResourceProviders.Add(resourceProviderDefinitionInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceProviderDefinitionInstance.Id = idInstance;
}
JToken namespaceValue = valueValue["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
resourceProviderDefinitionInstance.Namespace = namespaceInstance;
}
JToken resourceTypesArray = valueValue["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
resourceProviderDefinitionInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.ResourceType = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
JToken apiVersionsArray = resourceTypesValue["apiVersions"];
if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
{
foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
{
providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
}
}
JToken propertiesValue = resourceTypesValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented);
providerResourceTypeInstance.Properties = propertiesInstance;
}
}
}
JToken registrationStateValue = valueValue["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
SubscriptionRegistrationState registrationStateInstance = ((SubscriptionRegistrationState)Enum.Parse(typeof(SubscriptionRegistrationState), ((string)registrationStateValue), true));
resourceProviderDefinitionInstance.RegistrationState = registrationStateInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
namespace Frapid.Config.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Smtp Configs.
/// </summary>
[RoutePrefix("api/v1.0/config/smtp-config")]
public class SmtpConfigController : FrapidApiController
{
/// <summary>
/// The SmtpConfig repository.
/// </summary>
private readonly ISmtpConfigRepository SmtpConfigRepository;
public SmtpConfigController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>();
this._UserId = AppUsers.GetCurrent().View.UserId.To<int>();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>();
this._Catalog = AppUsers.GetCatalog();
this.SmtpConfigRepository = new Frapid.Config.DataAccess.SmtpConfig
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public SmtpConfigController(ISmtpConfigRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.To<long>();
this._UserId = view.UserId.To<int>();
this._OfficeId = view.OfficeId.To<int>();
this._Catalog = catalog;
this.SmtpConfigRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Creates meta information of "smtp config" entity.
/// </summary>
/// <returns>Returns the "smtp config" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/config/smtp-config/meta")]
[Authorize]
public EntityView GetEntityView()
{
if (this._LoginId == 0)
{
return new EntityView();
}
return new EntityView
{
PrimaryKey = "smtp_id",
Columns = new List<EntityColumn>()
{
new EntityColumn { ColumnName = "smtp_id", PropertyName = "SmtpId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "configuration_name", PropertyName = "ConfigurationName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 },
new EntityColumn { ColumnName = "enabled", PropertyName = "Enabled", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "is_default", PropertyName = "IsDefault", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "from_display_name", PropertyName = "FromDisplayName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 },
new EntityColumn { ColumnName = "from_email_address", PropertyName = "FromEmailAddress", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 },
new EntityColumn { ColumnName = "smtp_host", PropertyName = "SmtpHost", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 },
new EntityColumn { ColumnName = "smtp_enable_ssl", PropertyName = "SmtpEnableSsl", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "smtp_username", PropertyName = "SmtpUsername", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 },
new EntityColumn { ColumnName = "smtp_password", PropertyName = "SmtpPassword", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 },
new EntityColumn { ColumnName = "smtp_port", PropertyName = "SmtpPort", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "audit_user_id", PropertyName = "AuditUserId", DataType = "int", DbDataType = "int4", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "audit_ts", PropertyName = "AuditTs", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }
}
};
}
/// <summary>
/// Counts the number of smtp configs.
/// </summary>
/// <returns>Returns the count of the smtp configs.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/config/smtp-config/count")]
[Authorize]
public long Count()
{
try
{
return this.SmtpConfigRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of smtp config.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/config/smtp-config/all")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetAll()
{
try
{
return this.SmtpConfigRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of smtp config for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/config/smtp-config/export")]
[Authorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.SmtpConfigRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of smtp config.
/// </summary>
/// <param name="smtpId">Enter SmtpId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{smtpId}")]
[Route("~/api/config/smtp-config/{smtpId}")]
[Authorize]
public Frapid.Config.Entities.SmtpConfig Get(int smtpId)
{
try
{
return this.SmtpConfigRepository.Get(smtpId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/config/smtp-config/get")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.SmtpConfig> Get([FromUri] int[] smtpIds)
{
try
{
return this.SmtpConfigRepository.Get(smtpIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of smtp config.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/config/smtp-config/first")]
[Authorize]
public Frapid.Config.Entities.SmtpConfig GetFirst()
{
try
{
return this.SmtpConfigRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of smtp config.
/// </summary>
/// <param name="smtpId">Enter SmtpId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{smtpId}")]
[Route("~/api/config/smtp-config/previous/{smtpId}")]
[Authorize]
public Frapid.Config.Entities.SmtpConfig GetPrevious(int smtpId)
{
try
{
return this.SmtpConfigRepository.GetPrevious(smtpId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of smtp config.
/// </summary>
/// <param name="smtpId">Enter SmtpId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{smtpId}")]
[Route("~/api/config/smtp-config/next/{smtpId}")]
[Authorize]
public Frapid.Config.Entities.SmtpConfig GetNext(int smtpId)
{
try
{
return this.SmtpConfigRepository.GetNext(smtpId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of smtp config.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/config/smtp-config/last")]
[Authorize]
public Frapid.Config.Entities.SmtpConfig GetLast()
{
try
{
return this.SmtpConfigRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 smtp configs on each page, sorted by the property SmtpId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/config/smtp-config")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetPaginatedResult()
{
try
{
return this.SmtpConfigRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 smtp configs on each page, sorted by the property SmtpId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/config/smtp-config/page/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetPaginatedResult(long pageNumber)
{
try
{
return this.SmtpConfigRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of smtp configs using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered smtp configs.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/config/smtp-config/count-where")]
[Authorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.SmtpConfigRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 smtp configs on each page, sorted by the property SmtpId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/config/smtp-config/get-where/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.SmtpConfigRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of smtp configs using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered smtp configs.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/config/smtp-config/count-filtered/{filterName}")]
[Authorize]
public long CountFiltered(string filterName)
{
try
{
return this.SmtpConfigRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 smtp configs on each page, sorted by the property SmtpId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/config/smtp-config/get-filtered/{pageNumber}/{filterName}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.SmtpConfigRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of smtp configs.
/// </summary>
/// <returns>Returns an enumerable key/value collection of smtp configs.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/config/smtp-config/display-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.SmtpConfigRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for smtp configs.
/// </summary>
/// <returns>Returns an enumerable custom field collection of smtp configs.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/config/smtp-config/custom-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.SmtpConfigRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for smtp configs.
/// </summary>
/// <returns>Returns an enumerable custom field collection of smtp configs.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/config/smtp-config/custom-fields/{resourceId}")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.SmtpConfigRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of SmtpConfig class.
/// </summary>
/// <param name="smtpConfig">Your instance of smtp configs class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/config/smtp-config/add-or-edit")]
[Authorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic smtpConfig = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (smtpConfig == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.SmtpConfigRepository.AddOrEdit(smtpConfig, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of SmtpConfig class.
/// </summary>
/// <param name="smtpConfig">Your instance of smtp configs class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{smtpConfig}")]
[Route("~/api/config/smtp-config/add/{smtpConfig}")]
[Authorize]
public void Add(Frapid.Config.Entities.SmtpConfig smtpConfig)
{
if (smtpConfig == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.SmtpConfigRepository.Add(smtpConfig);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of SmtpConfig class.
/// </summary>
/// <param name="smtpConfig">Your instance of SmtpConfig class to edit.</param>
/// <param name="smtpId">Enter the value for SmtpId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{smtpId}")]
[Route("~/api/config/smtp-config/edit/{smtpId}")]
[Authorize]
public void Edit(int smtpId, [FromBody] Frapid.Config.Entities.SmtpConfig smtpConfig)
{
if (smtpConfig == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.SmtpConfigRepository.Update(smtpConfig, smtpId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of SmtpConfig class.
/// </summary>
/// <param name="collection">Your collection of SmtpConfig class to bulk import.</param>
/// <returns>Returns list of imported smtpIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any SmtpConfig class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/config/smtp-config/bulk-import")]
[Authorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> smtpConfigCollection = this.ParseCollection(collection);
if (smtpConfigCollection == null || smtpConfigCollection.Count.Equals(0))
{
return null;
}
try
{
return this.SmtpConfigRepository.BulkImport(smtpConfigCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of SmtpConfig class via SmtpId.
/// </summary>
/// <param name="smtpId">Enter the value for SmtpId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{smtpId}")]
[Route("~/api/config/smtp-config/delete/{smtpId}")]
[Authorize]
public void Delete(int smtpId)
{
try
{
this.SmtpConfigRepository.Delete(smtpId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
using System;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/***** This file contains automatically generated code ******
**
** The code in this file has been automatically generated by
**
** sqlite/tool/mkkeywordhash.c
**
** The code in this file implements a function that determines whether
** or not a given identifier is really an SQL keyword. The same thing
** might be implemented more directly using a hand-written hash table.
** But by using this automatically generated code, the size of the code
** is substantially reduced. This is important for embedded applications
** on platforms with limited memory.
*************************************************************************
** 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
**
*************************************************************************
*/
/* Hash score: 175 */
/* zText[] encodes 811 bytes of keywords in 541 bytes */
/* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
/* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
/* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
/* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
/* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
/* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
/* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
/* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
/* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
/* INITIALLY */
private static string zText = new string(new char[540] {
'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G',
#if !SQLITE_OMIT_TRIGGER
'E',
#else
'\0',
#endif
'R',
#if !SQLITE_OMIT_FOREIGN_KEY
'E',
#else
'\0',
#endif
'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
});
private static byte[] aHash = { //aHash[127]
72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
};
private static byte[] aNext = { //aNext[121]
0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
35, 64, 0, 0,
};
private static byte[] aLen = { //aLen[121]
7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
6, 4, 9, 3,
};
private static int[] aOffset = { //aOffset[121]
0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
521, 527, 531, 536,
};
private static byte[] aCode = { //aCode[121
TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
TK_ALL,
};
private static int keywordCode(string z, int iOffset, int n)
{
int h, i;
if (n < 2)
return TK_ID;
h = ((sqlite3UpperToLower[z[iOffset + 0]]) * 4 ^//(charMap(z[iOffset+0]) * 4) ^
(sqlite3UpperToLower[z[iOffset + n - 1]] * 3) ^ //(charMap(z[iOffset+n - 1]) * 3) ^
n) % 127;
for (i = (aHash[h]) - 1; i >= 0; i = (aNext[i]) - 1)
{
if (aLen[i] == n && String.Compare(zText, aOffset[i], z, iOffset, n, StringComparison.OrdinalIgnoreCase) == 0)
{
testcase(i == 0); /* REINDEX */
testcase(i == 1); /* INDEXED */
testcase(i == 2); /* INDEX */
testcase(i == 3); /* DESC */
testcase(i == 4); /* ESCAPE */
testcase(i == 5); /* EACH */
testcase(i == 6); /* CHECK */
testcase(i == 7); /* KEY */
testcase(i == 8); /* BEFORE */
testcase(i == 9); /* FOREIGN */
testcase(i == 10); /* FOR */
testcase(i == 11); /* IGNORE */
testcase(i == 12); /* REGEXP */
testcase(i == 13); /* EXPLAIN */
testcase(i == 14); /* INSTEAD */
testcase(i == 15); /* ADD */
testcase(i == 16); /* DATABASE */
testcase(i == 17); /* AS */
testcase(i == 18); /* SELECT */
testcase(i == 19); /* TABLE */
testcase(i == 20); /* LEFT */
testcase(i == 21); /* THEN */
testcase(i == 22); /* END */
testcase(i == 23); /* DEFERRABLE */
testcase(i == 24); /* ELSE */
testcase(i == 25); /* EXCEPT */
testcase(i == 26); /* TRANSACTION */
testcase(i == 27); /* ACTION */
testcase(i == 28); /* ON */
testcase(i == 29); /* NATURAL */
testcase(i == 30); /* ALTER */
testcase(i == 31); /* RAISE */
testcase(i == 32); /* EXCLUSIVE */
testcase(i == 33); /* EXISTS */
testcase(i == 34); /* SAVEPOINT */
testcase(i == 35); /* INTERSECT */
testcase(i == 36); /* TRIGGER */
testcase(i == 37); /* REFERENCES */
testcase(i == 38); /* CONSTRAINT */
testcase(i == 39); /* INTO */
testcase(i == 40); /* OFFSET */
testcase(i == 41); /* OF */
testcase(i == 42); /* SET */
testcase(i == 43); /* TEMPORARY */
testcase(i == 44); /* TEMP */
testcase(i == 45); /* OR */
testcase(i == 46); /* UNIQUE */
testcase(i == 47); /* QUERY */
testcase(i == 48); /* ATTACH */
testcase(i == 49); /* HAVING */
testcase(i == 50); /* GROUP */
testcase(i == 51); /* UPDATE */
testcase(i == 52); /* BEGIN */
testcase(i == 53); /* INNER */
testcase(i == 54); /* RELEASE */
testcase(i == 55); /* BETWEEN */
testcase(i == 56); /* NOTNULL */
testcase(i == 57); /* NOT */
testcase(i == 58); /* NO */
testcase(i == 59); /* NULL */
testcase(i == 60); /* LIKE */
testcase(i == 61); /* CASCADE */
testcase(i == 62); /* ASC */
testcase(i == 63); /* DELETE */
testcase(i == 64); /* CASE */
testcase(i == 65); /* COLLATE */
testcase(i == 66); /* CREATE */
testcase(i == 67); /* CURRENT_DATE */
testcase(i == 68); /* DETACH */
testcase(i == 69); /* IMMEDIATE */
testcase(i == 70); /* JOIN */
testcase(i == 71); /* INSERT */
testcase(i == 72); /* MATCH */
testcase(i == 73); /* PLAN */
testcase(i == 74); /* ANALYZE */
testcase(i == 75); /* PRAGMA */
testcase(i == 76); /* ABORT */
testcase(i == 77); /* VALUES */
testcase(i == 78); /* VIRTUAL */
testcase(i == 79); /* LIMIT */
testcase(i == 80); /* WHEN */
testcase(i == 81); /* WHERE */
testcase(i == 82); /* RENAME */
testcase(i == 83); /* AFTER */
testcase(i == 84); /* REPLACE */
testcase(i == 85); /* AND */
testcase(i == 86); /* DEFAULT */
testcase(i == 87); /* AUTOINCREMENT */
testcase(i == 88); /* TO */
testcase(i == 89); /* IN */
testcase(i == 90); /* CAST */
testcase(i == 91); /* COLUMN */
testcase(i == 92); /* COMMIT */
testcase(i == 93); /* CONFLICT */
testcase(i == 94); /* CROSS */
testcase(i == 95); /* CURRENT_TIMESTAMP */
testcase(i == 96); /* CURRENT_TIME */
testcase(i == 97); /* PRIMARY */
testcase(i == 98); /* DEFERRED */
testcase(i == 99); /* DISTINCT */
testcase(i == 100); /* IS */
testcase(i == 101); /* DROP */
testcase(i == 102); /* FAIL */
testcase(i == 103); /* FROM */
testcase(i == 104); /* FULL */
testcase(i == 105); /* GLOB */
testcase(i == 106); /* BY */
testcase(i == 107); /* IF */
testcase(i == 108); /* ISNULL */
testcase(i == 109); /* ORDER */
testcase(i == 110); /* RESTRICT */
testcase(i == 111); /* OUTER */
testcase(i == 112); /* RIGHT */
testcase(i == 113); /* ROLLBACK */
testcase(i == 114); /* ROW */
testcase(i == 115); /* UNION */
testcase(i == 116); /* USING */
testcase(i == 117); /* VACUUM */
testcase(i == 118); /* VIEW */
testcase(i == 119); /* INITIALLY */
testcase(i == 120); /* ALL */
return aCode[i];
}
}
return TK_ID;
}
private static int sqlite3KeywordCode(string z, int n)
{
return keywordCode(z, 0, n);
}
public const int SQLITE_N_KEYWORD = 121;//#define SQLITE_N_KEYWORD 121
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Org.Webrtc;
using System.Text.RegularExpressions;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
using Android.Content;
namespace PeerNet
{
/// <summary>
/// Class Representation of a Peer, for both this peer and the remote peer.
/// </summary>
public class Peer
{
/// <summary>
/// Options for this Peer.
/// </summary>
public PeerOptions Options{ get; set; }
/// <summary>
/// Id of this peer.
/// </summary>
public string Id{ get; set; }
/// <summary>
/// Connection has been killed.
/// </summary>
public bool Destroyed{ get; set; }
/// <summary>
/// connection to the peer server has been killed.
/// </summary>
public bool Disconnected{ get; set; }
/// <summary>
/// Connections have not been opened.
/// </summary>
public bool Open{ get; set; }
/// <summary>
/// List of data connections for this server;
/// </summary>
public List<DataConnection> connections;
/// <summary>
/// Socket for this Peer
/// </summary>
public Socket socket;
/// <summary>
/// Context of the application using the library
/// </summary>
public Context context;
public delegate void PeerConnectedMessageHandler (object sender, PeerConnectedEventArgs args);
public event PeerConnectedMessageHandler PeerConnected;
/// <summary>
/// Peer Contructor.
/// </summary>
/// <param name="peerId">Id of the peer. If not specified will be generated by the server;</param>
/// <param name="peerOptions">Peer options, An instance of Peer.PeerOptions class</param>
public Peer (string peerId, PeerOptions peerOptions, Context context)
{
Options = peerOptions ?? new PeerOptions (null, null, null, null, null);
Id = peerId;
this.context = context;
connections = new List<DataConnection> ();
InitializeServerConnection ();
if (Id == null) {
InitializeID ();
} else {
Initialize (Id);
}
}
/// <summary>
/// This constructor is meant to hold the peer intance for the destination.
/// We donot provide the options, since we don ot connect this peer. We just use it to hold the peer ID so that
/// the peer class is uniformly used througout the code.
/// </summary>
/// <param name="peerId">Peer identifier.</param>
public Peer (string peerId)
{
this.Id = peerId;
}
public DataConnection Connect (string peer, DataConnectionOptions options)
{
Peer peerToConnect = new Peer (peer);
DataConnection dataConnection = new DataConnection (peerToConnect, this, options);
this.connections.Add (dataConnection);
return dataConnection;
}
/// <summary>
/// Internal method to init the Peer connection from server
/// </summary>
/// <param name="id">Identifier.</param>
private void Initialize (string id)
{
this.Id = id;
socket.Start (id, this.Options.Token);
}
/// <summary>
/// Initializes the ID by sending an HTTP request to the web server.
/// </summary>
private async void InitializeID ()
{
string protocol = "http://";
string url = protocol + this.Options.Host + ":" + this.Options.Port + this.Options.Path + this.Options.Key + "/id";
HttpWebRequest httpWebRequest = new HttpWebRequest (new Uri (url));
httpWebRequest.Method = "GET";
using (WebResponse response = await httpWebRequest.GetResponseAsync ()) {
using (Stream stream = response.GetResponseStream ()) {
JsonSerializer jsonSerializer = new JsonSerializer ();
StreamReader streamReader = new StreamReader (stream);
string id = streamReader.ReadToEnd ();
this.Id = id;
Initialize (id);
}
}
}
/// <summary>
/// Initializes socket to the server so that messages can be sent ot recieved
/// </summary>
private void InitializeServerConnection ()
{
this.socket = new Socket (Options.Host, Options.Port, Options.Path, Options.Key);
socket.MessageArrived += Socket_MessageArrived;
socket.SocketOpened += Socket_SocketOpened;
socket.SocketError += Socket_SocketError;
socket.SocketClosed += Socket_SocketClosed;
}
/// <summary>
/// Event fired when the socket closed.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Eevent Arguments</param>
private void Socket_SocketClosed (object sender, EventArgs e)
{
Console.WriteLine ("Socket Closed");
}
/// <summary>
/// Event fired when the socket closed.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Eevent Arguments</param>
private void Socket_SocketError (object sender, WebSocketSharp.ErrorEventArgs args)
{
Console.WriteLine ("Socket Error:" + args.Message);
}
/// <summary>
/// Event fired when the socket opened.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Eevent Arguments</param>
private void Socket_SocketOpened (object sender, EventArgs e)
{
Console.WriteLine ("Socket Opened");
}
/// <summary>
/// Event fired when message arrived from the socket.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Eevent Arguments</param>
private void Socket_MessageArrived (object sender, SocketMessageEventArgs args)
{
HandleMessage (args.Message);
}
/// <summary>
/// Handles the message sent by the other peer or the server
/// </summary>
/// <param name="message">Message.</param>
private void HandleMessage (string message)
{
ServerMessage serverMessage = JsonConvert.DeserializeObject<ServerMessage> (message);
switch (serverMessage.Type) {
//this message comes whent the connection to the sever is opened
case "OPEN":
PeerConnectedEventArgs peerConnectedEventArgs = new PeerConnectedEventArgs ();
peerConnectedEventArgs.PeerId = this.Id;
OnPeerConnected (peerConnectedEventArgs);
break;
//this message comes in when the offer is answered by the other peer. Contains the remote session desciption
case "ANSWER":
Negotiator negotiator = Negotiator.GetNegotiator ();
SessionDescription sessionDescription = new SessionDescription (SessionDescription.Type.Answer, serverMessage.Payload.Sdp.Sdp);
negotiator.HandleMessage (serverMessage, sessionDescription);
break;
}
}
//Metod to fire event when the peer is connected
private void OnPeerConnected (PeerConnectedEventArgs peerConnectedEventArgs)
{
PeerConnectedMessageHandler handler = PeerConnected;
if (handler != null) {
handler (this, peerConnectedEventArgs);
}
}
}
/// <summary>
/// This class hold the Class representation of the JSOn format of the server message.
/// </summary>
public class ServerMessage
{
public string Type{ get; set; }
public Payload Payload { get; set; }
public string Src { get; set; }
public string Msg{ get; set; }
public string Dst{ get; set; }
}
public class Payload
{
public SdpType Sdp{ get; set; }
public string Type{ get; set; }
public string ConnectionId{ get; set; }
public string Browser{ get; set; }
}
public class SdpType
{
public string Type{ get; set; }
public string Sdp { get; set; }
}
public class PeerConnectedEventArgs : EventArgs
{
public string PeerId { get; set; }
}
/// <summary>
/// Class representing the Peer options while constructing the Peer object
/// </summary>
public class PeerOptions
{
public string Host{ get; set; }
public int Port{ get; set; }
public string Key{ get; set; }
public string Path{ get; set; }
public string Token{ get; set; }
public List<PeerConnection.IceServer> Config{ get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="host">Optional host parameter. Defaults to 0.peerjs.com</param>
/// <param name="port">Optional port. deefaults to 9000</param>
/// <param name="key">optional key, defaults to "peerjs"</param>
/// <param name="path">the path of the peerjs server on the url defaults to '/'</param>
/// <param name="config">List of IceServers to use. defaults to "stun:stun.l.google.com:19302"</param>
public PeerOptions (string host, int? port, string key, string path, List<PeerConnection.IceServer> config)
{
this.Host = host ?? Util.host;
this.Port = port ?? Util.port;
this.Key = key ?? "peerjs";
this.Path = path ?? "/";
this.Token = Util.token;
this.Config = config ?? Util.defaultConfig;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowThrottleSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.IO;
using Akka.Streams.Actors;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowThrottleSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public FlowThrottleSpec(ITestOutputHelper helper) : base(helper)
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(1, 1);
Materializer = ActorMaterializer.Create(Sys, settings);
}
private static ByteString GenerateByteString(int length)
{
var random = new Random();
var bytes =
Enumerable.Range(0, 255)
.Select(_ => random.Next(0, 255))
.Take(length)
.Select(Convert.ToByte)
.ToArray();
return ByteString.Create(bytes);
}
[Fact]
public void Throttle_for_single_cost_elements_must_work_for_the_happy_case()
{
this.AssertAllStagesStopped(() =>
{
Source.From(Enumerable.Range(1, 5))
.Throttle(1, TimeSpan.FromMilliseconds(100), 0, ThrottleMode.Shaping)
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(5)
.ExpectNext(1, 2, 3, 4, 5)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void Throttle_for_single_cost_elements_must_emit_single_element_per_tick()
{
this.AssertAllStagesStopped(() =>
{
var upstream = TestPublisher.CreateProbe<int>(this);
var downstream = TestSubscriber.CreateProbe<int>(this);
Source.FromPublisher(upstream)
.Throttle(1, TimeSpan.FromMilliseconds(300), 0, ThrottleMode.Shaping)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(2);
upstream.SendNext(1);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(150));
downstream.ExpectNext(1);
upstream.SendNext(2);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(150));
downstream.ExpectNext(2);
upstream.SendComplete();
downstream.ExpectComplete();
}, Materializer);
}
[Fact]
public void Throttle_for_single_cost_elements_must_not_send_downstream_if_upstream_does_not_emit_element()
{
this.AssertAllStagesStopped(() =>
{
var upstream = TestPublisher.CreateProbe<int>(this);
var downstream = TestSubscriber.CreateProbe<int>(this);
Source.FromPublisher(upstream)
.Throttle(1, TimeSpan.FromMilliseconds(300), 0, ThrottleMode.Shaping)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(2);
upstream.SendNext(1);
downstream.ExpectNext(1);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
upstream.SendNext(2);
downstream.ExpectNext(2);
upstream.SendComplete();
downstream.ExpectComplete();
}, Materializer);
}
[Fact]
public void Throttle_for_single_cost_elements_must_cancel_when_downstream_cancels()
{
this.AssertAllStagesStopped(() =>
{
var downstream = TestSubscriber.CreateProbe<int>(this);
Source.From(Enumerable.Range(1, 10))
.Throttle(1, TimeSpan.FromMilliseconds(300), 0, ThrottleMode.Shaping)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Cancel();
}, Materializer);
}
[Fact]
public void Throttle_for_single_cost_elements_must_send_elements_downstream_as_soon_as_time_comes()
{
this.AssertAllStagesStopped(() =>
{
var probe =
Source.From(Enumerable.Range(1, 10))
.Throttle(2, TimeSpan.FromMilliseconds(500), 0, ThrottleMode.Shaping)
.RunWith(this.SinkProbe<int>(), Materializer);
probe.Request(5);
var result = probe.ReceiveWhile(TimeSpan.FromMilliseconds(600), filter: x => x);
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(100))
.ExpectNext(3)
.ExpectNoMsg(TimeSpan.FromMilliseconds(100))
.ExpectNext(4);
probe.Cancel();
// assertion may take longer then the throttle and therefore the next assertion fails
result.ShouldAllBeEquivalentTo(new[] { new OnNext(1), new OnNext(2) });
}, Materializer);
}
[Fact]
public void Throttle_for_single_cost_elements_must_burst_according_to_its_maximum_if_enough_time_passed()
{
this.AssertAllStagesStopped(() =>
{
var upstream = TestPublisher.CreateProbe<int>(this);
var downstream = TestSubscriber.CreateProbe<int>(this);
Source.FromPublisher(upstream)
.Throttle(1, TimeSpan.FromMilliseconds(200), 5, ThrottleMode.Shaping)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(1);
upstream.SendNext(1);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
downstream.ExpectNext(1);
downstream.Request(5);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(1200));
var expected = new List<OnNext>();
for (var i = 2; i < 7; i++)
{
upstream.SendNext(i);
expected.Add(new OnNext(i));
}
downstream.ReceiveWhile(TimeSpan.FromMilliseconds(300), filter: x => x, msgs: 5)
.ShouldAllBeEquivalentTo(expected);
downstream.Cancel();
}, Materializer);
}
[Fact]
public void Throttle_for_single_cost_elements_must_burst_some_elements_if_have_enough_time()
{
this.AssertAllStagesStopped(() =>
{
var upstream = TestPublisher.CreateProbe<int>(this);
var downstream = TestSubscriber.CreateProbe<int>(this);
Source.FromPublisher(upstream)
.Throttle(1, TimeSpan.FromMilliseconds(200), 5, ThrottleMode.Shaping)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(1);
upstream.SendNext(1);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
downstream.ExpectNext(1);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
downstream.Request(5);
var expected = new List<OnNext>();
for (var i = 2; i < 5; i++)
{
upstream.SendNext(i);
if (i < 4)
expected.Add(new OnNext(i));
}
downstream.ReceiveWhile(TimeSpan.FromMilliseconds(100), filter: x => x, msgs: 2)
.ShouldAllBeEquivalentTo(expected);
downstream.Cancel();
}, Materializer);
}
[Fact]
public void Throttle_for_single_cost_elements_must_throw_exception_when_exceeding_throughtput_in_enforced_mode()
{
this.AssertAllStagesStopped(() =>
{
var t =
Source.From(Enumerable.Range(1, 5))
.Throttle(1, TimeSpan.FromMilliseconds(200), 5, ThrottleMode.Enforcing)
.RunWith(Sink.Ignore<int>(), Materializer);
t.Invoking(task => task.Wait(TimeSpan.FromSeconds(2))).ShouldThrow<OverflowException>();
}, Materializer);
}
[Fact]
public void Throttle_for_single_cost_elements_must_properly_combine_shape_and_throttle_modes()
{
this.AssertAllStagesStopped(() =>
{
Source.From(Enumerable.Range(1, 5))
.Throttle(1, TimeSpan.FromMilliseconds(100), 5, ThrottleMode.Shaping)
.Throttle(1, TimeSpan.FromMilliseconds(100), 5, ThrottleMode.Enforcing)
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(5)
.ExpectNext(1, 2, 3, 4, 5)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void Throttle_for_various_cost_elements_must_work_for_the_happy_case()
{
this.AssertAllStagesStopped(() =>
{
Source.From(Enumerable.Range(1, 5))
.Throttle(1, TimeSpan.FromMilliseconds(100), 0, _ => 1, ThrottleMode.Shaping)
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(5)
.ExpectNext(1, 2, 3, 4, 5)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void Throttle_for_various_cost_elements_must_emit_elements_according_to_cost()
{
this.AssertAllStagesStopped(() =>
{
var list = Enumerable.Range(1, 4).Select(x => x*2).Select(GenerateByteString).ToList();
Source.From(list)
.Throttle(2, TimeSpan.FromMilliseconds(200), 0, x => x.Count, ThrottleMode.Shaping)
.RunWith(this.SinkProbe<ByteString>(), Materializer)
.Request(4)
.ExpectNext(list[0])
.ExpectNoMsg(TimeSpan.FromMilliseconds(300))
.ExpectNext(list[1])
.ExpectNoMsg(TimeSpan.FromMilliseconds(500))
.ExpectNext(list[2])
.ExpectNoMsg(TimeSpan.FromMilliseconds(700))
.ExpectNext(list[3])
.ExpectComplete();
}, Materializer);
}
[Fact]
public void Throttle_for_various_cost_elements_must_not_send_downstream_if_upstream_does_not_emit_element()
{
this.AssertAllStagesStopped(() =>
{
var upstream = TestPublisher.CreateProbe<int>(this);
var downstream = TestSubscriber.CreateProbe<int>(this);
Source.FromPublisher(upstream)
.Throttle(1, TimeSpan.FromMilliseconds(300), 0, x => x, ThrottleMode.Shaping)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(2);
upstream.SendNext(1);
downstream.ExpectNext(1);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
upstream.SendNext(2);
downstream.ExpectNext(2);
upstream.SendComplete();
downstream.ExpectComplete();
}, Materializer);
}
[Fact]
public void Throttle_for_various_cost_elements_must_cancel_when_downstream_cancels()
{
this.AssertAllStagesStopped(() =>
{
var downstream = TestSubscriber.CreateProbe<int>(this);
Source.From(Enumerable.Range(1, 10))
.Throttle(2, TimeSpan.FromMilliseconds(200), 0, x => x, ThrottleMode.Shaping)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Cancel();
}, Materializer);
}
[Fact]
public void Throttle_for_various_cost_elements_must_send_elements_downstream_as_soon_as_time_comes()
{
this.AssertAllStagesStopped(() =>
{
var probe =
Source.From(Enumerable.Range(1, 10))
.Throttle(4, TimeSpan.FromMilliseconds(500), 0, _ => 2, ThrottleMode.Shaping)
.RunWith(this.SinkProbe<int>(), Materializer);
probe.Request(5);
var result = probe.ReceiveWhile(TimeSpan.FromMilliseconds(600), filter: x => x);
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(100))
.ExpectNext(3)
.ExpectNoMsg(TimeSpan.FromMilliseconds(100))
.ExpectNext(4);
probe.Cancel();
// assertion may take longer then the throttle and therefore the next assertion fails
result.ShouldAllBeEquivalentTo(new[] { new OnNext(1), new OnNext(2) });
}, Materializer);
}
[Fact]
public void Throttle_for_various_cost_elements_must_burst_according_to_its_maximum_if_enough_time_passed()
{
this.AssertAllStagesStopped(() =>
{
var upstream = TestPublisher.CreateProbe<int>(this);
var downstream = TestSubscriber.CreateProbe<int>(this);
Source.FromPublisher(upstream)
.Throttle(2, TimeSpan.FromMilliseconds(400), 5, x => 1, ThrottleMode.Shaping)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(1);
upstream.SendNext(1);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
downstream.ExpectNext(1);
downstream.Request(5);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(1200));
var expected = new List<OnNext>();
for (var i = 2; i < 7; i++)
{
upstream.SendNext(i);
expected.Add(new OnNext(i));
}
downstream.ReceiveWhile(TimeSpan.FromMilliseconds(300), filter: x => x, msgs: 5)
.ShouldAllBeEquivalentTo(expected);
downstream.Cancel();
}, Materializer);
}
[Fact]
public void Throttle_for_various_cost_elements_must_burst_some_elements_if_have_enough_time()
{
this.AssertAllStagesStopped(() =>
{
var upstream = TestPublisher.CreateProbe<int>(this);
var downstream = TestSubscriber.CreateProbe<int>(this);
Source.FromPublisher(upstream)
.Throttle(2, TimeSpan.FromMilliseconds(400), 5, e => e < 4 ? 1 : 20, ThrottleMode.Shaping)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(1);
upstream.SendNext(1);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
downstream.ExpectNext(1);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); //wait to receive 2 in burst afterwards
downstream.Request(5);
var expected = new List<OnNext>();
for (var i = 2; i < 5; i++)
{
upstream.SendNext(i);
if (i < 4)
expected.Add(new OnNext(i));
}
downstream.ReceiveWhile(TimeSpan.FromMilliseconds(200), filter: x => x, msgs: 2)
.ShouldAllBeEquivalentTo(expected);
downstream.Cancel();
}, Materializer);
}
[Fact]
public void Throttle_for_various_cost_elements_must_throw_exception_when_exceeding_throughtput_in_enforced_mode()
{
this.AssertAllStagesStopped(() =>
{
var t =
Source.From(Enumerable.Range(1, 5))
.Throttle(2, TimeSpan.FromMilliseconds(200), 5, x => x, ThrottleMode.Enforcing)
.RunWith(Sink.Ignore<int>(), Materializer);
t.Invoking(task => task.Wait(TimeSpan.FromSeconds(2))).ShouldThrow<OverflowException>();
}, Materializer);
}
[Fact]
public void Throttle_for_various_cost_elements_must_properly_combine_shape_and_throttle_modes()
{
this.AssertAllStagesStopped(() =>
{
Source.From(Enumerable.Range(1, 5))
.Throttle(2, TimeSpan.FromMilliseconds(200), 0, x => x, ThrottleMode.Shaping)
.Throttle(1, TimeSpan.FromMilliseconds(100), 5, ThrottleMode.Enforcing)
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(5)
.ExpectNext(1, 2, 3, 4, 5)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void Throttle_for_various_cost_elements_must_handle_rate_calculation_function_exception()
{
this.AssertAllStagesStopped(() =>
{
var ex = new SystemException();
Source.From(Enumerable.Range(1, 5))
.Throttle(2, TimeSpan.FromMilliseconds(200), 0, _ => { throw ex; }, ThrottleMode.Shaping)
.Throttle(1, TimeSpan.FromMilliseconds(100), 5, ThrottleMode.Enforcing)
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(5)
.ExpectError().Should().Be(ex);
}, Materializer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace StringMatch
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Class that implements Boyer-Moore and related exact string-matching algorithms
/// </summary>
/// <remarks>
/// From "Handbook of exact string-matching algorithms"
/// by Christian Charras and Thierry Lecroq
/// chapter 15
/// http://www-igm.univ-mlv.fr/~lecroq/string/node15.html#SECTION00150
/// </remarks>
public class BoyerMoore
{
private int[] m_badCharacterShift;
private int[] m_goodSuffixShift;
private int[] m_suffixes;
private string m_pattern;
/// <summary>
/// Constructor
/// </summary>
/// <param name="pattern">Pattern for search</param>
public BoyerMoore(string pattern)
{
/* Preprocessing */
m_pattern = pattern;
m_badCharacterShift = BuildBadCharacterShift(pattern);
m_suffixes = FindSuffixes(pattern);
m_goodSuffixShift = BuildGoodSuffixShift(pattern, m_suffixes);
}
/// <summary>
/// Build the bad character shift array.
/// </summary>
/// <param name="pattern">Pattern for search</param>
/// <returns>bad character shift array</returns>
private int[] BuildBadCharacterShift(string pattern)
{
int[] badCharacterShift = new int[256];
for (int c = 0; c < badCharacterShift.Length; ++c)
badCharacterShift[c] = pattern.Length;
for (int i = 0; i < pattern.Length - 1; ++i)
badCharacterShift[pattern[i]] = pattern.Length - i - 1;
return badCharacterShift;
}
/// <summary>
/// Find suffixes in the pattern
/// </summary>
/// <param name="pattern">Pattern for search</param>
/// <returns>Suffix array</returns>
private int[] FindSuffixes(string pattern)
{
int f = 0, g;
int patternLength = pattern.Length;
int[] suffixes = new int[pattern.Length + 1];
suffixes[patternLength - 1] = patternLength;
g = patternLength - 1;
for (int i = patternLength - 2; i >= 0; --i)
{
if (i > g && suffixes[i + patternLength - 1 - f] < i - g)
suffixes[i] = suffixes[i + patternLength - 1 - f];
else
{
if (i < g)
g = i;
f = i;
while (g >= 0 && (pattern[g] == pattern[g + patternLength - 1 - f]))
--g;
suffixes[i] = f - g;
}
}
return suffixes;
}
/// <summary>
/// Build the good suffix array.
/// </summary>
/// <param name="pattern">Pattern for search</param>
/// <returns>Good suffix shift array</returns>
private int[] BuildGoodSuffixShift(string pattern, int[] suff)
{
int patternLength = pattern.Length;
int[] goodSuffixShift = new int[pattern.Length + 1];
for (int i = 0; i < patternLength; ++i)
goodSuffixShift[i] = patternLength;
int j = 0;
for (int i = patternLength - 1; i >= -1; --i)
if (i == -1 || suff[i] == i + 1)
for (; j < patternLength - 1 - i; ++j)
if (goodSuffixShift[j] == patternLength)
goodSuffixShift[j] = patternLength - 1 - i;
for (int i = 0; i <= patternLength - 2; ++i)
goodSuffixShift[patternLength - 1 - suff[i]] = patternLength - 1 - i;
return goodSuffixShift;
}
/// <summary>
/// Return all matched of the pattern in the specified text using the .NET String.indexOf API
/// </summary>
/// <param name="text">text to be searched</param>
/// <param name="startingIndex">Index at which search begins</param>
/// <returns>IEnumerable which returns the indexes of pattern matches</returns>
public IEnumerable<int> BCLMatch(string text, int startingIndex)
{
int patternLength = m_pattern.Length;
int index = startingIndex;
do
{
index = text.IndexOf(m_pattern, index, StringComparison.InvariantCultureIgnoreCase);
if (index < 0)
yield break;
yield return index;
index += patternLength;
} while (true);
}
/// <summary>
/// Return all matched of the pattern in the specified text using the .NET String.indexOf API
/// </summary>
/// <param name="text">text to be searched</param>
/// <returns>IEnumerable which returns the indexes of pattern matches</returns>
public IEnumerable<int> BCLMatch(string text)
{
return BCLMatch(text, 0);
}
/// <summary>
/// Return all matches of the pattern in specified text using the Horspool algorithm
/// </summary>
/// <param name="text">text to be searched</param>
/// <param name="startingIndex">Index at which search begins</param>
/// <returns>IEnumerable which returns the indexes of pattern matches</returns>
public IEnumerable<int> HorspoolMatch(string text, int startingIndex)
{
int patternLength = m_pattern.Length;
int textLength = text.Length;
/* Searching */
int index = startingIndex;
while (index <= textLength - patternLength)
{
int unmatched;
for (
unmatched = patternLength - 1;
unmatched >= 0 && m_pattern[unmatched] == text[unmatched + index];
--unmatched
)
; // empty
if (unmatched < 0)
yield return index;
index += m_badCharacterShift[text[unmatched + patternLength - 1]];
}
}
/// <summary>
/// Return all matches of the pattern in specified text using the Horspool algorithm
/// </summary>
/// <param name="text">text to be searched</param>
/// <returns>IEnumerable which returns the indexes of pattern matches</returns>
public IEnumerable<int> HorspoolMatch(string text)
{
return HorspoolMatch(text, 0);
}
/// <summary>
/// Return all matches of the pattern in specified text using the Boyer-Moore algorithm
/// </summary>
/// <param name="text">text to be searched</param>
/// <param name="startingIndex">Index at which search begins</param>
/// <returns>IEnumerable which returns the indexes of pattern matches</returns>
public IEnumerable<int> BoyerMooreMatch(string text, int startingIndex)
{
int patternLength = m_pattern.Length;
int textLength = text.Length;
/* Searching */
int index = startingIndex;
while (index <= textLength - patternLength)
{
int unmatched;
for (unmatched = patternLength - 1;
unmatched >= 0 && (m_pattern[unmatched] == text[unmatched + index]);
--unmatched
)
; // empty
if (unmatched < 0)
{
yield return index;
index += m_goodSuffixShift[0];
}
else
index += Math.Max(m_goodSuffixShift[unmatched],
m_badCharacterShift[text[unmatched + index]] - patternLength + 1 + unmatched);
}
}
/// <summary>
/// Return all matches of the pattern in specified text using the Boyer-Moore algorithm
/// </summary>
/// <param name="text">text to be searched</param>
/// <returns>IEnumerable which returns the indexes of pattern matches</returns>
public IEnumerable<int> BoyerMooreMatch(string text)
{
return BoyerMooreMatch(text, 0);
}
/// <summary>
/// Return all matches of the pattern in specified text using the Turbo Boyer-Moore algorithm
/// </summary>
/// <param name="text">text to be searched</param>
/// <param name="startingIndex">Index at which search begins</param>
/// <returns>IEnumerable which returns the indexes of pattern matches</returns>
public IEnumerable<int> TurboBoyerMooreMatch(string text, int startingIndex)
{
int patternLength = m_pattern.Length;
int textLength = text.Length;
/* Searching */
int index = startingIndex;
int overlap = 0;
int shift = patternLength;
while (index <= textLength - patternLength)
{
int unmatched = patternLength - 1;
while (unmatched >= 0 && (m_pattern[unmatched] == text[unmatched + index]))
{
--unmatched;
if (overlap != 0 && unmatched == patternLength - 1 - shift)
unmatched -= overlap;
}
if (unmatched < 0)
{
yield return index;
shift = m_goodSuffixShift[0];
overlap = patternLength - shift;
}
else
{
int matched = patternLength - 1 - unmatched;
int turboShift = overlap - matched;
int bcShift = m_badCharacterShift[text[unmatched + index]] - patternLength + 1 + unmatched;
shift = Math.Max(turboShift, bcShift);
shift = Math.Max(shift, m_goodSuffixShift[unmatched]);
if (shift == m_goodSuffixShift[unmatched])
overlap = Math.Min(patternLength - shift, matched);
else
{
if (turboShift < bcShift)
shift = Math.Max(shift, overlap + 1);
overlap = 0;
}
}
index += shift;
}
}
/// <summary>
/// Return all matches of the pattern in specified text using the Turbo Boyer-Moore algorithm
/// </summary>
/// <param name="text">text to be searched</param>
/// <returns>IEnumerable which returns the indexes of pattern matches</returns>
public IEnumerable<int> TurboBoyerMooreMatch(string text)
{
return TurboBoyerMooreMatch(text, 0);
}
/// <summary>
/// Return all matches of the pattern in specified text using the Apostolico-GiancarloMatch algorithm
/// </summary>
/// <param name="text">text to be searched</param>
/// <param name="startingIndex">Index at which search begins</param>
/// <returns>IEnumerable which returns the indexes of pattern matches</returns>
public IEnumerable<int> ApostolicoGiancarloMatch(string text, int startingIndex)
{
int patternLength = m_pattern.Length;
int textLength = text.Length;
int[] skip = new int[patternLength];
int shift;
/* Searching */
int index = startingIndex;
while (index <= textLength - patternLength)
{
int unmatched = patternLength - 1;
while (unmatched >= 0)
{
int skipLength = skip[unmatched];
int suffixLength = m_suffixes[unmatched];
if (skipLength > 0)
if (skipLength > suffixLength)
{
if (unmatched + 1 == suffixLength)
unmatched = (-1);
else
unmatched -= suffixLength;
break;
}
else
{
unmatched -= skipLength;
if (skipLength < suffixLength)
break;
}
else
{
if (m_pattern[unmatched] == text[unmatched + index])
--unmatched;
else
break;
}
}
if (unmatched < 0)
{
yield return index;
skip[patternLength - 1] = patternLength;
shift = m_goodSuffixShift[0];
}
else
{
skip[patternLength - 1] = patternLength - 1 - unmatched;
shift = Math.Max(m_goodSuffixShift[unmatched],
m_badCharacterShift[text[unmatched + index]] - patternLength + 1 + unmatched
);
}
index += shift;
for (int copy = 0; copy < patternLength - shift; ++copy)
skip[copy] = skip[copy + shift];
for (int clear = 0; clear < shift; ++clear)
skip[patternLength - shift + clear] = 0;
}
}
/// <summary>
/// Return all matches of the pattern in specified text using the Apostolico-GiancarloMatch algorithm
/// </summary>
/// <param name="text">text to be searched</param>
/// <returns>IEnumerable which returns the indexes of pattern matches</returns>
public IEnumerable<int> ApostolicoGiancarloMatch(string text)
{
return ApostolicoGiancarloMatch(text, 0);
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
#if NETSTANDARD1_3
using System.Globalization;
#else
using System.Configuration;
#endif
using System.Reflection;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;
namespace log4net.Util
{
/// <summary>
/// Utility class for system specific information.
/// </summary>
/// <remarks>
/// <para>
/// Utility class of static methods for system specific information.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Alexey Solofnenko</author>
public sealed class SystemInfo
{
#region Private Constants
private const string DEFAULT_NULL_TEXT = "(null)";
private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE";
#endregion
#region Private Instance Constructors
/// <summary>
/// Private constructor to prevent instances.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
private SystemInfo()
{
}
#endregion Private Instance Constructors
#region Public Static Constructor
/// <summary>
/// Initialize default values for private static fields.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
static SystemInfo()
{
string nullText = DEFAULT_NULL_TEXT;
string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT;
#if !NETCF
// Look for log4net.NullText in AppSettings
string nullTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NullText");
if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "].");
nullText = nullTextAppSettingsKey;
}
// Look for log4net.NotAvailableText in AppSettings
string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NotAvailableText");
if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "].");
notAvailableText = notAvailableTextAppSettingsKey;
}
#endif
s_notAvailableText = notAvailableText;
s_nullText = nullText;
}
#endregion
#region Public Static Properties
/// <summary>
/// Gets the system dependent line terminator.
/// </summary>
/// <value>
/// The system dependent line terminator.
/// </value>
/// <remarks>
/// <para>
/// Gets the system dependent line terminator.
/// </para>
/// </remarks>
public static string NewLine
{
get
{
#if NETCF
return "\r\n";
#else
return System.Environment.NewLine;
#endif
}
}
/// <summary>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </summary>
/// <value>The base directory path for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ApplicationBaseDirectory
{
get
{
#if NETCF
- return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar;
#elif NETSTANDARD1_3
return Directory.GetCurrentDirectory();
#else
return AppDomain.CurrentDomain.BaseDirectory;
#endif
}
}
/// <summary>
/// Gets the path to the configuration file for the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the configuration file for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// The .NET Compact Framework 1.0 does not have a concept of a configuration
/// file. For this runtime, we use the entry assembly location as the root for
/// the configuration file name.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ConfigurationFileLocation
{
get
{
#if NETCF || NETSTANDARD1_3
return SystemInfo.EntryAssemblyLocation+".config";
#else
return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
#endif
}
}
/// <summary>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the entry assembly.</value>
/// <remarks>
/// <para>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </para>
/// </remarks>
public static string EntryAssemblyLocation
{
get
{
#if NETCF
return SystemInfo.NativeEntryAssemblyLocation;
#elif NETSTANDARD1_3 // TODO GetEntryAssembly is available for netstandard1.5
return AppContext.BaseDirectory;
#else
return System.Reflection.Assembly.GetEntryAssembly().Location;
#endif
}
}
/// <summary>
/// Gets the ID of the current thread.
/// </summary>
/// <value>The ID of the current thread.</value>
/// <remarks>
/// <para>
/// On the .NET framework, the <c>AppDomain.GetCurrentThreadId</c> method
/// is used to obtain the thread ID for the current thread. This is the
/// operating system ID for the thread.
/// </para>
/// <para>
/// On the .NET Compact Framework 1.0 it is not possible to get the
/// operating system thread ID for the current thread. The native method
/// <c>GetCurrentThreadId</c> is implemented inline in a header file
/// and cannot be called.
/// </para>
/// <para>
/// On the .NET Framework 2.0 the <c>Thread.ManagedThreadId</c> is used as this
/// gives a stable id unrelated to the operating system thread ID which may
/// change if the runtime is using fibers.
/// </para>
/// </remarks>
public static int CurrentThreadId
{
get
{
#if NETCF_1_0
return System.Threading.Thread.CurrentThread.GetHashCode();
#elif NET_2_0 || NETCF_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD1_3
return System.Threading.Thread.CurrentThread.ManagedThreadId;
#else
return AppDomain.GetCurrentThreadId();
#endif
}
}
/// <summary>
/// Get the host name or machine name for the current machine
/// </summary>
/// <value>
/// The hostname or machine name
/// </value>
/// <remarks>
/// <para>
/// Get the host name or machine name for the current machine
/// </para>
/// <para>
/// The host name (<see cref="System.Net.Dns.GetHostName"/>) or
/// the machine name (<c>Environment.MachineName</c>) for
/// the current machine, or if neither of these are available
/// then <c>NOT AVAILABLE</c> is returned.
/// </para>
/// </remarks>
public static string HostName
{
get
{
if (s_hostName == null)
{
// Get the DNS host name of the current machine
try
{
// Lookup the host name
s_hostName = System.Net.Dns.GetHostName();
}
catch (System.Net.Sockets.SocketException)
{
LogLog.Debug(declaringType, "Socket exception occurred while getting the dns hostname. Error Ignored.");
}
catch (System.Security.SecurityException)
{
// We may get a security exception looking up the hostname
// You must have Unrestricted DnsPermission to access resource
LogLog.Debug(declaringType, "Security exception occurred while getting the dns hostname. Error Ignored.");
}
catch (Exception ex)
{
LogLog.Debug(declaringType, "Some other exception occurred while getting the dns hostname. Error Ignored.", ex);
}
// Get the NETBIOS machine name of the current machine
if (s_hostName == null || s_hostName.Length == 0)
{
try
{
#if NETSTANDARD1_3
s_hostName = Environment.GetEnvironmentVariable("COMPUTERNAME");
#elif (!SSCLI && !NETCF)
s_hostName = Environment.MachineName;
#endif
}
catch(InvalidOperationException)
{
}
catch(System.Security.SecurityException)
{
// We may get a security exception looking up the machine name
// You must have Unrestricted EnvironmentPermission to access resource
}
}
// Couldn't find a value
if (s_hostName == null || s_hostName.Length == 0)
{
s_hostName = s_notAvailableText;
LogLog.Debug(declaringType, "Could not determine the hostname. Error Ignored. Empty host name will be used");
}
}
return s_hostName;
}
}
/// <summary>
/// Get this application's friendly name
/// </summary>
/// <value>
/// The friendly name of this application as a string
/// </value>
/// <remarks>
/// <para>
/// If available the name of the application is retrieved from
/// the <c>AppDomain</c> using <c>AppDomain.CurrentDomain.FriendlyName</c>.
/// </para>
/// <para>
/// Otherwise the file name of the entry assembly is used.
/// </para>
/// </remarks>
public static string ApplicationFriendlyName
{
get
{
if (s_appFriendlyName == null)
{
try
{
#if !(NETCF || NETSTANDARD1_3)
s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName;
#endif
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// some undefined set of SecurityPermission flags.
LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored.");
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
try
{
string assemblyLocation = SystemInfo.EntryAssemblyLocation;
s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation);
}
catch(System.Security.SecurityException)
{
// Caller needs path discovery permission
}
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
s_appFriendlyName = s_notAvailableText;
}
}
return s_appFriendlyName;
}
}
/// <summary>
/// Get the UTC start time for the current process.
/// </summary>
/// <remarks>
/// <para>
/// This is the UTC time at which the log4net library was loaded into the
/// AppDomain. Due to reports of a hang in the call to <c>System.Diagnostics.Process.StartTime</c>
/// this is not the start time for the current process.
/// </para>
/// <para>
/// The log4net library should be loaded by an application early during its
/// startup, therefore this start time should be a good approximation for
/// the actual start time.
/// </para>
/// <para>
/// Note that AppDomains may be loaded and unloaded within the
/// same process without the process terminating, however this start time
/// will be set per AppDomain.
/// </para>
/// </remarks>
public static DateTime ProcessStartTimeUtc
{
get { return s_processStartTimeUtc; }
}
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
/// <remarks>
/// <para>
/// Use this value to indicate a <c>null</c> has been encountered while
/// outputting a string representation of an item.
/// </para>
/// <para>
/// The default value is <c>(null)</c>. This value can be overridden by specifying
/// a value for the <c>log4net.NullText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NullText
{
get { return s_nullText; }
set { s_nullText = value; }
}
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
/// <remarks>
/// <para>
/// Use this value when an unsupported feature is requested.
/// </para>
/// <para>
/// The default value is <c>NOT AVAILABLE</c>. This value can be overridden by specifying
/// a value for the <c>log4net.NotAvailableText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NotAvailableText
{
get { return s_notAvailableText; }
set { s_notAvailableText = value; }
}
#endregion Public Static Properties
#region Public Static Methods
/// <summary>
/// Gets the assembly location path for the specified assembly.
/// </summary>
/// <param name="myAssembly">The assembly to get the location for.</param>
/// <returns>The location of the assembly.</returns>
/// <remarks>
/// <para>
/// This method does not guarantee to return the correct path
/// to the assembly. If only tries to give an indication as to
/// where the assembly was loaded from.
/// </para>
/// </remarks>
public static string AssemblyLocationInfo(Assembly myAssembly)
{
#if NETCF
return "Not supported on Microsoft .NET Compact Framework";
#elif NETSTANDARD1_3 // TODO Assembly.Location available in netstandard1.5
return "Not supported on .NET Core";
#else
if (myAssembly.GlobalAssemblyCache)
{
return "Global Assembly Cache";
}
else
{
try
{
#if NET_4_0 || MONO_4_0
if (myAssembly.IsDynamic)
{
return "Dynamic Assembly";
}
#else
if (myAssembly is System.Reflection.Emit.AssemblyBuilder)
{
return "Dynamic Assembly";
}
else if(myAssembly.GetType().FullName == "System.Reflection.Emit.InternalAssemblyBuilder")
{
return "Dynamic Assembly";
}
#endif
else
{
// This call requires FileIOPermission for access to the path
// if we don't have permission then we just ignore it and
// carry on.
return myAssembly.Location;
}
}
catch (NotSupportedException)
{
// The location information may be unavailable for dynamic assemblies and a NotSupportedException
// is thrown in those cases. See: http://msdn.microsoft.com/de-de/library/system.reflection.assembly.location.aspx
return "Dynamic Assembly";
}
catch (TargetInvocationException ex)
{
return "Location Detect Failed (" + ex.Message + ")";
}
catch (ArgumentException ex)
{
return "Location Detect Failed (" + ex.Message + ")";
}
catch (System.Security.SecurityException)
{
return "Location Permission Denied";
}
}
#endif
}
/// <summary>
/// Gets the fully qualified name of the <see cref="Type" />, including
/// the name of the assembly from which the <see cref="Type" /> was
/// loaded.
/// </summary>
/// <param name="type">The <see cref="Type" /> to get the fully qualified name for.</param>
/// <returns>The fully qualified name for the <see cref="Type" />.</returns>
/// <remarks>
/// <para>
/// This is equivalent to the <c>Type.AssemblyQualifiedName</c> property,
/// but this method works on the .NET Compact Framework 1.0 as well as
/// the full .NET runtime.
/// </para>
/// </remarks>
public static string AssemblyQualifiedName(Type type)
{
return type.FullName + ", "
#if NETSTANDARD1_3
+ type.GetTypeInfo().Assembly.FullName;
#else
+ type.Assembly.FullName;
#endif
}
/// <summary>
/// Gets the short name of the <see cref="Assembly" />.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the name for.</param>
/// <returns>The short name of the <see cref="Assembly" />.</returns>
/// <remarks>
/// <para>
/// The short name of the assembly is the <see cref="Assembly.FullName" />
/// without the version, culture, or public key. i.e. it is just the
/// assembly's file name without the extension.
/// </para>
/// <para>
/// Use this rather than <c>Assembly.GetName().Name</c> because that
/// is not available on the Compact Framework.
/// </para>
/// <para>
/// Because of a FileIOPermission security demand we cannot do
/// the obvious Assembly.GetName().Name. We are allowed to get
/// the <see cref="Assembly.FullName" /> of the assembly so we
/// start from there and strip out just the assembly name.
/// </para>
/// </remarks>
public static string AssemblyShortName(Assembly myAssembly)
{
string name = myAssembly.FullName;
int offset = name.IndexOf(',');
if (offset > 0)
{
name = name.Substring(0, offset);
}
return name.Trim();
// TODO: Do we need to unescape the assembly name string?
// Doc says '\' is an escape char but has this already been
// done by the string loader?
}
/// <summary>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the file name for.</param>
/// <returns>The file name of the assembly.</returns>
/// <remarks>
/// <para>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </para>
/// </remarks>
public static string AssemblyFileName(Assembly myAssembly)
{
#if NETCF || NETSTANDARD1_3 // TODO Assembly.Location is in netstandard1.5 System.Reflection
// This is not very good because it assumes that only
// the entry assembly can be an EXE. In fact multiple
// EXEs can be loaded in to a process.
string assemblyShortName = SystemInfo.AssemblyShortName(myAssembly);
string entryAssemblyShortName = System.IO.Path.GetFileNameWithoutExtension(SystemInfo.EntryAssemblyLocation);
if (string.Compare(assemblyShortName, entryAssemblyShortName, true) == 0)
{
// assembly is entry assembly
return assemblyShortName + ".exe";
}
else
{
// assembly is not entry assembly
return assemblyShortName + ".dll";
}
#else
return System.IO.Path.GetFileName(myAssembly.Location);
#endif
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeType">A sibling type to use to load the type.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified, it will be loaded from the assembly
/// containing the specified relative type. If the type is not found in the assembly
/// then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase)
{
#if NETSTANDARD1_3
return GetTypeFromString(relativeType.GetTypeInfo().Assembly, typeName, throwOnError, ignoreCase);
#else
return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase);
#endif
}
#if !NETSTANDARD1_3
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the
/// assembly that is directly calling this method. If the type is not found
/// in the assembly then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase);
}
#endif
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeAssembly">An assembly to load the type from.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the specified
/// assembly. If the type is not found in the assembly then all the loaded assemblies
/// will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase)
{
// Check if the type name specifies the assembly name
if(typeName.IndexOf(',') == -1)
{
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
#if NETSTANDARD1_3
return relativeAssembly.GetType(typeName, throwOnError, ignoreCase);
#elif NETCF
return relativeAssembly.GetType(typeName, throwOnError);
#else
// Attempt to lookup the type from the relativeAssembly
Type type = relativeAssembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in relative assembly
//LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
return type;
}
Assembly[] loadedAssemblies = null;
try
{
loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
}
catch(System.Security.SecurityException)
{
// Insufficient permissions to get the list of loaded assemblies
}
if (loadedAssemblies != null)
{
Type fallback = null;
// Search the loaded assemblies for the type
foreach (Assembly assembly in loadedAssemblies)
{
Type t = assembly.GetType(typeName, false, ignoreCase);
if (t != null)
{
// Found type in loaded assembly
LogLog.Debug(declaringType, "Loaded type ["+typeName+"] from assembly ["+assembly.FullName+"] by searching loaded assemblies.");
if (assembly.GlobalAssemblyCache)
{
fallback = t;
}
else
{
return t;
}
}
}
if (fallback != null)
{
return fallback;
}
}
// Didn't find the type
if (throwOnError)
{
throw new TypeLoadException("Could not load type ["+typeName+"]. Tried assembly ["+relativeAssembly.FullName+"] and all loaded assemblies");
}
return null;
#endif
}
else
{
// Includes explicit assembly name
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type");
#if NETCF
// In NETCF 2 and 3 arg versions seem to behave differently
// https://issues.apache.org/jira/browse/LOG4NET-113
return Type.GetType(typeName, throwOnError);
#else
return Type.GetType(typeName, throwOnError, ignoreCase);
#endif
}
}
/// <summary>
/// Generate a new guid
/// </summary>
/// <returns>A new Guid</returns>
/// <remarks>
/// <para>
/// Generate a new guid
/// </para>
/// </remarks>
public static Guid NewGuid()
{
#if NETCF_1_0
return PocketGuid.NewGuid();
#else
return Guid.NewGuid();
#endif
}
/// <summary>
/// Create an <see cref="ArgumentOutOfRangeException"/>
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the exception</param>
/// <param name="actualValue">The value of the argument that causes this exception</param>
/// <param name="message">The message that describes the error</param>
/// <returns>the ArgumentOutOfRangeException object</returns>
/// <remarks>
/// <para>
/// Create a new instance of the <see cref="ArgumentOutOfRangeException"/> class
/// with a specified error message, the parameter name, and the value
/// of the argument.
/// </para>
/// <para>
/// The Compact Framework does not support the 3 parameter constructor for the
/// <see cref="ArgumentOutOfRangeException"/> type. This method provides an
/// implementation that works for all platforms.
/// </para>
/// </remarks>
public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message)
{
#if NETCF_1_0
return new ArgumentOutOfRangeException(message + " [param=" + parameterName + "] [value=" + actualValue + "]");
#elif NETCF_2_0
return new ArgumentOutOfRangeException(parameterName, message + " [value=" + actualValue + "]");
#else
return new ArgumentOutOfRangeException(parameterName, actualValue, message);
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int32"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out int val)
{
#if NETCF
val = 0;
try
{
val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt32(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int64"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out long val)
{
#if NETCF
val = 0;
try
{
val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt64(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int16"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out short val)
{
#if NETCF
val = 0;
try
{
val = short.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt16(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Lookup an application setting
/// </summary>
/// <param name="key">the application settings key to lookup</param>
/// <returns>the value for the key, or <c>null</c></returns>
/// <remarks>
/// <para>
/// Configuration APIs are not supported under the Compact Framework
/// </para>
/// </remarks>
public static string GetAppSetting(string key)
{
try
{
#if NETCF || NETSTANDARD1_3
// Configuration APIs are not suported under the Compact Framework
#elif NET_2_0
return ConfigurationManager.AppSettings[key];
#else
return ConfigurationSettings.AppSettings[key];
#endif
}
catch(Exception ex)
{
// If an exception is thrown here then it looks like the config file does not parse correctly.
LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex);
}
return null;
}
/// <summary>
/// Convert a path into a fully qualified local file path.
/// </summary>
/// <param name="path">The path to convert.</param>
/// <returns>The fully qualified path.</returns>
/// <remarks>
/// <para>
/// Converts the path specified to a fully
/// qualified path. If the path is relative it is
/// taken as relative from the application base
/// directory.
/// </para>
/// <para>
/// The path specified must be a local file path, a URI is not supported.
/// </para>
/// </remarks>
public static string ConvertToFullPath(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
string baseDirectory = "";
try
{
string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
if (applicationBaseDirectory != null)
{
// applicationBaseDirectory may be a URI not a local file path
Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory);
if (applicationBaseDirectoryUri.IsFile)
{
baseDirectory = applicationBaseDirectoryUri.LocalPath;
}
}
}
catch
{
// Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory
}
if (baseDirectory != null && baseDirectory.Length > 0)
{
// Note that Path.Combine will return the second path if it is rooted
return Path.GetFullPath(Path.Combine(baseDirectory, path));
}
return Path.GetFullPath(path);
}
/// <summary>
/// Creates a new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity.
/// </summary>
/// <returns>A new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity</returns>
/// <remarks>
/// <para>
/// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer.
/// </para>
/// </remarks>
public static Hashtable CreateCaseInsensitiveHashtable()
{
#if NETCF_1_0
return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default);
#elif NETCF_2_0 || NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0
return new Hashtable(StringComparer.OrdinalIgnoreCase);
#else
return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable();
#endif
}
/// <summary>
/// Tests two strings for equality, the ignoring case.
/// </summary>
/// <remarks>
/// If the platform permits, culture information is ignored completely (ordinal comparison).
/// The aim of this method is to provide a fast comparison that deals with <c>null</c> and ignores different casing.
/// It is not supposed to deal with various, culture-specific habits.
/// Use it to compare against pure ASCII constants, like keywords etc.
/// </remarks>
/// <param name="a">The one string.</param>
/// <param name="b">The other string.</param>
/// <returns><c>true</c> if the strings are equal, <c>false</c> otherwise.</returns>
public static Boolean EqualsIgnoringCase(String a, String b)
{
#if NET_1_0 || NET_1_1 || NETCF_1_0
return string.Compare(a, b, true, System.Globalization.CultureInfo.InvariantCulture) == 0
#elif NETSTANDARD1_3
return CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0;
#else // >= .NET-2.0
return String.Equals(a, b, StringComparison.OrdinalIgnoreCase);
#endif
}
#endregion Public Static Methods
#region Private Static Methods
#if NETCF
private static string NativeEntryAssemblyLocation
{
get
{
StringBuilder moduleName = null;
IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero);
if (moduleHandle != IntPtr.Zero)
{
moduleName = new StringBuilder(255);
if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0)
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
}
else
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
return moduleName.ToString();
}
}
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(IntPtr ModuleName);
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern Int32 GetModuleFileName(
IntPtr hModule,
StringBuilder ModuleName,
Int32 cch);
#endif
#endregion Private Static Methods
#region Public Static Fields
/// <summary>
/// Gets an empty array of types.
/// </summary>
/// <remarks>
/// <para>
/// The <c>Type.EmptyTypes</c> field is not available on
/// the .NET Compact Framework 1.0.
/// </para>
/// </remarks>
public static readonly Type[] EmptyTypes = new Type[0];
#endregion Public Static Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the SystemInfo class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(SystemInfo);
/// <summary>
/// Cache the host name for the current machine
/// </summary>
private static string s_hostName;
/// <summary>
/// Cache the application friendly name
/// </summary>
private static string s_appFriendlyName;
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
private static string s_nullText;
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
private static string s_notAvailableText;
/// <summary>
/// Start time for the current process.
/// </summary>
private static DateTime s_processStartTimeUtc = DateTime.UtcNow;
#endregion
#region Compact Framework Helper Classes
#if NETCF_1_0
/// <summary>
/// Generate GUIDs on the .NET Compact Framework.
/// </summary>
public class PocketGuid
{
// guid variant types
private enum GuidVariant
{
ReservedNCS = 0x00,
Standard = 0x02,
ReservedMicrosoft = 0x06,
ReservedFuture = 0x07
}
// guid version types
private enum GuidVersion
{
TimeBased = 0x01,
Reserved = 0x02,
NameBased = 0x03,
Random = 0x04
}
// constants that are used in the class
private class Const
{
// number of bytes in guid
public const int ByteArraySize = 16;
// multiplex variant info
public const int VariantByte = 8;
public const int VariantByteMask = 0x3f;
public const int VariantByteShift = 6;
// multiplex version info
public const int VersionByte = 7;
public const int VersionByteMask = 0x0f;
public const int VersionByteShift = 4;
}
// imports for the crypto api functions
private class WinApi
{
public const uint PROV_RSA_FULL = 1;
public const uint CRYPT_VERIFYCONTEXT = 0xf0000000;
[DllImport("CoreDll.dll")]
public static extern bool CryptAcquireContext(
ref IntPtr phProv, string pszContainer, string pszProvider,
uint dwProvType, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptReleaseContext(
IntPtr hProv, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptGenRandom(
IntPtr hProv, int dwLen, byte[] pbBuffer);
}
// all static methods
private PocketGuid()
{
}
/// <summary>
/// Return a new System.Guid object.
/// </summary>
public static Guid NewGuid()
{
IntPtr hCryptProv = IntPtr.Zero;
Guid guid = Guid.Empty;
try
{
// holds random bits for guid
byte[] bits = new byte[Const.ByteArraySize];
// get crypto provider handle
if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null,
WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT))
{
throw new SystemException(
"Failed to acquire cryptography handle.");
}
// generate a 128 bit (16 byte) cryptographically random number
if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits))
{
throw new SystemException(
"Failed to generate cryptography random bytes.");
}
// set the variant
bits[Const.VariantByte] &= Const.VariantByteMask;
bits[Const.VariantByte] |=
((int)GuidVariant.Standard << Const.VariantByteShift);
// set the version
bits[Const.VersionByte] &= Const.VersionByteMask;
bits[Const.VersionByte] |=
((int)GuidVersion.Random << Const.VersionByteShift);
// create the new System.Guid object
guid = new Guid(bits);
}
finally
{
// release the crypto provider handle
if (hCryptProv != IntPtr.Zero)
WinApi.CryptReleaseContext(hCryptProv, 0);
}
return guid;
}
}
#endif
#endregion Compact Framework Helper Classes
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Dataproc.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedBatchControllerClientTest
{
[xunit::FactAttribute]
public void GetBatchRequestObject()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch response = client.GetBatch(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetBatchRequestObjectAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Batch>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch responseCallSettings = await client.GetBatchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Batch responseCancellationToken = await client.GetBatchAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetBatch()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch response = client.GetBatch(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetBatchAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Batch>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch responseCallSettings = await client.GetBatchAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Batch responseCancellationToken = await client.GetBatchAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetBatchResourceNames()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch response = client.GetBatch(request.BatchName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetBatchResourceNamesAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Batch>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch responseCallSettings = await client.GetBatchAsync(request.BatchName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Batch responseCancellationToken = await client.GetBatchAsync(request.BatchName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteBatchRequestObject()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
client.DeleteBatch(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteBatchRequestObjectAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
await client.DeleteBatchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteBatchAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteBatch()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
client.DeleteBatch(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteBatchAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
await client.DeleteBatchAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteBatchAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteBatchResourceNames()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
client.DeleteBatch(request.BatchName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteBatchResourceNamesAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
await client.DeleteBatchAsync(request.BatchName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteBatchAsync(request.BatchName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright 2017 Google Inc. 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.
// This provider is only available on an Android device.
#if UNITY_ANDROID && !UNITY_EDITOR
using UnityEngine;
using System;
using System.Runtime.InteropServices;
/// @cond
namespace Gvr.Internal {
/// Controller Provider that uses the native GVR C API to communicate with controllers
/// via Google VR Services on Android.
class AndroidNativeControllerProvider : IControllerProvider {
// Note: keep structs and function signatures in sync with the C header file (gvr_controller.h).
// GVR controller option flags.
private const int GVR_CONTROLLER_ENABLE_ORIENTATION = 1 << 0;
private const int GVR_CONTROLLER_ENABLE_TOUCH = 1 << 1;
private const int GVR_CONTROLLER_ENABLE_GYRO = 1 << 2;
private const int GVR_CONTROLLER_ENABLE_ACCEL = 1 << 3;
private const int GVR_CONTROLLER_ENABLE_GESTURES = 1 << 4;
private const int GVR_CONTROLLER_ENABLE_POSE_PREDICTION = 1 << 5;
// enum gvr_controller_button:
private const int GVR_CONTROLLER_BUTTON_NONE = 0;
private const int GVR_CONTROLLER_BUTTON_CLICK = 1;
private const int GVR_CONTROLLER_BUTTON_HOME = 2;
private const int GVR_CONTROLLER_BUTTON_APP = 3;
private const int GVR_CONTROLLER_BUTTON_VOLUME_UP = 4;
private const int GVR_CONTROLLER_BUTTON_VOLUME_DOWN = 5;
private const int GVR_CONTROLLER_BUTTON_COUNT = 6;
// enum gvr_controller_connection_state:
private const int GVR_CONTROLLER_DISCONNECTED = 0;
private const int GVR_CONTROLLER_SCANNING = 1;
private const int GVR_CONTROLLER_CONNECTING = 2;
private const int GVR_CONTROLLER_CONNECTED = 3;
// enum gvr_controller_api_status
private const int GVR_CONTROLLER_API_OK = 0;
private const int GVR_CONTROLLER_API_UNSUPPORTED = 1;
private const int GVR_CONTROLLER_API_NOT_AUTHORIZED = 2;
private const int GVR_CONTROLLER_API_UNAVAILABLE = 3;
private const int GVR_CONTROLLER_API_SERVICE_OBSOLETE = 4;
private const int GVR_CONTROLLER_API_CLIENT_OBSOLETE = 5;
private const int GVR_CONTROLLER_API_MALFUNCTION = 6;
[StructLayout(LayoutKind.Sequential)]
private struct gvr_quat {
internal float x;
internal float y;
internal float z;
internal float w;
}
[StructLayout(LayoutKind.Sequential)]
private struct gvr_vec3 {
internal float x;
internal float y;
internal float z;
}
[StructLayout(LayoutKind.Sequential)]
private struct gvr_vec2 {
internal float x;
internal float y;
}
private const string dllName = GvrActivityHelper.GVR_DLL_NAME;
[DllImport(dllName)]
private static extern int gvr_controller_get_default_options();
[DllImport(dllName)]
private static extern IntPtr gvr_controller_create_and_init_android(
IntPtr jniEnv, IntPtr androidContext, IntPtr classLoader,
int options, IntPtr context);
[DllImport(dllName)]
private static extern void gvr_controller_destroy(ref IntPtr api);
[DllImport(dllName)]
private static extern void gvr_controller_pause(IntPtr api);
[DllImport(dllName)]
private static extern void gvr_controller_resume(IntPtr api);
[DllImport(dllName)]
private static extern IntPtr gvr_controller_state_create();
[DllImport(dllName)]
private static extern void gvr_controller_state_destroy(ref IntPtr state);
[DllImport(dllName)]
private static extern void gvr_controller_state_update(IntPtr api, int flags, IntPtr out_state);
[DllImport(dllName)]
private static extern int gvr_controller_state_get_api_status(IntPtr state);
[DllImport(dllName)]
private static extern int gvr_controller_state_get_connection_state(IntPtr state);
[DllImport(dllName)]
private static extern gvr_quat gvr_controller_state_get_orientation(IntPtr state);
[DllImport(dllName)]
private static extern gvr_vec3 gvr_controller_state_get_gyro(IntPtr state);
[DllImport(dllName)]
private static extern gvr_vec3 gvr_controller_state_get_accel(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_is_touching(IntPtr state);
[DllImport(dllName)]
private static extern gvr_vec2 gvr_controller_state_get_touch_pos(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_touch_down(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_touch_up(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_recentered(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_button_state(IntPtr state, int button);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_button_down(IntPtr state, int button);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_button_up(IntPtr state, int button);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_orientation_timestamp(IntPtr state);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_gyro_timestamp(IntPtr state);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_accel_timestamp(IntPtr state);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_touch_timestamp(IntPtr state);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_button_timestamp(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_battery_charging(IntPtr state);
[DllImport(dllName)]
private static extern int gvr_controller_state_get_battery_level(IntPtr state);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_battery_timestamp(IntPtr state);
private const string VRCORE_UTILS_CLASS = "com.google.vr.vrcore.base.api.VrCoreUtils";
private IntPtr api;
private bool hasBatteryMethods = false;
private AndroidJavaObject androidContext;
private AndroidJavaObject classLoader;
private bool error = false;
private string errorDetails = string.Empty;
private IntPtr statePtr;
private MutablePose3D pose3d = new MutablePose3D();
private bool lastTouchState;
private bool lastButtonState;
private bool lastAppButtonState;
private bool lastHomeButtonState;
public bool SupportsBatteryStatus {
get { return hasBatteryMethods; }
}
internal AndroidNativeControllerProvider() {
#if !UNITY_EDITOR
// Debug.Log("Initializing Daydream controller API.");
int options = gvr_controller_get_default_options();
options |= GVR_CONTROLLER_ENABLE_ACCEL;
options |= GVR_CONTROLLER_ENABLE_GYRO;
statePtr = gvr_controller_state_create();
// Get a hold of the activity, context and class loader.
AndroidJavaObject activity = GvrActivityHelper.GetActivity();
if (activity == null) {
error = true;
errorDetails = "Failed to get Activity from Unity Player.";
return;
}
androidContext = GvrActivityHelper.GetApplicationContext(activity);
if (androidContext == null) {
error = true;
errorDetails = "Failed to get Android application context from Activity.";
return;
}
classLoader = GetClassLoaderFromActivity(activity);
if (classLoader == null) {
error = true;
errorDetails = "Failed to get class loader from Activity.";
return;
}
// Use IntPtr instead of GetRawObject() so that Unity can shut down gracefully on
// Application.Quit(). Note that GetRawObject() is not pinned by the receiver so it's not
// cleaned up appropriately on shutdown, which is a known bug in Unity.
IntPtr androidContextPtr = AndroidJNI.NewLocalRef(androidContext.GetRawObject());
IntPtr classLoaderPtr = AndroidJNI.NewLocalRef(classLoader.GetRawObject());
Debug.Log ("Creating and initializing GVR API controller object.");
api = gvr_controller_create_and_init_android (IntPtr.Zero, androidContextPtr, classLoaderPtr,
options, IntPtr.Zero);
AndroidJNI.DeleteLocalRef(androidContextPtr);
AndroidJNI.DeleteLocalRef(classLoaderPtr);
if (IntPtr.Zero == api) {
Debug.LogError("Error creating/initializing Daydream controller API.");
error = true;
errorDetails = "Failed to initialize Daydream controller API.";
return;
}
try {
gvr_controller_state_get_battery_charging(statePtr);
gvr_controller_state_get_battery_level(statePtr);
hasBatteryMethods = true;
} catch (EntryPointNotFoundException) {
// Older VrCore version. Does not support battery indicator.
// Note that controller API is not dynamically loaded as of June 2017 (b/35662043),
// so we'll need to support this case indefinitely...
}
// Debug.Log("GVR API successfully initialized. Now resuming it.");
gvr_controller_resume(api);
// Debug.Log("GVR API resumed.");
#endif
}
~AndroidNativeControllerProvider() {
// Debug.Log("Destroying GVR API structures.");
gvr_controller_state_destroy(ref statePtr);
gvr_controller_destroy(ref api);
// Debug.Log("AndroidNativeControllerProvider destroyed.");
}
public void ReadState(ControllerState outState) {
if (error) {
outState.connectionState = GvrConnectionState.Error;
outState.apiStatus = GvrControllerApiStatus.Error;
outState.errorDetails = errorDetails;
return;
}
gvr_controller_state_update(api, 0, statePtr);
outState.connectionState = ConvertConnectionState(
gvr_controller_state_get_connection_state(statePtr));
outState.apiStatus = ConvertControllerApiStatus(
gvr_controller_state_get_api_status(statePtr));
gvr_quat rawOri = gvr_controller_state_get_orientation(statePtr);
gvr_vec3 rawAccel = gvr_controller_state_get_accel(statePtr);
gvr_vec3 rawGyro = gvr_controller_state_get_gyro(statePtr);
// Convert GVR API orientation (right-handed) into Unity axis system (left-handed).
pose3d.Set(Vector3.zero, new Quaternion(rawOri.x, rawOri.y, rawOri.z, rawOri.w));
pose3d.SetRightHanded(pose3d.Matrix);
outState.orientation = pose3d.Orientation;
// For accelerometer, we have to flip Z because the GVR API has Z pointing backwards
// and Unity has Z pointing forward.
outState.accel = new Vector3(rawAccel.x, rawAccel.y, -rawAccel.z);
// Gyro in GVR represents a right-handed angular velocity about each axis (positive means
// clockwise when sighting along axis). Since Unity uses a left-handed system, we flip the
// signs to adjust the sign of the rotational velocity (so that positive means
// counter-clockwise). In addition, since in Unity the Z axis points forward while GVR
// has Z pointing backwards, we flip the Z axis sign again. So the result is that
// we should use -X, -Y, +Z:
outState.gyro = new Vector3(-rawGyro.x, -rawGyro.y, rawGyro.z);
outState.isTouching = 0 != gvr_controller_state_is_touching(statePtr);
gvr_vec2 touchPos = gvr_controller_state_get_touch_pos(statePtr);
outState.touchPos = new Vector2(touchPos.x, touchPos.y);
outState.appButtonState =
0 != gvr_controller_state_get_button_state(statePtr, GVR_CONTROLLER_BUTTON_APP);
outState.homeButtonState =
0 != gvr_controller_state_get_button_state(statePtr, GVR_CONTROLLER_BUTTON_HOME);
outState.clickButtonState =
0 != gvr_controller_state_get_button_state(statePtr, GVR_CONTROLLER_BUTTON_CLICK);
UpdateInputEvents(outState.isTouching, ref lastTouchState,
ref outState.touchUp, ref outState.touchDown);
UpdateInputEvents(outState.clickButtonState, ref lastButtonState,
ref outState.clickButtonUp, ref outState.clickButtonDown);
UpdateInputEvents(outState.appButtonState, ref lastAppButtonState,
ref outState.appButtonUp, ref outState.appButtonDown);
UpdateInputEvents(outState.homeButtonState, ref lastHomeButtonState,
ref outState.homeButtonUp, ref outState.homeButtonDown);
outState.recentered = 0 != gvr_controller_state_get_recentered(statePtr);
outState.gvrPtr = statePtr;
if (hasBatteryMethods) {
outState.isCharging = 0 != gvr_controller_state_get_battery_charging(statePtr);
outState.batteryLevel = (GvrControllerBatteryLevel)gvr_controller_state_get_battery_level(statePtr);
}
}
public void OnPause() {
if (IntPtr.Zero != api) {
gvr_controller_pause(api);
}
}
public void OnResume() {
if (IntPtr.Zero != api) {
gvr_controller_resume(api);
}
}
private GvrConnectionState ConvertConnectionState(int connectionState) {
switch (connectionState) {
case GVR_CONTROLLER_CONNECTED:
return GvrConnectionState.Connected;
case GVR_CONTROLLER_CONNECTING:
return GvrConnectionState.Connecting;
case GVR_CONTROLLER_SCANNING:
return GvrConnectionState.Scanning;
default:
return GvrConnectionState.Disconnected;
}
}
private GvrControllerApiStatus ConvertControllerApiStatus(int gvrControllerApiStatus) {
switch (gvrControllerApiStatus) {
case GVR_CONTROLLER_API_OK:
return GvrControllerApiStatus.Ok;
case GVR_CONTROLLER_API_UNSUPPORTED:
return GvrControllerApiStatus.Unsupported;
case GVR_CONTROLLER_API_NOT_AUTHORIZED:
return GvrControllerApiStatus.NotAuthorized;
case GVR_CONTROLLER_API_SERVICE_OBSOLETE:
return GvrControllerApiStatus.ApiServiceObsolete;
case GVR_CONTROLLER_API_CLIENT_OBSOLETE:
return GvrControllerApiStatus.ApiClientObsolete;
case GVR_CONTROLLER_API_MALFUNCTION:
return GvrControllerApiStatus.ApiMalfunction;
case GVR_CONTROLLER_API_UNAVAILABLE:
default: // Fall through.
return GvrControllerApiStatus.Unavailable;
}
}
private static void UpdateInputEvents(bool currentState, ref bool previousState, ref bool up, ref bool down) {
down = !previousState && currentState;
up = previousState && !currentState;
previousState = currentState;
}
private static AndroidJavaObject GetClassLoaderFromActivity(AndroidJavaObject activity) {
AndroidJavaObject result = activity.Call<AndroidJavaObject>("getClassLoader");
if (result == null) {
Debug.LogErrorFormat("Failed to get class loader from Activity.");
return null;
}
return result;
}
private static int GetVrCoreClientApiVersion(AndroidJavaObject activity) {
try {
AndroidJavaClass utilsClass = new AndroidJavaClass(VRCORE_UTILS_CLASS);
int apiVersion = utilsClass.CallStatic<int>("getVrCoreClientApiVersion", activity);
// Debug.LogFormat("VrCore client API version: " + apiVersion);
return apiVersion;
} catch (Exception exc) {
// Even though a catch-all block is normally frowned upon, in this case we really
// need it because this method has to be robust to unpredictable circumstances:
// VrCore might not exist in the device, the Java layer might be broken, etc, etc.
// None of those should abort the app.
Debug.LogError("Error obtaining VrCore client API version: " + exc);
return 0;
}
}
}
}
/// @endcond
#endif // UNITY_ANDROID && !UNITY_EDITOR
| |
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using System;
using System.Collections;
using System.Collections.Generic;
namespace OpenSim.Region.ScriptEngine.Interfaces
{
public enum StateSource
{
RegionStart = 0,
NewRez = 1,
PrimCrossing = 2,
ScriptedRez = 3,
AttachedRez = 4,
Teleporting = 5
}
public interface IScriptWorkItem
{
bool Cancel();
bool Abort();
/// <summary>
/// Wait for the work item to complete.
/// </summary>
/// <param name='t'>The number of milliseconds to wait. Must be >= -1 (Timeout.Infinite).</param>
bool Wait(int t);
}
/// <summary>
/// Interface for interaction with a particular script instance
/// </summary>
public interface IScriptInstance
{
/// <summary>
/// Debug level for this script instance.
/// </summary>
/// <remarks>
/// Level == 0, no extra data is logged.
/// Level >= 1, state changes are logged.
/// Level >= 2, event firing is logged.
/// <value>
/// The debug level.
/// </value>
int DebugLevel { get; set; }
/// <summary>
/// Is the script currently running?
/// </summary>
bool Running { get; set; }
/// <summary>
/// Is the script suspended?
/// </summary>
bool Suspended { get; set; }
/// <summary>
/// Is the script shutting down?
/// </summary>
bool ShuttingDown { get; set; }
/// <summary>
/// Script state
/// </summary>
string State { get; set; }
/// <summary>
/// Time the script was last started
/// </summary>
DateTime TimeStarted { get; }
/// <summary>
/// Tick the last measurement period was started.
/// </summary>
int MeasurementPeriodTickStart { get; }
/// <summary>
/// Ticks spent executing in the last measurement period.
/// </summary>
int MeasurementPeriodExecutionTime { get; }
/// <summary>
/// Scene part in which this script instance is contained.
/// </summary>
SceneObjectPart Part { get; }
IScriptEngine Engine { get; }
UUID AppDomain { get; set; }
string PrimName { get; }
string ScriptName { get; }
UUID ItemID { get; }
UUID ObjectID { get; }
/// <summary>
/// UUID of the root object for the linkset that the script is in.
/// </summary>
UUID RootObjectID { get; }
/// <summary>
/// Local id of the root object for the linkset that the script is in.
/// </summary>
uint RootLocalID { get; }
uint LocalID { get; }
UUID AssetID { get; }
/// <summary>
/// Inventory item containing the script used.
/// </summary>
TaskInventoryItem ScriptTask { get; }
void EnqueueEvent(object o);
object DequeueEvent();
/// <summary>
/// Number of events queued for processing.
/// </summary>
long EventsQueued { get; }
/// <summary>
/// Number of events processed by this script instance.
/// </summary>
long EventsProcessed { get; }
void ClearQueue();
int StartParam { get; set; }
void RemoveState();
void Init();
void Start();
/// <summary>
/// Stop the script instance.
/// </summary>
/// <remarks>
/// This must not be called by a thread that is in the process of handling an event for this script. Otherwise
/// there is a danger that it will self-abort and not complete the reset.
/// </remarks>
/// <param name="timeout"></param>
/// How many milliseconds we will wait for an existing script event to finish before
/// forcibly aborting that event.
/// <returns>true if the script was successfully stopped, false otherwise</returns>
bool Stop(int timeout);
void SetState(string state);
/// <summary>
/// Post an event to this script instance.
/// </summary>
/// <param name="data"></param>
void PostEvent(EventParams data);
void Suspend();
void Resume();
/// <summary>
/// Process the next event queued for this script instance.
/// </summary>
/// <returns></returns>
object EventProcessor();
int EventTime();
/// <summary>
/// Reset the script.
/// </summary>
/// <remarks>
/// This must not be called by a thread that is in the process of handling an event for this script. Otherwise
/// there is a danger that it will self-abort and not complete the reset. Such a thread must call
/// ApiResetScript() instead.
/// </remarks>
/// <param name='timeout'>
/// How many milliseconds we will wait for an existing script event to finish before
/// forcibly aborting that event prior to script reset.
/// </param>
void ResetScript(int timeout);
/// <summary>
/// Reset the script.
/// </summary>
/// <remarks>
/// This must not be called by any thread other than the one executing the scripts current event. This is
/// because there is no wait or abort logic if another thread is in the middle of processing a script event.
/// Such an external thread should use ResetScript() instead.
/// </remarks>
void ApiResetScript();
Dictionary<string, object> GetVars();
void SetVars(Dictionary<string, object> vars);
DetectParams GetDetectParams(int idx);
UUID GetDetectID(int idx);
void SaveState(string assembly);
void DestroyScriptInstance();
IScriptApi GetApi(string name);
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap
{ get; set; }
string GetAssemblyName();
string GetXMLState();
double MinEventDelay { set; }
UUID RegionID { get; }
}
}
| |
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
// ReSharper disable once CheckNamespace
namespace Fluent
{
using Fluent.Internal.KnownBoxes;
/// <summary>
/// Represents KeyTip control
/// </summary>
public class KeyTip : Label
{
#region Keys Attached Property
/// <summary>
/// Using a DependencyProperty as the backing store for Keys.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty KeysProperty = DependencyProperty.RegisterAttached(
"Keys",
typeof(string),
typeof(KeyTip),
new PropertyMetadata(KeysPropertyChanged)
);
private static void KeysPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
/// <summary>
/// Sets value of attached property Keys for the given element
/// </summary>
/// <param name="element">The given element</param>
/// <param name="value">Value</param>
public static void SetKeys(DependencyObject element, string value)
{
element.SetValue(KeysProperty, value);
}
/// <summary>
/// Gets value of the attached property Keys of the given element
/// </summary>
/// <param name="element">The given element</param>
[System.ComponentModel.DisplayName("Keys"),
AttachedPropertyBrowsableForChildren(IncludeDescendants = true),
System.ComponentModel.Category("KeyTips"),
System.ComponentModel.Description("Key sequence for the given element")]
public static string GetKeys(DependencyObject element)
{
return (string)element.GetValue(KeysProperty);
}
#endregion
#region AutoPlacement Attached Property
/// <summary>
/// Using a DependencyProperty as the backing store for AutoPlacement.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty AutoPlacementProperty = DependencyProperty.RegisterAttached(
"AutoPlacement",
typeof(bool),
typeof(KeyTip),
new PropertyMetadata(BooleanBoxes.TrueBox)
);
/// <summary>
/// Sets whether key tip placement is auto
/// or defined by alignment and margin properties
/// </summary>
/// <param name="element">The given element</param>
/// <param name="value">Value</param>
public static void SetAutoPlacement(DependencyObject element, bool value)
{
element.SetValue(AutoPlacementProperty, value);
}
/// <summary>
/// Gets whether key tip placement is auto
/// or defined by alignment and margin properties
/// </summary>
/// <param name="element">The given element</param>
[System.ComponentModel.DisplayName("AutoPlacement"),
AttachedPropertyBrowsableForChildren(IncludeDescendants = true),
System.ComponentModel.Category("KeyTips"),
System.ComponentModel.Description("Whether key tip placement is auto or defined by alignment and margin properties")]
public static bool GetAutoPlacement(DependencyObject element)
{
return (bool)element.GetValue(AutoPlacementProperty);
}
#endregion
#region HorizontalAlignment Attached Property
/// <summary>
/// Using a DependencyProperty as the backing store for HorizontalAlignment.
/// This enables animation, styling, binding, etc...
/// </summary>
public new static readonly DependencyProperty HorizontalAlignmentProperty = DependencyProperty.RegisterAttached(
nameof(HorizontalAlignment),
typeof(HorizontalAlignment),
typeof(KeyTip),
new PropertyMetadata(HorizontalAlignment.Center)
);
/// <summary>
/// Sets Horizontal Alignment of the key tip
/// </summary>
/// <param name="element">The given element</param>
/// <param name="value">Value</param>
public static void SetHorizontalAlignment(DependencyObject element, HorizontalAlignment value)
{
element.SetValue(HorizontalAlignmentProperty, value);
}
/// <summary>
/// Gets Horizontal alignment of the key tip
/// </summary>
/// <param name="element">The given element</param>
[System.ComponentModel.DisplayName("HorizontalAlignment"),
AttachedPropertyBrowsableForChildren(IncludeDescendants = true),
System.ComponentModel.Category("KeyTips"),
System.ComponentModel.Description("Horizontal alignment of the key tip")]
public static HorizontalAlignment GetHorizontalAlignment(DependencyObject element)
{
return (HorizontalAlignment)element.GetValue(HorizontalAlignmentProperty);
}
#endregion
#region VerticalAlignment Attached Property
/// <summary>
/// Gets vertical alignment of the key tip
/// </summary>
/// <param name="element">The given element</param>
[System.ComponentModel.DisplayName("VerticalAlignment"),
AttachedPropertyBrowsableForChildren(IncludeDescendants = true),
System.ComponentModel.Category("KeyTips"),
System.ComponentModel.Description("Vertical alignment of the key tip")]
public static VerticalAlignment GetVerticalAlignment(DependencyObject element)
{
return (VerticalAlignment)element.GetValue(VerticalAlignmentProperty);
}
/// <summary>
/// Sets vertical alignment of the key tip
/// </summary>
/// <param name="obj">The given element</param>
/// <param name="value">Value</param>
public static void SetVerticalAlignment(DependencyObject obj, VerticalAlignment value)
{
obj.SetValue(VerticalAlignmentProperty, value);
}
/// <summary>
/// Using a DependencyProperty as the backing store for VerticalAlignment.
/// This enables animation, styling, binding, etc...
/// </summary>
public new static readonly DependencyProperty VerticalAlignmentProperty =
DependencyProperty.RegisterAttached("VerticalAlignment",
typeof(VerticalAlignment), typeof(KeyTip),
new PropertyMetadata(VerticalAlignment.Center));
#endregion
#region Margin Attached Property
/// <summary>
/// Gets margin of the key tip
/// </summary>
/// <param name="obj">The key tip</param>
/// <returns>Margin</returns>
[System.ComponentModel.DisplayName("Margin"),
AttachedPropertyBrowsableForChildren(IncludeDescendants = true),
System.ComponentModel.Category("KeyTips"),
System.ComponentModel.Description("Margin of the key tip")]
public static Thickness GetMargin(DependencyObject obj)
{
return (Thickness)obj.GetValue(MarginProperty);
}
/// <summary>
/// Sets margin of the key tip
/// </summary>
/// <param name="obj">The key tip</param>
/// <param name="value">Value</param>
public static void SetMargin(DependencyObject obj, Thickness value)
{
obj.SetValue(MarginProperty, value);
}
/// <summary>
/// Using a DependencyProperty as the backing store for Margin.
/// This enables animation, styling, binding, etc...
/// </summary>
public new static readonly DependencyProperty MarginProperty =
DependencyProperty.RegisterAttached(nameof(Margin), typeof(Thickness), typeof(KeyTip), new PropertyMetadata(new Thickness()));
#endregion
[SuppressMessage("Microsoft.Performance", "CA1810")]
static KeyTip()
{
// Override metadata to allow styling
DefaultStyleKeyProperty.OverrideMetadata(typeof(KeyTip), new FrameworkPropertyMetadata(typeof(KeyTip)));
}
}
}
| |
//
// BaseTrackListView.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
using Hyena.Data;
using Hyena.Data.Gui;
using Hyena.Gui;
using Banshee.Collection.Database;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
using Banshee.Playlist;
using Banshee.Gui;
namespace Banshee.Collection.Gui
{
#if TREEVIEW
public class BaseTrackListView : SearchableTreeView<TrackInfo>
#else
public class BaseTrackListView : SearchableListView<TrackInfo>
#endif
{
public BaseTrackListView () : base ()
{
RulesHint = true;
RowOpaquePropertyName = "Enabled";
RowBoldPropertyName = "IsPlaying";
ServiceManager.PlayerEngine.ConnectEvent (
OnPlayerEvent, PlayerEvent.StartOfStream | PlayerEvent.StateChange);
ForceDragSourceSet = true;
IsEverReorderable = true;
RowActivated += (o, a) => {
var source = ServiceManager.SourceManager.ActiveSource as ITrackModelSource;
if (source != null && source.TrackModel == Model) {
var ias = ServiceManager.Get<InterfaceActionService> ();
var action = ias.TrackActions ["PlayTrack"];
action.Activate ();
}
};
DragFailed += (o, a) => {
int x, y;
GetPointer (out x, out y);
bool inside_list = (x >= 0 && y >= 0) && (x < Allocation.Width && y < Allocation.Height);
if (inside_list && a.Result == DragResult.NoTarget) {
PlaylistSource playlist = ServiceManager.SourceManager.ActiveSource as PlaylistSource;
if (playlist != null && !IsReorderable) {
Hyena.Log.Information (
Catalog.GetString ("Cannot Reorder While Sorted"),
Catalog.GetString ("To put the playlist in manual sort mode, click the currently sorted column header until the sort arrow goes away."),
true
);
}
}
};
}
protected BaseTrackListView (IntPtr raw) : base (raw)
{
}
public override bool SelectOnRowFound {
get { return true; }
}
private static TargetEntry [] source_targets = new TargetEntry [] {
ListViewDragDropTarget.ModelSelection,
Banshee.Gui.DragDrop.DragDropTarget.UriList
};
protected override TargetEntry [] DragDropSourceEntries {
get { return source_targets; }
}
protected override bool OnKeyPressEvent (Gdk.EventKey press)
{
// Have o act the same as enter - activate the selection
if (GtkUtilities.NoImportantModifiersAreSet () && press.Key == Gdk.Key.o && ActivateSelection ()) {
return true;
}
return base.OnKeyPressEvent (press);
}
protected override bool OnPopupMenu ()
{
ServiceManager.Get<InterfaceActionService> ().TrackActions["TrackContextMenuAction"].Activate ();
return true;
}
private string user_query;
protected override void OnModelReloaded ()
{
base.OnModelReloaded ();
var model = Model as IFilterable;
if (model != null && user_query != model.UserQuery) {
// Make sure selected tracks are visible as the user edits the query.
CenterOnSelection ();
user_query = model.UserQuery;
}
}
private void OnPlayerEvent (PlayerEventArgs args)
{
if (args.Event == PlayerEvent.StartOfStream) {
UpdateSelection ();
} else if (args.Event == PlayerEvent.StateChange) {
QueueDraw ();
}
}
private TrackInfo current_track;
private void UpdateSelection ()
{
TrackInfo old_track = current_track;
current_track = ServiceManager.PlayerEngine.CurrentTrack;
var track_model = Model as TrackListModel;
if (track_model == null) {
return;
}
if (Selection.Count > 1) {
return;
}
int old_index = Selection.FirstIndex;
TrackInfo selected_track = Selection.Count == 1 ? track_model[old_index] : null;
if (selected_track != null && !selected_track.TrackEqual (old_track)) {
return;
}
int current_index = track_model.IndexOf (current_track);
if (current_index == -1) {
return;
}
Selection.Clear (false);
Selection.QuietSelect (current_index);
Selection.FocusedIndex = current_index;
if (old_index == -1 || IsRowVisible (old_index)) {
CenterOn (current_index);
}
}
#region Drag and Drop
protected override void OnDragSourceSet ()
{
base.OnDragSourceSet ();
Drag.SourceSetIconName (this, "audio-x-generic");
}
protected override bool OnDragDrop (Gdk.DragContext context, int x, int y, uint time_)
{
y = TranslateToListY (y);
if (Gtk.Drag.GetSourceWidget (context) == this) {
PlaylistSource playlist = ServiceManager.SourceManager.ActiveSource as PlaylistSource;
if (playlist != null) {
//Gtk.Drag.
int row = GetModelRowAt (0, y);
if (row != GetModelRowAt (0, y + ChildSize.Height / 2)) {
row += 1;
}
if (playlist.TrackModel.Selection.Contains (row)) {
// can't drop within the selection
return false;
}
playlist.ReorderSelectedTracks (row);
return true;
}
}
return false;
}
protected override void OnDragDataGet (Gdk.DragContext context, SelectionData selection_data, uint info, uint time)
{
if (info == Banshee.Gui.DragDrop.DragDropTarget.UriList.Info) {
ITrackModelSource track_source = ServiceManager.SourceManager.ActiveSource as ITrackModelSource;
if (track_source != null) {
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
foreach (TrackInfo track in track_source.TrackModel.SelectedItems) {
sb.Append (track.Uri);
sb.Append ("\r\n");
}
byte [] data = System.Text.Encoding.UTF8.GetBytes (sb.ToString ());
selection_data.Set (context.ListTargets ()[0], 8, data, data.Length);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NSubstitute;
using NuGet.Packaging.Core;
using NuGet.Versioning;
using NuKeeper.Abstractions.Logging;
using NuKeeper.Inspection.Sort;
using NuKeeper.Inspection.RepositoryInspection;
using NUnit.Framework;
using NuKeeper.Abstractions.RepositoryInspection;
namespace NuKeeper.Tests.Engine.Sort
{
[TestFixture]
public class PackageUpdateSortDependencyTests
{
private static readonly DateTimeOffset StandardPublishedDate = new DateTimeOffset(2018, 2, 19, 11, 12, 7, TimeSpan.Zero);
[Test]
public void WillSortByProjectCountWhenThereAreNoDeps()
{
var upstream = OnePackageUpdateSet("upstream", 1, null);
var downstream = OnePackageUpdateSet("downstream", 2, null);
var items = new List<PackageUpdateSet>
{
downstream,
upstream
};
var output = Sort(items);
Assert.That(output.Count, Is.EqualTo(2));
Assert.That(output[0].SelectedId, Is.EqualTo("downstream"));
Assert.That(output[1].SelectedId, Is.EqualTo("upstream"));
}
[Test]
public void WillSortByDependencyWhenItExists()
{
var upstream = OnePackageUpdateSet("upstream", 1, null);
var depOnUpstream = new List<PackageDependency>
{
new PackageDependency("upstream", VersionRange.All)
};
var downstream = OnePackageUpdateSet("downstream", 2, depOnUpstream);
var items = new List<PackageUpdateSet>
{
downstream,
upstream
};
var output = Sort(items);
Assert.That(output.Count, Is.EqualTo(2));
Assert.That(output[0].SelectedId, Is.EqualTo("upstream"));
Assert.That(output[1].SelectedId, Is.EqualTo("downstream"));
}
[Test]
public void WillSortSecondAndThirdByDependencyWhenItExists()
{
var upstream = OnePackageUpdateSet("upstream", 1, null);
var depOnUpstream = new List<PackageDependency>
{
new PackageDependency("upstream", VersionRange.All)
};
var downstream = OnePackageUpdateSet("downstream", 2, depOnUpstream);
var items = new List<PackageUpdateSet>
{
OnePackageUpdateSet("nodeps", 3, null),
downstream,
upstream
};
var output = Sort(items);
Assert.That(output.Count, Is.EqualTo(3));
Assert.That(output[0].SelectedId, Is.EqualTo("nodeps"));
Assert.That(output[1].SelectedId, Is.EqualTo("upstream"));
Assert.That(output[2].SelectedId, Is.EqualTo("downstream"));
}
[Test]
public void SortWithThreeLevels()
{
var level1 = OnePackageUpdateSet("l1", 1, null);
var depOnLevel1 = new List<PackageDependency>
{
new PackageDependency("l1", VersionRange.All)
};
var level2 = OnePackageUpdateSet("l2", 2, depOnLevel1);
var depOnLevel2 = new List<PackageDependency>
{
new PackageDependency("l2", VersionRange.All)
};
var level3 = OnePackageUpdateSet("l3", 2, depOnLevel2);
var items = new List<PackageUpdateSet>
{
level3,
level2,
level1
};
var output = Sort(items);
Assert.That(output.Count, Is.EqualTo(3));
Assert.That(output[0].SelectedId, Is.EqualTo("l1"));
Assert.That(output[1].SelectedId, Is.EqualTo("l2"));
Assert.That(output[2].SelectedId, Is.EqualTo("l3"));
}
[Test]
public void SortWhenTwoPackagesDependOnSameUpstream()
{
var level1 = OnePackageUpdateSet("l1", 1, null);
var depOnLevel1 = new List<PackageDependency>
{
new PackageDependency("l1", VersionRange.All)
};
var level2A = OnePackageUpdateSet("l2a", 2, depOnLevel1);
var level2B = OnePackageUpdateSet("l2b", 2, depOnLevel1);
var items = new List<PackageUpdateSet>
{
level2A,
level2B,
level1
};
var output = Sort(items);
Assert.That(output.Count, Is.EqualTo(3));
Assert.That(output[0].SelectedId, Is.EqualTo("l1"));
// prior ordering should be preserved here
Assert.That(output[1].SelectedId, Is.EqualTo("l2a"));
Assert.That(output[2].SelectedId, Is.EqualTo("l2b"));
}
[Test]
public void SortWhenDependenciesAreCircular()
{
var depOnA = new List<PackageDependency>
{
new PackageDependency("PackageA", VersionRange.All)
};
var depOnB = new List<PackageDependency>
{
new PackageDependency("PackageB", VersionRange.All)
};
// circular dependencies should not happen, but probably will
// do not break
var packageA = OnePackageUpdateSet("PackageA", 1, depOnB);
var packageB = OnePackageUpdateSet("PackageB", 1, depOnA);
var items = new List<PackageUpdateSet>
{
packageA,
packageB
};
var output = Sort(items);
Assert.That(output.Count, Is.EqualTo(2));
Assert.That(output[0].SelectedId, Is.EqualTo("PackageA"));
Assert.That(output[1].SelectedId, Is.EqualTo("PackageB"));
}
private static PackageUpdateSet OnePackageUpdateSet(string packageName, int projectCount,
List<PackageDependency> deps)
{
var newPackage = new PackageIdentity(packageName, new NuGetVersion("1.4.5"));
var package = new PackageIdentity(packageName, new NuGetVersion("1.2.3"));
var projects = new List<PackageInProject>();
foreach (var i in Enumerable.Range(1, projectCount))
{
projects.Add(MakePackageInProjectFor(package));
}
return PackageUpdates.For(newPackage, StandardPublishedDate, projects, deps);
}
private static PackageInProject MakePackageInProjectFor(PackageIdentity package)
{
var path = new PackagePath(
Path.GetTempPath(),
Path.Combine("folder", "src", "project1", "packages.config"),
PackageReferenceType.PackagesConfig);
return new PackageInProject(package.Id, package.Version.ToString(), path);
}
private static List<PackageUpdateSet> Sort(IReadOnlyCollection<PackageUpdateSet> input)
{
var sorter = new PackageUpdateSetSort(Substitute.For<INuKeeperLogger>());
return sorter.Sort(input)
.ToList();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.UserControl.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI
{
public partial class UserControl : TemplateControl, IAttributeAccessor, INamingContainer, IUserControlDesignerAccessor
{
#region Methods and constructors
public void DesignerInitialize ()
{
}
public void InitializeAsUserControl (Page page)
{
}
protected override void LoadViewState (Object savedState)
{
}
public string MapPath (string virtualPath)
{
return default(string);
}
protected internal override void OnInit (EventArgs e)
{
}
protected override Object SaveViewState ()
{
return default(Object);
}
string System.Web.UI.IAttributeAccessor.GetAttribute (string name)
{
return default(string);
}
void System.Web.UI.IAttributeAccessor.SetAttribute (string name, string value)
{
}
public UserControl ()
{
}
#endregion
#region Properties and indexers
public System.Web.HttpApplicationState Application
{
get
{
Contract.Ensures (Contract.Result<System.Web.HttpApplicationState>() == this.Page.Application);
return default(System.Web.HttpApplicationState);
}
}
public AttributeCollection Attributes
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.AttributeCollection>() != null);
return default(AttributeCollection);
}
}
public System.Web.Caching.Cache Cache
{
get
{
Contract.Requires (this.Page != null);
Contract.Ensures (Contract.Result<System.Web.Caching.Cache>() != null);
Contract.Ensures (this.Page.Cache != null);
Contract.Ensures (Contract.Result<System.Web.Caching.Cache>() == this.Page.Cache);
return default(System.Web.Caching.Cache);
}
}
public ControlCachePolicy CachePolicy
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.ControlCachePolicy>() != null);
return default(ControlCachePolicy);
}
}
public bool IsPostBack
{
get
{
Contract.Requires (this.Page != null);
Contract.Ensures (Contract.Result<bool>() == this.Page.IsPostBack);
return default(bool);
}
}
public System.Web.HttpRequest Request
{
get
{
Contract.Requires (this.Page != null);
Contract.Ensures (Contract.Result<System.Web.HttpRequest>() != null);
Contract.Ensures (this.Page.Request != null);
Contract.Ensures (Contract.Result<System.Web.HttpRequest>() == this.Page.Request);
return default(System.Web.HttpRequest);
}
}
public System.Web.HttpResponse Response
{
get
{
Contract.Requires (this.Page != null);
Contract.Ensures (Contract.Result<System.Web.HttpResponse>() != null);
Contract.Ensures (this.Page.Response != null);
Contract.Ensures (Contract.Result<System.Web.HttpResponse>() == this.Page.Response);
return default(System.Web.HttpResponse);
}
}
public System.Web.HttpServerUtility Server
{
get
{
Contract.Requires (this.Page != null);
Contract.Ensures (Contract.Result<System.Web.HttpServerUtility>() == this.Page.Server);
return default(System.Web.HttpServerUtility);
}
}
public System.Web.SessionState.HttpSessionState Session
{
get
{
Contract.Requires (this.Page != null);
Contract.Ensures (Contract.Result<System.Web.SessionState.HttpSessionState>() == this.Page.Session);
return default(System.Web.SessionState.HttpSessionState);
}
}
string System.Web.UI.IUserControlDesignerAccessor.InnerText
{
get
{
return default(string);
}
set
{
}
}
string System.Web.UI.IUserControlDesignerAccessor.TagName
{
get
{
return default(string);
}
set
{
}
}
public System.Web.TraceContext Trace
{
get
{
Contract.Requires (this.Page != null);
Contract.Ensures (Contract.Result<System.Web.TraceContext>() == this.Page.Trace);
return default(System.Web.TraceContext);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public static class ConnectivityParametersTest
{
private const string COL_PROGRAM_NAME = "ProgramName";
private const string COL_HOSTNAME = "HostName";
private static readonly string s_databaseName = "d_" + Guid.NewGuid().ToString().Replace('-', '_');
private static readonly string s_tableName = "Person";
private static readonly string s_connectionString = DataTestUtility.TcpConnStr;
private static readonly string s_dbConnectionString = new SqlConnectionStringBuilder(s_connectionString) { InitialCatalog = s_databaseName }.ConnectionString;
private static readonly string s_createDatabaseCmd = $"CREATE DATABASE {s_databaseName}";
private static readonly string s_createTableCmd = $"CREATE TABLE {s_tableName} (NAME NVARCHAR(40), AGE INT)";
private static readonly string s_alterDatabaseSingleCmd = $"ALTER DATABASE {s_databaseName} SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
private static readonly string s_alterDatabaseMultiCmd = $"ALTER DATABASE {s_databaseName} SET MULTI_USER WITH ROLLBACK IMMEDIATE;";
private static readonly string s_selectTableCmd = $"SELECT COUNT(*) FROM {s_tableName}";
private static readonly string s_dropDatabaseCmd = $"DROP DATABASE {s_databaseName}";
[CheckConnStrSetupFact]
public static void EnvironmentHostNameTest()
{
SqlConnectionStringBuilder builder = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { Pooling = true });
builder.ApplicationName = "HostNameTest";
using (SqlConnection sqlConnection = new SqlConnection(builder.ConnectionString))
{
sqlConnection.Open();
using (SqlCommand command = new SqlCommand("sp_who2", sqlConnection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int programNameOrdinal = reader.GetOrdinal(COL_PROGRAM_NAME);
string programName = reader.GetString(programNameOrdinal);
if (programName != null && programName.Trim().Equals(builder.ApplicationName))
{
// Get the hostname
int hostnameOrdinal = reader.GetOrdinal(COL_HOSTNAME);
string hostnameFromServer = reader.GetString(hostnameOrdinal);
string expectedMachineName = Environment.MachineName.ToUpper();
string hostNameFromServer = hostnameFromServer.Trim().ToUpper();
Assert.Matches(expectedMachineName, hostNameFromServer);
return;
}
}
}
}
}
Assert.True(false, "No non-empty hostname found for the application");
}
[CheckConnStrSetupFact]
public static void ConnectionTimeoutTestWithThread()
{
const int timeoutSec = 5;
const int numOfTry = 2;
const int numOfThreads = 5;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
builder.DataSource = "invalidhost";
builder.ConnectTimeout = timeoutSec;
string connStrNotAvailable = builder.ConnectionString;
for (int i = 0; i < numOfThreads; ++i)
{
new ConnectionWorker(connStrNotAvailable, numOfTry);
}
ConnectionWorker.Start();
ConnectionWorker.Stop();
double timeTotal = 0;
double timeElapsed = 0;
foreach (ConnectionWorker w in ConnectionWorker.WorkerList)
{
timeTotal += w.TimeElapsed;
}
timeElapsed = timeTotal / Convert.ToDouble(ConnectionWorker.WorkerList.Count);
int threshold = timeoutSec * numOfTry * 2 * 1000;
Assert.True(timeElapsed < threshold);
}
[CheckConnStrSetupFact]
public static void ProcessIdTest()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
string sqlProviderName = builder.ApplicationName;
string sqlProviderProcessID = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
using (SqlConnection sqlConnection = new SqlConnection(builder.ConnectionString))
{
sqlConnection.Open();
string strCommand = $"SELECT PROGRAM_NAME,HOSTPROCESS FROM SYS.SYSPROCESSES WHERE PROGRAM_NAME LIKE ('%{sqlProviderName}%')";
using (SqlCommand command = new SqlCommand(strCommand, sqlConnection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Assert.Equal(sqlProviderName,reader.GetString(0).Trim());
Assert.Equal(sqlProviderProcessID, reader.GetString(1).Trim());
}
}
}
}
}
public class ConnectionWorker
{
private static List<ConnectionWorker> workerList = new List<ConnectionWorker>();
private ManualResetEventSlim _doneEvent = new ManualResetEventSlim(false);
private double _timeElapsed;
private Thread _thread;
private string _connectionString;
private int _numOfTry;
public ConnectionWorker(string connectionString, int numOfTry)
{
workerList.Add(this);
_connectionString = connectionString;
_numOfTry = numOfTry;
_thread = new Thread(new ThreadStart(SqlConnectionOpen));
}
public static List<ConnectionWorker> WorkerList => workerList;
public double TimeElapsed => _timeElapsed;
public static void Start()
{
foreach (ConnectionWorker w in workerList)
{
w._thread.Start();
}
}
public static void Stop()
{
foreach (ConnectionWorker w in workerList)
{
w._doneEvent.Wait();
}
}
public void SqlConnectionOpen()
{
Stopwatch sw = new Stopwatch();
double totalTime = 0;
for (int i = 0; i < _numOfTry; ++i)
{
using (SqlConnection con = new SqlConnection(_connectionString))
{
sw.Start();
try
{
con.Open();
}
catch { }
sw.Stop();
}
totalTime += sw.Elapsed.TotalMilliseconds;
sw.Reset();
}
_timeElapsed = totalTime / Convert.ToDouble(_numOfTry);
_doneEvent.Set();
}
}
[CheckConnStrSetupFact]
public static void ConnectionKilledTest()
{
try
{
// Setup Database and Table.
DataTestUtility.RunNonQuery(s_connectionString, s_createDatabaseCmd);
DataTestUtility.RunNonQuery(s_dbConnectionString, s_createTableCmd);
// Kill all the connections and set Database to SINGLE_USER Mode.
DataTestUtility.RunNonQuery(s_connectionString, s_alterDatabaseSingleCmd);
// Set Database back to MULTI_USER Mode
DataTestUtility.RunNonQuery(s_connectionString, s_alterDatabaseMultiCmd);
// Execute SELECT statement.
DataTestUtility.RunNonQuery(s_dbConnectionString, s_selectTableCmd);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Assert.Null(ex);
}
finally
{
// Kill all the connections, set Database to SINGLE_USER Mode and drop Database
DataTestUtility.RunNonQuery(s_connectionString, s_alterDatabaseSingleCmd);
DataTestUtility.RunNonQuery(s_connectionString, s_dropDatabaseCmd);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.Spellcheck;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.SpellCheck
{
public class SpellCheckTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new CSharpSpellCheckCodeFixProvider());
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> FlattenActions(actions);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestNoSpellcheckForIfOnly2Characters()
{
var text =
@"class Foo
{
void Bar()
{
var a = new [|Fo|]
}
}";
await TestMissingInRegularAndScriptAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestAfterNewExpression()
{
var text =
@"class Foo
{
void Bar()
{
void a = new [|Fooa|].ToString();
}
}";
await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Fooa", "Foo") });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestInLocalType()
{
var text = @"class Foo
{
void Bar()
{
[|Foa|] a;
}
}";
await TestExactActionSetOfferedAsync(text, new[]
{
String.Format(FeaturesResources.Change_0_to_1, "Foa", "Foo"),
String.Format(FeaturesResources.Change_0_to_1, "Foa", "for")
});
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestInFunc()
{
var text = @"
using System;
class Foo
{
void Bar(Func<[|Foa|]> f)
{
}
}";
await TestExactActionSetOfferedAsync(text,
new[] { String.Format(FeaturesResources.Change_0_to_1, "Foa", "Foo") });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestInExpression()
{
var text = @"class Program
{
void Main(string[] args)
{
var zzz = 2;
var y = 2 + [|zza|];
}
}";
await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "zza", "zzz") });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestInTypeOfIsExpression()
{
var text = @"using System;
public class Class1
{
void F()
{
if (x is [|Boolea|]) {}
}
}";
await TestExactActionSetOfferedAsync(text, new[]
{
String.Format(FeaturesResources.Change_0_to_1, "Boolea", "Boolean"),
String.Format(FeaturesResources.Change_0_to_1, "Boolea", "bool")
});
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestInvokeCorrectIdentifier()
{
var text = @"class Program
{
void Main(string[] args)
{
var zzz = 2;
var y = 2 + [|zza|];
}
}";
var expected = @"class Program
{
void Main(string[] args)
{
var zzz = 2;
var y = 2 + zzz;
}
}";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestAfterDot()
{
var text = @"class Program
{
static void Main(string[] args)
{
Program.[|Mair|]
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
Program.Main
}
}";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestNotInaccessibleProperty()
{
var text = @"class Program
{
void Main(string[] args)
{
var z = new c().[|membr|]
}
}
class c
{
protected int member { get; }
}";
await TestMissingInRegularAndScriptAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestGenericName1()
{
var text = @"class Foo<T>
{
private [|Foo2|]<T> x;
}";
var expected = @"class Foo<T>
{
private Foo<T> x;
}";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestGenericName2()
{
var text = @"class Foo<T>
{
private [|Foo2|] x;
}";
var expected = @"class Foo<T>
{
private Foo x;
}";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestQualifiedName1()
{
var text = @"class Program
{
private object x = new [|Foo2|].Bar
}
class Foo
{
class Bar
{
}
}";
var expected = @"class Program
{
private object x = new Foo.Bar
}
class Foo
{
class Bar
{
}
}";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestQualifiedName2()
{
var text = @"class Program
{
private object x = new Foo.[|Ba2|]
}
class Foo
{
public class Bar
{
}
}";
var expected = @"class Program
{
private object x = new Foo.Bar
}
class Foo
{
public class Bar
{
}
}";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestMiddleOfDottedExpression()
{
var text = @"class Program
{
void Main(string[] args)
{
var z = new c().[|membr|].ToString();
}
}
class c
{
public int member { get; }
}";
var expected = @"class Program
{
void Main(string[] args)
{
var z = new c().member.ToString();
}
}
class c
{
public int member { get; }
}";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestNotForOverloadResolutionFailure()
{
var text = @"class Program
{
void Main(string[] args)
{
}
void Foo()
{
[|Method|]();
}
int Method(int argument)
{
}
}";
await TestMissingInRegularAndScriptAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestHandlePredefinedTypeKeywordCorrectly()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Main(string[] args)
{
[|Int3|] i;
}
}";
var expected = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Main(string[] args)
{
int i;
}
}";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestHandlePredefinedTypeKeywordCorrectly1()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Main(string[] args)
{
[|Int3|] i;
}
}";
var expected = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Main(string[] args)
{
Int32 i;
}
}";
await TestInRegularAndScriptAsync(text, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestOnGeneric()
{
var text = @"
interface Enumerable<T>
{
}
class C
{
void Main(string[] args)
{
[|IEnumerable|]<int> x;
}
}";
var expected = @"
interface Enumerable<T>
{
}
class C
{
void Main(string[] args)
{
Enumerable<int> x;
}
}";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestTestObjectConstruction()
{
await TestInRegularAndScriptAsync(
@"class AwesomeClass
{
void M()
{
var foo = new [|AwesomeClas()|];
}
}",
@"class AwesomeClass
{
void M()
{
var foo = new AwesomeClass();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
public async Task TestTestMissingName()
{
await TestMissingInRegularAndScriptAsync(
@"[assembly: Microsoft.CodeAnalysis.[||]]");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
[WorkItem(12990, "https://github.com/dotnet/roslyn/issues/12990")]
public async Task TestTrivia1()
{
var text = @"
using System.Text;
class C
{
void M()
{
/*leading*/ [|stringbuilder|] /*trailing*/ sb = null;
}
}";
var expected = @"
using System.Text;
class C
{
void M()
{
/*leading*/ StringBuilder /*trailing*/ sb = null;
}
}";
await TestInRegularAndScriptAsync(text, expected, ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
[WorkItem(13345, "https://github.com/dotnet/roslyn/issues/13345")]
public async Task TestNotMissingOnKeywordWhichIsAlsoASnippet()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
// here 'for' is a keyword and snippet, so we should offer to spell check to it.
[|foo|];
}
}",
@"class C
{
void M()
{
// here 'for' is a keyword and snippet, so we should offer to spell check to it.
for;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
[WorkItem(13345, "https://github.com/dotnet/roslyn/issues/13345")]
public async Task TestMissingOnKeywordWhichIsOnlyASnippet()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
// here 'for' is *only* a snippet, and we should not offer to spell check to it.
var v = [|foo|];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)]
[WorkItem(15733, "https://github.com/dotnet/roslyn/issues/15733")]
public async Task TestMissingOnVar()
{
await TestMissingInRegularAndScriptAsync(
@"
namespace bar { }
class C
{
void M()
{
var y =
[|var|]
}
}");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ServiceStack.Text;
using ServiceStack.VirtualPath;
namespace ServiceStack.IO
{
public partial class GistVirtualFiles : AbstractVirtualPathProviderBase, IVirtualFiles
{
public IGistGateway Gateway { get; }
public string GistId { get; private set; }
private readonly GistVirtualDirectory rootDirectory;
public GistVirtualFiles(string gistId) : this(gistId, new GitHubGateway()) { }
public GistVirtualFiles(string gistId, string accessToken) : this(gistId, new GitHubGateway(accessToken)) { }
public GistVirtualFiles(string gistId, IGistGateway gateway)
{
this.Gateway = gateway;
this.GistId = gistId;
this.rootDirectory = new GistVirtualDirectory(this, null, null);
}
public GistVirtualFiles(Gist gist) : this(gist.Id) => InitGist(gist);
public GistVirtualFiles(Gist gist, string accessToken) : this(gist.Id, accessToken) => InitGist(gist);
public GistVirtualFiles(Gist gist, IGistGateway gateway) : this(gist.Id, gateway) => InitGist(gist);
private void InitGist(Gist gist)
{
gistCache = gist;
LastRefresh = gist.Updated_At.GetValueOrDefault(DateTime.UtcNow);
}
public DateTime LastRefresh { get; private set; }
public TimeSpan RefreshAfter { get; set; } = TimeSpan.MaxValue;
public const char DirSep = '\\';
public override IVirtualDirectory RootDirectory => rootDirectory;
public override string VirtualPathSeparator => "/";
public override string RealPathSeparator => "\\";
protected override void Initialize() { }
public static bool IsDirSep(char c) => c == '\\' || c == '/';
public const string Base64Modifier = "|base64";
private static byte[] FromBase64String(string path, string base64String)
{
try
{
if (string.IsNullOrEmpty(base64String))
return TypeConstants.EmptyByteArray;
return Convert.FromBase64String(base64String);
}
catch (Exception ex)
{
throw new Exception(
$"Could not convert Base 64 contents of '{path}', length: {base64String.Length}, starting with: {base64String.SafeSubstring(50)}",
ex);
}
}
public static bool GetGistTextContents(string filePath, Gist gist, out string text)
{
if (GetGistContents(filePath, gist, out text, out var bytesContent))
{
if (text == null)
text = MemoryProvider.Instance.FromUtf8(bytesContent.GetBufferAsMemory().Span).ToString();
return true;
}
return false;
}
public static bool GetGistContents(string filePath, Gist gist, out string text, out MemoryStream stream)
{
var base64FilePath = filePath + Base64Modifier;
foreach (var entry in gist.Files)
{
var file = entry.Value;
var isMatch = entry.Key == filePath || entry.Key == base64FilePath;
if (!isMatch)
continue;
// GitHub can truncate Gist and return partial content
if ((string.IsNullOrEmpty(file.Content) || file.Content.Length < file.Size) && file.Truncated)
{
file.Content = file.Raw_Url.GetStringFromUrl(
requestFilter: req => req.UserAgent = nameof(GitHubGateway));
}
text = file.Content;
if (entry.Key == filePath)
{
if (filePath.EndsWith(Base64Modifier))
{
stream = MemoryStreamFactory.GetStream(FromBase64String(entry.Key, text));
text = null;
}
else
{
var bytesMemory = MemoryProvider.Instance.ToUtf8(text.AsSpan());
stream = MemoryProvider.Instance.ToMemoryStream(bytesMemory.Span);
}
return true;
}
if (entry.Key == base64FilePath)
{
stream = MemoryStreamFactory.GetStream(FromBase64String(entry.Key, text));
text = null;
return true;
}
}
text = null;
stream = null;
return false;
}
private Gist gistCache;
public Gist GetGist(bool refresh = false)
{
if (gistCache != null && !refresh)
return gistCache;
LastRefresh = DateTime.UtcNow;
return gistCache = Gateway.GetGist(GistId);
}
public async Task<Gist> GetGistAsync(bool refresh = false)
{
if (gistCache != null && !refresh)
return gistCache;
LastRefresh = DateTime.UtcNow;
return gistCache = await Gateway.GetGistAsync(GistId);
}
public async Task LoadAllTruncatedFilesAsync()
{
var gist = await GetGistAsync();
var files = gist.Files.Where(x =>
(string.IsNullOrEmpty(x.Value.Content) || x.Value.Content.Length < x.Value.Size) && x.Value.Truncated);
var tasks = files.Select(async x => {
x.Value.Content = await x.Value.Raw_Url.GetStringFromUrlAsync();
});
await Task.WhenAll(tasks);
}
public void ClearGist() => gistCache = null;
public override IVirtualFile GetFile(string virtualPath)
{
if (string.IsNullOrEmpty(virtualPath))
return null;
var filePath = SanitizePath(virtualPath);
var gist = GetGist();
if (!GetGistContents(filePath, gist, out var text, out var stream))
return null;
var dirPath = GetDirPath(filePath);
return new GistVirtualFile(this, new GistVirtualDirectory(this, dirPath, GetParentDirectory(dirPath)))
.Init(filePath, gist.Updated_At ?? gist.Created_at, text, stream);
}
private GistVirtualDirectory GetParentDirectory(string dirPath)
{
if (string.IsNullOrEmpty(dirPath))
return null;
var parentDir = GetDirPath(dirPath.TrimEnd(DirSep));
return parentDir != null
? new GistVirtualDirectory(this, parentDir, GetParentDirectory(parentDir))
: (GistVirtualDirectory) RootDirectory;
}
public override IVirtualDirectory GetDirectory(string virtualPath)
{
if (virtualPath == null)
return null;
var dirPath = SanitizePath(virtualPath);
if (string.IsNullOrEmpty(dirPath))
return RootDirectory;
var seekPath = dirPath[dirPath.Length - 1] != DirSep
? dirPath + DirSep
: dirPath;
var gist = GetGist();
foreach (var entry in gist.Files)
{
if (entry.Key.StartsWith(seekPath))
return new GistVirtualDirectory(this, dirPath, GetParentDirectory(dirPath));
}
return null;
}
public override bool DirectoryExists(string virtualPath)
{
return GetDirectory(virtualPath) != null;
}
public override bool FileExists(string virtualPath)
{
return GetFile(virtualPath) != null;
}
public override void WriteFiles(Dictionary<string, string> textFiles)
{
var gistFiles = new Dictionary<string, string>();
foreach (var entry in textFiles)
{
var filePath = SanitizePath(entry.Key);
gistFiles[filePath] = entry.Value;
}
Gateway.WriteGistFiles(GistId, gistFiles);
ClearGist();
}
public override void WriteFiles(Dictionary<string, object> files)
{
Gateway.WriteGistFiles(GistId, files);
ClearGist();
}
public void WriteFile(string virtualPath, string contents)
{
var filePath = SanitizePath(virtualPath);
Gateway.WriteGistFile(GistId, filePath, contents);
ClearGist();
}
public void WriteFile(string virtualPath, Stream stream)
{
var base64 = ToBase64(stream);
var filePath = SanitizePath(virtualPath) + Base64Modifier;
Gateway.WriteGistFile(GistId, filePath, base64);
ClearGist();
}
public static string ToBase64(Stream stream)
{
var base64 = stream is MemoryStream ms
? Convert.ToBase64String(ms.GetBuffer(), 0, (int) ms.Length)
: Convert.ToBase64String(stream.ReadFully());
return base64;
}
public static string ToBase64(byte[] bytes) => Convert.ToBase64String(bytes);
public void WriteFiles(IEnumerable<IVirtualFile> files, Func<IVirtualFile, string> toPath = null)
{
this.CopyFrom(files, toPath);
ClearGist();
}
public void AppendFile(string filePath, string textContents)
{
throw new NotImplementedException("Gists doesn't support appending to files");
}
public void AppendFile(string filePath, Stream stream)
{
throw new NotImplementedException("Gists doesn't support appending to files");
}
public string ResolveGistFileName(string filePath)
{
var gist = GetGist();
var baseFilePath = filePath + Base64Modifier;
foreach (var entry in gist.Files)
{
if (entry.Key == filePath || entry.Key == baseFilePath)
return entry.Key;
}
return null;
}
public void DeleteFile(string filePath)
{
filePath = SanitizePath(filePath);
filePath = ResolveGistFileName(filePath) ?? filePath;
Gateway.DeleteGistFiles(GistId, filePath);
ClearGist();
}
public void DeleteFiles(IEnumerable<string> virtualFilePaths)
{
var filePaths = virtualFilePaths.Map(x => {
var filePath = SanitizePath(x);
return ResolveGistFileName(filePath) ?? filePath;
});
Gateway.DeleteGistFiles(GistId, filePaths.ToArray());
ClearGist();
}
public void DeleteFolder(string dirPath)
{
dirPath = SanitizePath(dirPath);
var nestedFiles = EnumerateFiles(dirPath).Map(x => x.FilePath);
DeleteFiles(nestedFiles);
}
public IEnumerable<GistVirtualFile> EnumerateFiles(string prefix = null)
{
var gist = GetGist();
foreach (var entry in gist.Files)
{
if (!GetGistContents(entry.Key, gist, out var text, out var stream))
continue;
var filePath = SanitizePath(entry.Key);
var dirPath = GetDirPath(filePath);
if (prefix != null && (dirPath == null || !dirPath.StartsWith(prefix)))
continue;
yield return new GistVirtualFile(this,
new GistVirtualDirectory(this, dirPath, GetParentDirectory(dirPath)))
.Init(filePath, gist.Updated_At ?? gist.Created_at, text, stream);
}
}
public override IEnumerable<IVirtualFile> GetAllFiles()
{
return EnumerateFiles();
}
public IEnumerable<GistVirtualDirectory> GetImmediateDirectories(string fromDirPath)
{
var dirPaths = EnumerateFiles(fromDirPath)
.Map(x => x.DirPath)
.Distinct()
.Map(x => GetImmediateSubDirPath(fromDirPath, x))
.Where(x => x != null)
.Distinct();
var parentDir = GetParentDirectory(fromDirPath);
return dirPaths.Map(x => new GistVirtualDirectory(this, x, parentDir));
}
public IEnumerable<GistVirtualFile> GetImmediateFiles(string fromDirPath)
{
return EnumerateFiles(fromDirPath)
.Where(x => x.DirPath == fromDirPath);
}
public string GetDirPath(string filePath)
{
if (string.IsNullOrEmpty(filePath))
return null;
var lastDirPos = filePath.LastIndexOf(DirSep);
return lastDirPos >= 0
? filePath.Substring(0, lastDirPos)
: null;
}
public string GetImmediateSubDirPath(string fromDirPath, string subDirPath)
{
if (string.IsNullOrEmpty(subDirPath))
return null;
if (fromDirPath == null)
{
return subDirPath.CountOccurrencesOf(DirSep) == 0
? subDirPath
: subDirPath.LeftPart(DirSep);
}
if (!subDirPath.StartsWith(fromDirPath))
return null;
return fromDirPath.CountOccurrencesOf(DirSep) == subDirPath.CountOccurrencesOf(DirSep) - 1
? subDirPath
: null;
}
public override string SanitizePath(string filePath)
{
var sanitizedPath = string.IsNullOrEmpty(filePath)
? null
: (IsDirSep(filePath[0]) ? filePath.Substring(1) : filePath);
return sanitizedPath?.Replace('/', DirSep);
}
public static string GetFileName(string filePath) => filePath.LastRightPart(DirSep);
}
public class GistVirtualFile : AbstractVirtualFileBase
{
private GistVirtualFiles PathProvider { get; set; }
public IGistGateway Client => PathProvider.Gateway;
public string GistId => PathProvider.GistId;
public override string Extension => Name.LastRightPart('.').LeftPart('|');
public GistVirtualFile(GistVirtualFiles pathProvider, IVirtualDirectory directory)
: base(pathProvider, directory)
{
this.PathProvider = pathProvider;
}
public string DirPath => ((GistVirtualDirectory) base.Directory).DirPath;
public string FilePath { get; set; }
public string ContentType { get; set; }
public override string Name => GistVirtualFiles.GetFileName(FilePath);
public override string VirtualPath => FilePath.Replace('\\', '/');
public DateTime FileLastModified { get; set; }
public override DateTime LastModified => FileLastModified;
public override long Length => ContentLength;
public long ContentLength { get; set; }
public string Text { get; set; } // Empty for Binary Files
public Stream Stream { get; set; }
public GistVirtualFile Init(string filePath, DateTime lastModified, string text, MemoryStream stream)
{
FilePath = filePath;
ContentType = MimeTypes.GetMimeType(filePath);
FileLastModified = lastModified;
ContentLength = stream.Length;
Text = text;
Stream = stream;
return this;
}
public override Stream OpenRead()
{
Stream.Position = 0;
return Stream.CopyToNewMemoryStream();
}
public override object GetContents()
{
return Text != null
? (object) Text.AsMemory()
: (Stream is MemoryStream ms
? ms.GetBufferAsMemory()
: Stream?.CopyToNewMemoryStream().GetBufferAsMemory());
}
public override void Refresh()
{
var elapsed = DateTime.UtcNow - PathProvider.LastRefresh;
var shouldRefresh = elapsed > PathProvider.RefreshAfter;
var gist = PathProvider.GetGist(refresh: shouldRefresh);
if (gist != null)
{
if (!GistVirtualFiles.GetGistContents(FilePath, gist, out var text, out var stream))
throw new FileNotFoundException("Gist File no longer exists", FilePath);
Init(FilePath, gist.Updated_At ?? gist.Created_at, text, stream);
return;
}
throw new FileNotFoundException("Gist no longer exists", GistId);
}
}
public class GistVirtualDirectory : AbstractVirtualDirectoryBase
{
internal GistVirtualFiles PathProvider { get; private set; }
public GistVirtualDirectory(GistVirtualFiles pathProvider, string dirPath, GistVirtualDirectory parentDir)
: base(pathProvider, parentDir)
{
this.PathProvider = pathProvider;
this.DirPath = dirPath;
}
public DateTime DirLastModified { get; set; }
public override DateTime LastModified => DirLastModified;
public override IEnumerable<IVirtualFile> Files => PathProvider.GetImmediateFiles(DirPath);
public override IEnumerable<IVirtualDirectory> Directories => PathProvider.GetImmediateDirectories(DirPath);
public IGistGateway Gateway => PathProvider.Gateway;
public string GistId => PathProvider.GistId;
public string DirPath { get; set; }
public override string VirtualPath => DirPath?.Replace('\\', '/');
public override string Name => DirPath?.LastRightPart(GistVirtualFiles.DirSep);
public override IVirtualFile GetFile(string virtualPath)
{
return VirtualPathProvider.GetFile(DirPath.CombineWith(virtualPath));
}
public override IEnumerator<IVirtualNode> GetEnumerator()
{
throw new NotImplementedException();
}
protected override IVirtualFile GetFileFromBackingDirectoryOrDefault(string fileName)
{
return GetFile(fileName);
}
protected override IEnumerable<IVirtualFile> GetMatchingFilesInDir(string globPattern)
{
var matchingFilesInBackingDir = EnumerateFiles(globPattern);
return matchingFilesInBackingDir;
}
public IEnumerable<GistVirtualFile> EnumerateFiles(string pattern)
{
foreach (var file in PathProvider.GetImmediateFiles(DirPath).Where(f => f.Name.Glob(pattern)))
{
yield return file;
}
}
protected override IVirtualDirectory GetDirectoryFromBackingDirectoryOrDefault(string directoryName)
{
return new GistVirtualDirectory(PathProvider, PathProvider.SanitizePath(DirPath.CombineWith(directoryName)),
this);
}
public void AddFile(string virtualPath, string contents)
{
VirtualPathProvider.WriteFile(DirPath.CombineWith(virtualPath), contents);
}
public void AddFile(string virtualPath, Stream stream)
{
VirtualPathProvider.WriteFile(DirPath.CombineWith(virtualPath), stream);
}
private static string StripDirSeparatorPrefix(string filePath)
{
return string.IsNullOrEmpty(filePath)
? filePath
: (filePath[0] == GistVirtualFiles.DirSep ? filePath.Substring(1) : filePath);
}
public override IEnumerable<IVirtualFile> GetAllMatchingFiles(string globPattern, int maxDepth = int.MaxValue)
{
if (IsRoot)
{
return PathProvider.EnumerateFiles().Where(x =>
(x.DirPath == null || x.DirPath.CountOccurrencesOf(GistVirtualFiles.DirSep) < maxDepth - 1)
&& x.Name.Glob(globPattern));
}
return PathProvider.EnumerateFiles(DirPath).Where(x =>
x.DirPath != null
&& x.DirPath.CountOccurrencesOf(GistVirtualFiles.DirSep) < maxDepth - 1
&& x.DirPath.StartsWith(DirPath)
&& x.Name.Glob(globPattern));
}
}
}
| |
#pragma warning disable 0168
using nHydrate.Dsl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
namespace nHydrate.DslPackage.Forms
{
internal partial class RelationCollectionForm : System.Windows.Forms.Form
{
#region Class Members
private nHydrateModel _model = null;
private Microsoft.VisualStudio.Modeling.Store _store = null;
private Microsoft.VisualStudio.Modeling.Diagrams.Diagram _diagram = null;
private EntityShape _entityShape = null;
private nHydrateDocData _docData = null;
#endregion
public RelationCollectionForm()
{
InitializeComponent();
}
public RelationCollectionForm(
nHydrateModel model,
EntityShape entityShape,
Microsoft.VisualStudio.Modeling.Store store,
Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram,
nHydrateDocData docData)
: this()
{
_model = model;
_store = store;
_diagram = diagram;
_docData = docData;
_entityShape = entityShape;
lvwMembers.Columns.Clear();
lvwMembers.Columns.Add(new ColumnHeader() { Text = "Parent", Width = 200 });
lvwMembers.Columns.Add(new ColumnHeader() { Text = "Child", Width = 200 });
lvwMembers.Columns.Add(new ColumnHeader() { Text = "Role", Width = 200 });
lvwMembers.ListViewItemSorter = new ListViewItemComparer(0, lvwMembers.Sorting);
lvwMembers.Sort();
this.LoadList();
}
#region Form Events
#endregion
#region Methods
private void AddItem(EntityAssociationConnector connector)
{
var li = new ListViewItem();
li.Tag = connector;
li.Text = (connector.FromShape.ModelElement as Entity).Name;
if (connector.ToShape == null) li.SubItems.Add(string.Empty);
else li.SubItems.Add((connector.ToShape.ModelElement as Entity).Name);
li.SubItems.Add(((EntityHasEntities)connector.ModelElement).RoleName);
lvwMembers.Items.Add(li);
}
private void EnableButtons()
{
cmdEdit.Enabled = (lvwMembers.SelectedItems.Count >= 0);
cmdDelete.Enabled = (lvwMembers.SelectedItems.Count >= 0);
}
private void LoadList()
{
try
{
var index = -1;
if (lvwMembers.SelectedItems.Count > 0)
index = lvwMembers.SelectedItems[0].Index;
//Load the relations into the list
lvwMembers.Items.Clear();
//Get a list of relations for the current entity only
var relationshipList = new List<EntityAssociationConnector>();
foreach (var connector in _diagram.NestedChildShapes.Where(x => x is EntityAssociationConnector).Cast<EntityAssociationConnector>())
{
if (connector.FromShape == _entityShape)
{
relationshipList.Add(connector);
}
}
foreach (var connector in relationshipList)
{
this.AddItem(connector);
}
lvwMembers.SelectedItems.Clear();
if ((0 <= index) && (index < lvwMembers.Items.Count))
lvwMembers.Items[index].Selected = true;
else if (index >= 0)
lvwMembers.Items[lvwMembers.Items.Count - 1].Selected = true;
else if (lvwMembers.Items.Count != 0)
lvwMembers.Items[0].Selected = true;
}
catch (Exception ex)
{
throw;
}
this.EnableButtons();
}
private bool EditItem()
{
if (lvwMembers.SelectedItems.Count == 0) return false;
var connector = lvwMembers.SelectedItems.Cast<ListViewItem>().FirstOrDefault().Tag as EntityAssociationConnector;
var F = new nHydrate.DslPackage.Forms.RelationshipDialog(_model, _store, connector.ModelElement as EntityHasEntities);
if (F.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.LoadList();
return true;
}
return false;
}
#endregion
#region RelationPropertyChanged
private void RelationPropertyChanged(object sender, PropertyChangedEventArgs e)
{
this.LoadList();
}
#endregion
#region Event Handlers
private void cmdAdd_Click(object sender, EventArgs e)
{
using (var transaction = _store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
{
_docData.IsImporting = true;
try
{
var parent = _entityShape.ModelElement as Entity;
var currentList = _store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.ToList();
parent.ChildEntities.Add(parent);
var updatedList = _store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.ToList();
updatedList.RemoveAll(x => currentList.Contains(x));
var connection = updatedList.First() as EntityHasEntities;
var F = new nHydrate.DslPackage.Forms.RelationshipDialog(_model, _store, connection, true);
if (F.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
transaction.Commit();
}
}
catch (Exception ex)
{
throw;
}
finally
{
_docData.IsImporting = false;
}
this.LoadList();
}
}
private void cmdEdit_Click(object sender, EventArgs e)
{
this.EditItem();
}
private void cmdDelete_Click(object sender, EventArgs e)
{
var list = new List<ListViewItem>();
list.AddRange(lvwMembers.SelectedItems.Cast<ListViewItem>());
foreach (var li in list)
{
var connector = li.Tag as EntityAssociationConnector;
using (var transaction = _store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
{
connector.ModelElement.Delete();
_diagram.NestedChildShapes.Remove(connector);
transaction.Commit();
}
lvwMembers.Items.Remove(li);
}
this.LoadList();
}
private void cmdOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void lvwMembers_SelectedIndexChanged(object sender, EventArgs e)
{
this.EnableButtons();
}
private void lvwMembers_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
this.EditItem();
}
}
private void lvwMembers_DoubleClick(object sender, EventArgs e)
{
this.EditItem();
}
#endregion
private int sortColumn = -1;
private void lvwMembers_ColumnClick(object sender, ColumnClickEventArgs e)
{
// Determine whether the column is the same as the last column clicked.
if (e.Column != sortColumn)
{
// Set the sort column to the new column.
sortColumn = e.Column;
// Set the sort order to ascending by default.
lvwMembers.Sorting = SortOrder.Ascending;
}
else
{
// Determine what the last sort order was and change it.
if (lvwMembers.Sorting == SortOrder.Ascending)
lvwMembers.Sorting = SortOrder.Descending;
else
lvwMembers.Sorting = SortOrder.Ascending;
}
// Call the sort method to manually sort.
lvwMembers.Sort();
this.lvwMembers.ListViewItemSorter = new ListViewItemComparer(e.Column, lvwMembers.Sorting);
}
}
}
| |
using System;
using PcapDotNet.Base;
namespace PcapDotNet.Packets.IpV4
{
/// <summary>
/// The Quick-Start Option for IPv4
///
/// <para>
/// The Quick-Start Request for IPv4 is defined as follows:
/// <pre>
/// +--------+----------+-------+---------+-------+-------+
/// | 0-7 | 8-15 | 16-19 | 20-23 | 24-29 | 30-31 |
/// +--------+----------+-------+---------+-------+-------+
/// | Option | Length=8 | Func. | Rate | QS TTL |
/// | | | 0000 | Request | |
/// +--------+----------+-------+---------+-------+-------+
/// | QS Nonce | R |
/// +---------------------------------------------+-------+
/// </pre>
/// </para>
/// </summary>
[OptionTypeRegistration(typeof(IpV4OptionType), IpV4OptionType.QuickStart)]
public sealed class IpV4OptionQuickStart : IpV4OptionComplex, IOptionComplexFactory, IEquatable<IpV4OptionQuickStart>
{
/// <summary>
/// The number of bytes this option take.
/// </summary>
public const int OptionLength = 8;
/// <summary>
/// The number of bytes this option's value take.
/// </summary>
public const int OptionValueLength = OptionLength - OptionHeaderLength;
/// <summary>
/// The maximum value for the rate field.
/// </summary>
public const byte RateMaximumValue = 0x0F;
/// <summary>
/// Create a quick start option according to the given field values.
/// </summary>
/// <param name="function">The function of this quick start option.</param>
/// <param name="rate">Either the rate requested or reported.</param>
/// <param name="ttl">
/// The Quick-Start TTL (QS TTL) field.
/// The sender MUST set the QS TTL field to a random value.
/// Routers that approve the Quick-Start Request decrement the QS TTL (mod 256) by the same amount that they decrement the IP TTL.
/// The QS TTL is used by the sender to detect if all the routers along the path understood and approved the Quick-Start option.
/// </param>
/// <param name="nonce">
/// The QS Nonce gives the Quick-Start sender some protection against receivers lying about the value of the received Rate Request.
/// </param>
public IpV4OptionQuickStart(IpV4OptionQuickStartFunction function, byte rate, byte ttl, uint nonce)
: base(IpV4OptionType.QuickStart)
{
if (function != IpV4OptionQuickStartFunction.RateRequest &&
function != IpV4OptionQuickStartFunction.RateReport)
{
throw new ArgumentException("Illegal function " + function, "function");
}
if (rate > RateMaximumValue)
throw new ArgumentOutOfRangeException("rate", rate, "Rate maximum value is " + RateMaximumValue);
if ((nonce & 0x00000003) != 0)
throw new ArgumentException("nonce last two bits are reserved and must be zero", "nonce");
_function = function;
_rate = rate;
_ttl = ttl;
_nonce = nonce;
}
/// <summary>
/// Creates a request with 0 fields.
/// </summary>
public IpV4OptionQuickStart()
: this(IpV4OptionQuickStartFunction.RateRequest, 0, 0, 0)
{
}
/// <summary>
/// The function of this quick start option.
/// </summary>
public IpV4OptionQuickStartFunction Function
{
get { return _function; }
}
/// <summary>
/// If function is request then this field is the rate request.
/// If function is report then this field is the rate report.
/// </summary>
public byte Rate
{
get { return _rate; }
}
/// <summary>
/// The rate translated to KBPS.
/// </summary>
public int RateKbps
{
get
{
if (Rate == 0)
return 0;
return 40 * (1 << Rate);
}
}
/// <summary>
/// The Quick-Start TTL (QS TTL) field.
/// The sender MUST set the QS TTL field to a random value.
/// Routers that approve the Quick-Start Request decrement the QS TTL (mod 256) by the same amount that they decrement the IP TTL.
/// The QS TTL is used by the sender to detect if all the routers along the path understood and approved the Quick-Start option.
///
/// <para>
/// For a Rate Request, the transport sender MUST calculate and store the TTL Diff,
/// the difference between the IP TTL value, and the QS TTL value in the Quick-Start Request packet, as follows:
/// TTL Diff = ( IP TTL - QS TTL ) mod 256
/// </para>
/// </summary>
public byte Ttl
{
get { return _ttl; }
}
/// <summary>
/// The QS Nonce gives the Quick-Start sender some protection against receivers lying about the value of the received Rate Request.
/// This is particularly important if the receiver knows the original value of the Rate Request
/// (e.g., when the sender always requests the same value, and the receiver has a long history of communication with that sender).
/// Without the QS Nonce, there is nothing to prevent the receiver from reporting back to the sender a Rate Request of K,
/// when the received Rate Request was, in fact, less than K.
///
/// <para>
/// The format for the 30-bit QS Nonce.
/// <list type="table">
/// <listheader>
/// <term>Bits</term>
/// <description>Purpose</description>
/// </listheader>
/// <item><term>Bits 0-1</term><description>Rate 15 -> Rate 14</description></item>
/// <item><term>Bits 2-3</term><description>Rate 14 -> Rate 13</description></item>
/// <item><term>Bits 4-5</term><description>Rate 13 -> Rate 12</description></item>
/// <item><term>Bits 6-7</term><description>Rate 12 -> Rate 11</description></item>
/// <item><term>Bits 8-9</term><description>Rate 11 -> Rate 10</description></item>
/// <item><term>Bits 10-11</term><description>Rate 10 -> Rate 9</description></item>
/// <item><term>Bits 12-13</term><description>Rate 9 -> Rate 8</description></item>
/// <item><term>Bits 14-15</term><description>Rate 8 -> Rate 7</description></item>
/// <item><term>Bits 16-17</term><description>Rate 7 -> Rate 6</description></item>
/// <item><term>Bits 18-19</term><description>Rate 6 -> Rate 5</description></item>
/// <item><term>Bits 20-21</term><description>Rate 5 -> Rate 4</description></item>
/// <item><term>Bits 22-23</term><description>Rate 4 -> Rate 3</description></item>
/// <item><term>Bits 24-25</term><description>Rate 3 -> Rate 2</description></item>
/// <item><term>Bits 26-27</term><description>Rate 2 -> Rate 1</description></item>
/// <item><term>Bits 28-29</term><description>Rate 1 -> Rate 0</description></item>
/// </list>
/// </para>
///
/// <para>
/// The transport sender MUST initialize the QS Nonce to a random value.
/// If the router reduces the Rate Request from rate K to rate K-1,
/// then the router MUST set the field in the QS Nonce for "Rate K -> Rate K-1" to a new random value.
/// Similarly, if the router reduces the Rate Request by N steps,
/// the router MUST set the 2N bits in the relevant fields in the QS Nonce to a new random value.
/// The receiver MUST report the QS Nonce back to the sender.
/// </para>
///
/// <para>
/// If the Rate Request was not decremented in the network, then the QS Nonce should have its original value.
/// Similarly, if the Rate Request was decremented by N steps in the network,
/// and the receiver reports back a Rate Request of K, then the last 2K bits of the QS Nonce should have their original value.
/// </para>
/// </summary>
public uint Nonce
{
get { return _nonce; }
}
/// <summary>
/// The number of bytes this option will take.
/// </summary>
public override int Length
{
get { return OptionLength; }
}
/// <summary>
/// True iff this option may appear at most once in a datagram.
/// </summary>
public override bool IsAppearsAtMostOnce
{
get { return true; }
}
/// <summary>
/// Two quick start options are equal iff they have the exact same field values.
/// </summary>
public bool Equals(IpV4OptionQuickStart other)
{
if (other == null)
return false;
return Function == other.Function &&
Rate == other.Rate &&
Ttl == other.Ttl &&
Nonce == other.Nonce;
}
/// <summary>
/// Two trace route options are equal iff they have the exact same field values.
/// </summary>
public override bool Equals(IpV4Option other)
{
return Equals(other as IpV4OptionQuickStart);
}
/// <summary>
/// The hash code is the xor of the base class hash code with the following values hash code:
/// The combination of function, rate and ttl and the nonce.
/// </summary>
public override int GetHashCode()
{
return base.GetHashCode() ^
Sequence.GetHashCode(BitSequence.Merge((byte)((byte)Function | Rate), Ttl), Nonce);
}
/// <summary>
/// Tries to read the option from a buffer starting from the option value (after the type and length).
/// </summary>
/// <param name="buffer">The buffer to read the option from.</param>
/// <param name="offset">The offset to the first byte to read the buffer. Will be incremented by the number of bytes read.</param>
/// <param name="valueLength">The number of bytes the option value should take according to the length field that was already read.</param>
/// <returns>On success - the complex option read. On failure - null.</returns>
Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength)
{
if (valueLength != OptionValueLength)
return null;
byte functionAndRate = buffer[offset++];
IpV4OptionQuickStartFunction function = (IpV4OptionQuickStartFunction)(functionAndRate & 0xF0);
byte rate = (byte)(functionAndRate & 0x0F);
byte ttl = buffer[offset++];
uint nonce = buffer.ReadUInt(ref offset, Endianity.Big);
return new IpV4OptionQuickStart(function, rate, ttl, nonce);
}
internal override void Write(byte[] buffer, ref int offset)
{
base.Write(buffer, ref offset);
buffer[offset++] = (byte)((byte)Function | Rate);
buffer[offset++] = Ttl;
buffer.Write(ref offset, Nonce, Endianity.Big);
}
private readonly IpV4OptionQuickStartFunction _function;
private readonly byte _rate;
private readonly byte _ttl;
private readonly uint _nonce;
}
}
| |
// 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.Xml;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Execution;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Construction;
using Microsoft.Build.Collections;
using System.IO;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
namespace Microsoft.Build.UnitTests.QA
{
/// <summary>
/// Steps to write the tests
/// 1) Create a TestProjectDefinition object for each project file or a build request that you will submit
/// 2) Call Build() on the object to submit the build request
/// 3) Call ValidateResults() on the object to wait till the build completes and the results sent were what we expected
/// </summary>
[TestClass]
[Ignore] // "QA tests are double-initializing some components such as BuildRequestEngine."
public class Integration_Tests
{
#region Data members
private Common_Tests _commonTests;
private ResultsCache _resultsCache;
private string _assemblyPath;
private string _tempPath;
#endregion
#region Constructor
/// <summary>
/// Setup the object
/// </summary>
public Integration_Tests()
{
_commonTests = new Common_Tests(this.GetComponent, true);
_resultsCache = null;
_tempPath = System.IO.Path.GetTempPath();
_assemblyPath = Path.GetDirectoryName(
new Uri(System.Reflection.Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath);
_assemblyPath = Path.Combine(_assemblyPath, "Microsoft.Build.Unittest.dll");
}
#endregion
#region Common
/// <summary>
/// Delegate to common test setup
/// </summary>
[TestInitialize]
public void Setup()
{
_resultsCache = new ResultsCache();
_commonTests.Setup();
}
/// <summary>
/// Delegate to common test teardown
/// </summary>
[TestCleanup]
public void TearDown()
{
_commonTests.TearDown();
_resultsCache = null;
}
#endregion
#region GetComponent delegate
/// <summary>
/// Provides the components required by the tests
/// </summary>
internal IBuildComponent GetComponent(BuildComponentType type)
{
switch (type)
{
case BuildComponentType.RequestBuilder:
RequestBuilder requestBuilder = new RequestBuilder();
return (IBuildComponent)requestBuilder;
case BuildComponentType.TaskBuilder:
TaskBuilder taskBuilder = new TaskBuilder();
return (IBuildComponent)taskBuilder;
case BuildComponentType.TargetBuilder:
TargetBuilder targetBuilder = new TargetBuilder();
return (IBuildComponent)targetBuilder;
case BuildComponentType.ResultsCache:
return (IBuildComponent)_resultsCache;
default:
throw new ArgumentException("Unexpected type requested. Type = " + type.ToString());
}
}
#endregion
#region Data Input and Output from task
/// <summary>
/// Send some parameters to the task and expect certain outputs
/// </summary>
[TestMethod]
[Ignore] // "Cannot use a project instance if the project is created from a file."
public void InputAndOutputFromTask()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t'>
<QAMockTaskForIntegrationTests ExpectedOutput='Foo' TaskShouldThrowException='false'>
<Output TaskParameter='TaskOutput' PropertyName='SomeProperty'/>
</QAMockTaskForIntegrationTests>
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
ProjectPropertyInstance property = projectInstance.GetProperty("SomeProperty");
Assert.IsTrue(property.EvaluatedValue == "Foo", "SomeProperty=Foo");
}
#endregion
#region Data Output from target
/// <summary>
/// Target outputs
/// </summary>
[TestMethod]
public void OutputFromTarget()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t' Outputs='$(SomeProperty)'>
<QAMockTaskForIntegrationTests ExpectedOutput='Foo' TaskShouldThrowException='false'>
<Output TaskParameter='TaskOutput' PropertyName='SomeProperty'/>
</QAMockTaskForIntegrationTests>
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t", TargetResultCode.Success, new string[1] { "Foo" });
}
#endregion
#region Data changed
/// <summary>
/// Send some parameters to the task and expect certain outputs. This output overwrites an existing property
/// </summary>
[TestMethod]
[Ignore] // "Cannot use a project instance if the project is created from a file."
public void OutputFromTaskUpdatesProperty()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<PropertyGroup>
<SomeProperty>oldvalue</SomeProperty>
</PropertyGroup>
<Target Name='t'>
<QAMockTaskForIntegrationTests ExpectedOutput='Foo' TaskShouldThrowException='false'>
<Output TaskParameter='TaskOutput' PropertyName='SomeProperty'/>
</QAMockTaskForIntegrationTests>
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
ProjectPropertyInstance property = projectInstance.GetProperty("SomeProperty");
Assert.IsTrue(property.EvaluatedValue == "Foo", "SomeProperty=Foo");
}
#endregion
#region OnError
/// <summary>
/// Target1 executes task1. Task1 has an error with continue on error. Target1 then executes task2 with has an error with stop on error.
/// Target1 has OnError to execute target2
/// </summary>
[TestMethod]
public void OnErrorTargetIsBuilt()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t2", TargetResultCode.Success, null);
}
/// <summary>
/// Target1 executes task1. Task1 has an error with continue on error. Target1 then executes task2 with has an error with stop on error.
/// Target1 has OnError to execute target2
/// </summary>
[TestMethod]
public void OnErrorTargetIsBuilt2()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true' ContinueOnError='true'/>
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t2", TargetResultCode.Success, null);
}
/// <summary>
/// Target0 depends on Target1 which executes task1. Task1 has an error with stop on error. Target1 has OnError to execute target2
/// </summary>
[TestMethod]
public void OnErrorTargetIsBuilt3()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t0' DependsOnTargets='t1' />
<Target Name='t1' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t0", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t0", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t2", TargetResultCode.Success, null);
}
/// <summary>
/// Target1 executeserror with stop on error. Target1 has OnError to execute target2 and target3
/// </summary>
[TestMethod]
public void MultipleOnErrorTargetIsBuiltOnDependsOnTarget()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2;t3' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
<Target Name='t3' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t2", TargetResultCode.Success, null);
r1.ValidateNonPrimaryTargetEndResult("t3", TargetResultCode.Success, null);
}
/// <summary>
/// Target1 executes task1 which does not error. Target1 has OnError to execute target2
/// </summary>
[TestMethod]
public void OnErrorTargetIsNotBuiltInNonErrorCondition()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1' >
<QAMockTaskForIntegrationTests />
<OnError ExecuteTargets='t2' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Success, null);
r1.ValidateTargetDidNotBuild("t2");
}
/// <summary>
/// Target1 executes task1. Task1 has an error with continue on error. Target1 has OnError to execute target2
/// </summary>
[TestMethod]
public void OnErrorTargetIsNotBuiltWithContinueOnError()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true' ContinueOnError='true'/>
<OnError ExecuteTargets='t2' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Success, null);
r1.ValidateTargetDidNotBuild("t2");
}
/// <summary>
/// Target1 which executes task1. Task1 has an error with stop on error. Target1 has OnError to execute target2 and target3
/// </summary>
[TestMethod]
public void MultipleOnErrorTargetIsBuilt()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2;t3' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
<Target Name='t3' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t2", TargetResultCode.Success, null);
r1.ValidateNonPrimaryTargetEndResult("t3", TargetResultCode.Success, null);
}
/// <summary>
/// Target1 executes task1. Task1 has an error with Stop on error. Target1 has OnError to execute target2 but is above task1
/// (OnError is above the failing task)
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void OnErrorIsDefinedAboveTheFailingTask()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<OnError ExecuteTargets='t2' />
<QAMockTaskForIntegrationTests TaskShouldError='true' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateTargetDidNotBuild("t2");
}
/// <summary>
/// Request builds target1 and target2. Target2 has an error and calls target1
/// </summary>
[TestMethod]
public void OnErrorTargetIsATargetAlreadyBuilt()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t1' />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1;t2", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Success, null);
r1.ValidateTargetEndResult("t2", TargetResultCode.Failure, null);
}
/// <summary>
/// Initial target has target1. Target1 has an error and contains OnError which builds target2
/// </summary>
[TestMethod]
public void OnErrorTargetInvolvingInitialTarget()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace' InitialTargets='t1'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", null, out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t2", TargetResultCode.Success, null);
}
/// <summary>
/// Default target has target1. Target1 has an error and contains OnError which builds target2
/// </summary>
[TestMethod]
public void OnErrorTargetInvolvingDefaultTarget()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace' DefaultTargets='t1'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", null, out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t2", TargetResultCode.Success, null);
}
/// <summary>
/// Target1 which fails has an OnError with target2 and target3 where target2 has a task with stop on error and has OnError.
/// Target3 is also executed
/// </summary>
[TestMethod]
public void ErrorInFirstOnErrorTarget()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2;t3' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t4' />
</Target>
<Target Name='t3' >
<QAMockTaskForIntegrationTests />
</Target>
<Target Name='t4' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t2", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t3", TargetResultCode.Success, null);
r1.ValidateNonPrimaryTargetEndResult("t4", TargetResultCode.Success, null);
}
/// <summary>
/// Target1 which fails has an OnError with target2 and target3 where target2 has a task with stop on error and has OnError.
/// Target3 is executed in this case
/// </summary>
[TestMethod]
public void ErrorInFirstOnErrorTarget2()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2;t3' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
<Target Name='t3' >
<QAMockTaskForIntegrationTests TaskShouldError='true'/>
<OnError ExecuteTargets='t4' />
</Target>
<Target Name='t4' >
<QAMockTaskForIntegrationTests />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t2", TargetResultCode.Success, null);
r1.ValidateNonPrimaryTargetEndResult("t3", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t4", TargetResultCode.Success, null);
}
/// <summary>
/// Target1 which fails has an OnError with target2 and target3 where target2 also errors and has OnError
/// </summary>
[TestMethod]
public void ContinueOnErrorInFirstOnErrorTarget()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2;t3' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests />
</Target>
<Target Name='t3' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t4' />
</Target>
<Target Name='t4' />
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResults();
r1.ValidateTargetEndResult("t1", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t3", TargetResultCode.Failure, null);
r1.ValidateNonPrimaryTargetEndResult("t2", TargetResultCode.Success, null);
r1.ValidateNonPrimaryTargetEndResult("t4", TargetResultCode.Success, null);
}
/// <summary>
/// Circular dependency with OnError
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void CircularDependency()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true'/>
<OnError ExecuteTargets='t2' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t1' />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResultsThrowException();
}
/// <summary>
/// Circular dependency with OnError where OnError also has an OnError
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void CircularDependencyChain1()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true'/>
<OnError ExecuteTargets='t2' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t3' />
</Target>
<Target Name='t3' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2' />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResultsThrowException();
}
/// <summary>
/// Circular dependency with OnError where OnError also has an OnError
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void CircularDependencyChain2()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true'/>
<OnError ExecuteTargets='t2' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t3' />
</Target>
<Target Name='t3' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t1' />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResultsThrowException();
}
/// <summary>
/// Circular dependency with OnError where OnError also has an OnError
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void CircularDependencyChain3()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true'/>
<OnError ExecuteTargets='t3' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t3' />
</Target>
<Target Name='t3' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2' />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResultsThrowException();
}
/// <summary>
/// Circular dependency with OnError where OnError also has an OnError
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void CircularDependencyChain4()
{
string projectFileContents = String.Format(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='QAMockTaskForIntegrationTests' AssemblyFile='{0}' />
<Target Name='t1'>
<QAMockTaskForIntegrationTests TaskShouldError='true'/>
<OnError ExecuteTargets='t3' />
</Target>
<Target Name='t2' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t1' />
</Target>
<Target Name='t3' >
<QAMockTaskForIntegrationTests TaskShouldError='true' />
<OnError ExecuteTargets='t2' />
</Target>
</Project>"),
_assemblyPath);
ProjectInstance projectInstance = null;
RequestDefinition r1 = GetRequestUsingProject(projectFileContents, "1.proj", "t1", out projectInstance);
r1.SubmitBuildRequest();
r1.WaitForResultsThrowException();
}
#endregion
#region Private Helper
/// <summary>
/// Creates a projectinstance from a string which contains the project file contents
/// </summary>
private ProjectInstance GenerateProjectInstanceFromXml(string projectFileContents)
{
Project projectDefinition = new Project(XmlReader.Create(new StringReader(projectFileContents)));
return projectDefinition.CreateProjectInstance();
}
/// <summary>
/// Given a string containing the project file content return a RequestBuilder with all the information of the project
/// populated.
/// </summary>
private RequestDefinition GetRequestUsingProject(string projectFileContents, string projectName, string targetName, out ProjectInstance project)
{
ProjectDefinition p1 = new ProjectDefinition(projectName);
project = p1.MSBuildProjectInstance = GenerateProjectInstanceFromXml(projectFileContents);
string[] targetNames = null;
if (targetName != null)
{
targetNames = targetName.Split(';');
}
projectName = System.IO.Path.Combine(_tempPath, projectName);
RequestDefinition r1 = new RequestDefinition(projectName, "2.0", targetNames, null, 0, null, (IBuildComponentHost)_commonTests.Host);
r1.ProjectDefinition = p1;
return r1;
}
#endregion
}
/// <summary>
/// Mock task implementation which will be used by the above tests
/// </summary>
public class QAMockTaskForIntegrationTests : Microsoft.Build.Framework.ITask
{
#region Private data
/// <summary>
/// Task host
/// </summary>
private Microsoft.Build.Framework.ITaskHost _taskHost;
/// <summary>
/// Build engine
/// </summary>
private Microsoft.Build.Framework.IBuildEngine _buildEngine;
/// <summary>
/// Expected output
/// </summary>
private string _expectedOutput;
/// <summary>
/// Task should show an exception
/// </summary>
private bool _taskShouldThrow;
/// <summary>
/// Task should return false from Execute indicating error
/// </summary>
private bool _taskShouldError;
#endregion
/// <summary>
/// Default constructor
/// </summary>
public QAMockTaskForIntegrationTests()
{
_taskShouldError = false;
_taskShouldThrow = false;
_expectedOutput = String.Empty;
}
#region ITask Members
/// <summary>
/// BuildEngine that can be used to access some engine capabilities like building project
/// </summary>
public Microsoft.Build.Framework.IBuildEngine BuildEngine
{
get
{
return _buildEngine;
}
set
{
_buildEngine = value;
}
}
/// <summary>
/// Task Host
/// </summary>
public Microsoft.Build.Framework.ITaskHost HostObject
{
get
{
return _taskHost;
}
set
{
_taskHost = value;
}
}
/// <summary>
/// Expected output to populate
/// </summary>
public string ExpectedOutput
{
set
{
_expectedOutput = value;
}
}
/// <summary>
/// If the task should succeed or fail
/// </summary>
public bool TaskShouldError
{
set
{
_taskShouldError = value;
}
}
/// <summary>
/// Expected output to populate
/// </summary>
public bool TaskShouldThrowException
{
set
{
_taskShouldThrow = value;
}
}
/// <summary>
/// Output from the task which is set to the expected output
/// </summary>
[Microsoft.Build.Framework.Output]
public string TaskOutput
{
get
{
return _expectedOutput;
}
}
/// <summary>
/// Execution of the task
/// </summary>
public bool Execute()
{
if (_taskShouldThrow)
{
throw new QAMockTaskForIntegrationTestsException();
}
if (_taskShouldError)
{
return false;
}
return true;
}
#endregion
}
/// <summary>
/// Exception object for the mock task
/// </summary>
[Serializable]
public class QAMockTaskForIntegrationTestsException : Exception
{
public QAMockTaskForIntegrationTestsException()
: base("QAMockTaskForIntegrationTestsException")
{
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
/// <summary>
/// Transactional cache tests.
/// </summary>
public abstract class CacheAbstractTransactionalTest : CacheAbstractTest
{
/// <summary>
/// Simple cache lock test (while <see cref="TestLock"/> is ignored).
/// </summary>
[Test]
public void TestLockSimple()
{
var cache = Cache();
const int key = 7;
Action<ICacheLock> checkLock = lck =>
{
using (lck)
{
Assert.Throws<InvalidOperationException>(lck.Exit); // can't exit if not entered
lck.Enter();
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
lck.Exit();
Assert.IsFalse(cache.IsLocalLocked(key, true));
Assert.IsFalse(cache.IsLocalLocked(key, false));
Assert.IsTrue(lck.TryEnter());
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
lck.Exit();
}
Assert.Throws<ObjectDisposedException>(lck.Enter); // Can't enter disposed lock
};
checkLock(cache.Lock(key));
checkLock(cache.LockAll(new[] { key, 1, 2, 3 }));
}
/// <summary>
/// Tests cache locks.
/// </summary>
[Test]
[Ignore("IGNITE-835")]
public void TestLock()
{
var cache = Cache();
const int key = 7;
// Lock
CheckLock(cache, key, () => cache.Lock(key));
// LockAll
CheckLock(cache, key, () => cache.LockAll(new[] { key, 2, 3, 4, 5 }));
}
/// <summary>
/// Internal lock test routine.
/// </summary>
/// <param name="cache">Cache.</param>
/// <param name="key">Key.</param>
/// <param name="getLock">Function to get the lock.</param>
private static void CheckLock(ICache<int, int> cache, int key, Func<ICacheLock> getLock)
{
var sharedLock = getLock();
using (sharedLock)
{
Assert.Throws<InvalidOperationException>(() => sharedLock.Exit()); // can't exit if not entered
sharedLock.Enter();
try
{
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
EnsureCannotLock(getLock, sharedLock);
sharedLock.Enter();
try
{
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
EnsureCannotLock(getLock, sharedLock);
}
finally
{
sharedLock.Exit();
}
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
EnsureCannotLock(getLock, sharedLock);
Assert.Throws<SynchronizationLockException>(() => sharedLock.Dispose()); // can't dispose while locked
}
finally
{
sharedLock.Exit();
}
Assert.IsFalse(cache.IsLocalLocked(key, true));
Assert.IsFalse(cache.IsLocalLocked(key, false));
var innerTask = new Task(() =>
{
Assert.IsTrue(sharedLock.TryEnter());
sharedLock.Exit();
using (var otherLock = getLock())
{
Assert.IsTrue(otherLock.TryEnter());
otherLock.Exit();
}
});
innerTask.Start();
innerTask.Wait();
}
Assert.IsFalse(cache.IsLocalLocked(key, true));
Assert.IsFalse(cache.IsLocalLocked(key, false));
var outerTask = new Task(() =>
{
using (var otherLock = getLock())
{
Assert.IsTrue(otherLock.TryEnter());
otherLock.Exit();
}
});
outerTask.Start();
outerTask.Wait();
Assert.Throws<ObjectDisposedException>(() => sharedLock.Enter()); // Can't enter disposed lock
}
/// <summary>
/// Ensure that lock cannot be obtained by other threads.
/// </summary>
/// <param name="getLock">Get lock function.</param>
/// <param name="sharedLock">Shared lock.</param>
private static void EnsureCannotLock(Func<ICacheLock> getLock, ICacheLock sharedLock)
{
var task = new Task(() =>
{
Assert.IsFalse(sharedLock.TryEnter());
Assert.IsFalse(sharedLock.TryEnter(TimeSpan.FromMilliseconds(100)));
using (var otherLock = getLock())
{
Assert.IsFalse(otherLock.TryEnter());
Assert.IsFalse(otherLock.TryEnter(TimeSpan.FromMilliseconds(100)));
}
});
task.Start();
task.Wait();
}
/// <summary>
/// Tests that commit applies cache changes.
/// </summary>
[Test]
public void TestTxCommit([Values(true, false)] bool async)
{
var cache = Cache();
Assert.IsNull(Transactions.Tx);
using (var tx = Transactions.TxStart())
{
cache.Put(1, 1);
cache.Put(2, 2);
if (async)
{
var task = tx.CommitAsync();
task.Wait();
Assert.IsTrue(task.IsCompleted);
}
else
tx.Commit();
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests that rollback reverts cache changes.
/// </summary>
[Test]
public void TestTxRollback()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
Assert.IsNull(Transactions.Tx);
using (var tx = Transactions.TxStart())
{
cache.Put(1, 10);
cache.Put(2, 20);
tx.Rollback();
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests that Dispose without Commit reverts changes.
/// </summary>
[Test]
public void TestTxClose()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
Assert.IsNull(Transactions.Tx);
using (Transactions.TxStart())
{
cache.Put(1, 10);
cache.Put(2, 20);
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests all concurrency and isolation modes with and without timeout.
/// </summary>
[Test]
public void TestTxAllModes([Values(true, false)] bool withTimeout)
{
var cache = Cache();
int cntr = 0;
foreach (TransactionConcurrency concurrency in Enum.GetValues(typeof(TransactionConcurrency)))
{
foreach (TransactionIsolation isolation in Enum.GetValues(typeof(TransactionIsolation)))
{
Console.WriteLine("Test tx [concurrency=" + concurrency + ", isolation=" + isolation + "]");
Assert.IsNull(Transactions.Tx);
using (var tx = withTimeout
? Transactions.TxStart(concurrency, isolation, TimeSpan.FromMilliseconds(1100), 10)
: Transactions.TxStart(concurrency, isolation))
{
Assert.AreEqual(concurrency, tx.Concurrency);
Assert.AreEqual(isolation, tx.Isolation);
if (withTimeout)
Assert.AreEqual(1100, tx.Timeout.TotalMilliseconds);
cache.Put(1, cntr);
tx.Commit();
}
Assert.IsNull(Transactions.Tx);
Assert.AreEqual(cntr, cache.Get(1));
cntr++;
}
}
}
/// <summary>
/// Tests that transaction properties are applied and propagated properly.
/// </summary>
[Test]
public void TestTxAttributes()
{
ITransaction tx = Transactions.TxStart(TransactionConcurrency.Optimistic,
TransactionIsolation.RepeatableRead, TimeSpan.FromMilliseconds(2500), 100);
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.IsTrue(tx.StartTime.Ticks > 0);
Assert.AreEqual(tx.NodeId, GetIgnite(0).GetCluster().GetLocalNode().Id);
DateTime startTime1 = tx.StartTime;
tx.Commit();
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionState.Committed, tx.State);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(startTime1, tx.StartTime);
Thread.Sleep(100);
tx = Transactions.TxStart(TransactionConcurrency.Pessimistic, TransactionIsolation.ReadCommitted,
TimeSpan.FromMilliseconds(3500), 200);
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionConcurrency.Pessimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.ReadCommitted, tx.Isolation);
Assert.AreEqual(3500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.IsTrue(tx.StartTime.Ticks > 0);
Assert.IsTrue(tx.StartTime > startTime1);
DateTime startTime2 = tx.StartTime;
tx.Rollback();
Assert.AreEqual(TransactionState.RolledBack, tx.State);
Assert.AreEqual(TransactionConcurrency.Pessimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.ReadCommitted, tx.Isolation);
Assert.AreEqual(3500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(startTime2, tx.StartTime);
Thread.Sleep(100);
tx = Transactions.TxStart(TransactionConcurrency.Optimistic, TransactionIsolation.RepeatableRead,
TimeSpan.FromMilliseconds(2500), 100);
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.IsTrue(tx.StartTime > startTime2);
DateTime startTime3 = tx.StartTime;
tx.Commit();
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionState.Committed, tx.State);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(startTime3, tx.StartTime);
// Check defaults.
tx = Transactions.TxStart();
Assert.AreEqual(Transactions.DefaultTransactionConcurrency, tx.Concurrency);
Assert.AreEqual(Transactions.DefaultTransactionIsolation, tx.Isolation);
Assert.AreEqual(Transactions.DefaultTimeout, tx.Timeout);
tx.Commit();
}
/// <summary>
/// Tests <see cref="ITransaction.IsRollbackOnly"/> flag.
/// </summary>
[Test]
public void TestTxRollbackOnly()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
var tx = Transactions.TxStart();
cache.Put(1, 10);
cache.Put(2, 20);
Assert.IsFalse(tx.IsRollbackOnly);
tx.SetRollbackonly();
Assert.IsTrue(tx.IsRollbackOnly);
Assert.AreEqual(TransactionState.MarkedRollback, tx.State);
var ex = Assert.Throws<TransactionRollbackException>(() => tx.Commit());
Assert.IsTrue(ex.Message.StartsWith("Invalid transaction state for prepare [state=MARKED_ROLLBACK"));
tx.Dispose();
Assert.AreEqual(TransactionState.RolledBack, tx.State);
Assert.IsTrue(tx.IsRollbackOnly);
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests transaction metrics.
/// </summary>
[Test]
public void TestTxMetrics()
{
var cache = Cache();
var startTime = DateTime.UtcNow.AddSeconds(-1);
Transactions.ResetMetrics();
var metrics = Transactions.GetMetrics();
Assert.AreEqual(0, metrics.TxCommits);
Assert.AreEqual(0, metrics.TxRollbacks);
using (Transactions.TxStart())
{
cache.Put(1, 1);
}
using (var tx = Transactions.TxStart())
{
cache.Put(1, 1);
tx.Commit();
}
metrics = Transactions.GetMetrics();
Assert.AreEqual(1, metrics.TxCommits);
Assert.AreEqual(1, metrics.TxRollbacks);
Assert.LessOrEqual(startTime, metrics.CommitTime);
Assert.LessOrEqual(startTime, metrics.RollbackTime);
Assert.GreaterOrEqual(DateTime.UtcNow, metrics.CommitTime);
Assert.GreaterOrEqual(DateTime.UtcNow, metrics.RollbackTime);
}
/// <summary>
/// Tests transaction state transitions.
/// </summary>
[Test]
public void TestTxStateAndExceptions()
{
var tx = Transactions.TxStart();
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, tx.ThreadId);
tx.AddMeta("myMeta", 42);
Assert.AreEqual(42, tx.Meta<int>("myMeta"));
Assert.AreEqual(42, tx.RemoveMeta<int>("myMeta"));
tx.RollbackAsync().Wait();
Assert.AreEqual(TransactionState.RolledBack, tx.State);
Assert.Throws<InvalidOperationException>(() => tx.Commit());
tx = Transactions.TxStart();
Assert.AreEqual(TransactionState.Active, tx.State);
tx.CommitAsync().Wait();
Assert.AreEqual(TransactionState.Committed, tx.State);
var task = tx.RollbackAsync(); // Illegal, but should not fail here; will fail in task
Assert.Throws<AggregateException>(() => task.Wait());
}
/// <summary>
/// Tests the transaction deadlock detection.
/// </summary>
[Test]
public void TestTxDeadlockDetection()
{
var cache = Cache();
var keys0 = Enumerable.Range(1, 100).ToArray();
cache.PutAll(keys0.ToDictionary(x => x, x => x));
var barrier = new Barrier(2);
Action<int[]> increment = keys =>
{
using (var tx = Transactions.TxStart(TransactionConcurrency.Pessimistic,
TransactionIsolation.RepeatableRead, TimeSpan.FromSeconds(0.5), 0))
{
foreach (var key in keys)
cache[key]++;
barrier.SignalAndWait(500);
tx.Commit();
}
};
// Increment keys within tx in different order to cause a deadlock.
var aex = Assert.Throws<AggregateException>(() =>
Task.WaitAll(Task.Factory.StartNew(() => increment(keys0)),
Task.Factory.StartNew(() => increment(keys0.Reverse().ToArray()))));
Assert.AreEqual(2, aex.InnerExceptions.Count);
var deadlockEx = aex.InnerExceptions.OfType<TransactionDeadlockException>().First();
Assert.IsTrue(deadlockEx.Message.Trim().StartsWith("Deadlock detected:"), deadlockEx.Message);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/>.
/// </summary>
[Test]
public void TestTransactionScopeSingleCache()
{
var cache = Cache();
cache[1] = 1;
cache[2] = 2;
// Commit.
using (var ts = new TransactionScope())
{
cache[1] = 10;
cache[2] = 20;
Assert.IsNotNull(cache.Ignite.GetTransactions().Tx);
ts.Complete();
}
Assert.AreEqual(10, cache[1]);
Assert.AreEqual(20, cache[2]);
// Rollback.
using (new TransactionScope())
{
cache[1] = 100;
cache[2] = 200;
}
Assert.AreEqual(10, cache[1]);
Assert.AreEqual(20, cache[2]);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/>
/// with multiple participating caches.
/// </summary>
[Test]
public void TestTransactionScopeMultiCache([Values(true, false)] bool async)
{
var cache1 = Cache();
var cache2 = GetIgnite(0).GetOrCreateCache<int, int>(new CacheConfiguration(cache1.Name + "_")
{
AtomicityMode = CacheAtomicityMode.Transactional
});
cache1[1] = 1;
cache2[1] = 2;
// Commit.
using (var ts = new TransactionScope())
{
if (async)
{
cache1.PutAsync(1, 10);
cache2.PutAsync(1, 20);
}
else
{
cache1.Put(1, 10);
cache2.Put(1, 20);
}
ts.Complete();
}
Assert.AreEqual(10, cache1[1]);
Assert.AreEqual(20, cache2[1]);
// Rollback.
using (new TransactionScope())
{
if (async)
{
cache1.PutAsync(1, 100);
cache2.PutAsync(1, 200);
}
else
{
cache1.Put(1, 100);
cache2.Put(1, 200);
}
}
Assert.AreEqual(10, cache1[1]);
Assert.AreEqual(20, cache2[1]);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/>
/// when Ignite tx is started manually.
/// </summary>
[Test]
public void TestTransactionScopeWithManualIgniteTx()
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
cache[1] = 1;
// When Ignite tx is started manually, it won't be enlisted in TransactionScope.
using (var tx = transactions.TxStart())
{
using (new TransactionScope())
{
cache[1] = 2;
} // Revert transaction scope.
tx.Commit(); // Commit manual tx.
}
Assert.AreEqual(2, cache[1]);
}
/// <summary>
/// Test Ignite transaction with <see cref="TransactionScopeOption.Suppress"/> option.
/// </summary>
[Test]
public void TestSuppressedTransactionScope()
{
var cache = Cache();
cache[1] = 1;
using (new TransactionScope(TransactionScopeOption.Suppress))
{
cache[1] = 2;
}
// Even though transaction is not completed, the value is updated, because tx is suppressed.
Assert.AreEqual(2, cache[1]);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/> with nested scopes.
/// </summary>
[Test]
public void TestNestedTransactionScope()
{
var cache = Cache();
cache[1] = 1;
foreach (var option in new[] {TransactionScopeOption.Required, TransactionScopeOption.RequiresNew})
{
// Commit.
using (var ts1 = new TransactionScope())
{
using (var ts2 = new TransactionScope(option))
{
cache[1] = 2;
ts2.Complete();
}
cache[1] = 3;
ts1.Complete();
}
Assert.AreEqual(3, cache[1]);
// Rollback.
using (new TransactionScope())
{
using (new TransactionScope(option))
cache[1] = 4;
cache[1] = 5;
}
// In case with Required option there is a single tx
// that gets aborted, second put executes outside the tx.
Assert.AreEqual(option == TransactionScopeOption.Required ? 5 : 3, cache[1], option.ToString());
}
}
/// <summary>
/// Test that ambient <see cref="TransactionScope"/> options propagate to Ignite transaction.
/// </summary>
[Test]
public void TestTransactionScopeOptions()
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
var modes = new[]
{
Tuple.Create(IsolationLevel.Serializable, TransactionIsolation.Serializable),
Tuple.Create(IsolationLevel.RepeatableRead, TransactionIsolation.RepeatableRead),
Tuple.Create(IsolationLevel.ReadCommitted, TransactionIsolation.ReadCommitted),
Tuple.Create(IsolationLevel.ReadUncommitted, TransactionIsolation.ReadCommitted),
Tuple.Create(IsolationLevel.Snapshot, TransactionIsolation.ReadCommitted),
Tuple.Create(IsolationLevel.Chaos, TransactionIsolation.ReadCommitted),
};
foreach (var mode in modes)
{
using (new TransactionScope(TransactionScopeOption.Required, new TransactionOptions
{
IsolationLevel = mode.Item1
}))
{
cache[1] = 1;
var tx = transactions.Tx;
Assert.AreEqual(mode.Item2, tx.Isolation);
Assert.AreEqual(transactions.DefaultTransactionConcurrency, tx.Concurrency);
}
}
}
/// <summary>
/// Tests all transactional operations with <see cref="TransactionScope"/>.
/// </summary>
[Test]
public void TestTransactionScopeAllOperations()
{
for (var i = 0; i < 10; i++)
{
CheckTxOp((cache, key) => cache.Put(key, -5));
CheckTxOp((cache, key) => cache.PutAsync(key, -5));
CheckTxOp((cache, key) => cache.PutAll(new Dictionary<int, int> {{key, -7}}));
CheckTxOp((cache, key) => cache.PutAllAsync(new Dictionary<int, int> {{key, -7}}));
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.PutIfAbsent(key, -10);
});
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.PutIfAbsentAsync(key, -10);
});
CheckTxOp((cache, key) => cache.GetAndPut(key, -9));
CheckTxOp((cache, key) => cache.GetAndPutAsync(key, -9));
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.GetAndPutIfAbsent(key, -10);
});
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.GetAndPutIfAbsentAsync(key, -10);
});
CheckTxOp((cache, key) => cache.GetAndRemove(key));
CheckTxOp((cache, key) => cache.GetAndRemoveAsync(key));
CheckTxOp((cache, key) => cache.GetAndReplace(key, -11));
CheckTxOp((cache, key) => cache.GetAndReplaceAsync(key, -11));
CheckTxOp((cache, key) => cache.Invoke(key, new AddProcessor(), 1));
CheckTxOp((cache, key) => cache.InvokeAsync(key, new AddProcessor(), 1));
CheckTxOp((cache, key) => cache.InvokeAll(new[] {key}, new AddProcessor(), 1));
CheckTxOp((cache, key) => cache.InvokeAllAsync(new[] {key}, new AddProcessor(), 1));
CheckTxOp((cache, key) => cache.Remove(key));
CheckTxOp((cache, key) => cache.RemoveAsync(key));
CheckTxOp((cache, key) => cache.RemoveAll(new[] {key}));
CheckTxOp((cache, key) => cache.RemoveAllAsync(new[] {key}));
CheckTxOp((cache, key) => cache.Replace(key, 100));
CheckTxOp((cache, key) => cache.ReplaceAsync(key, 100));
CheckTxOp((cache, key) => cache.Replace(key, cache[key], 100));
CheckTxOp((cache, key) => cache.ReplaceAsync(key, cache[key], 100));
}
}
/// <summary>
/// Checks that cache operation behaves transactionally.
/// </summary>
private void CheckTxOp(Action<ICache<int, int>, int> act)
{
var isolationLevels = new[]
{
IsolationLevel.Serializable, IsolationLevel.RepeatableRead, IsolationLevel.ReadCommitted,
IsolationLevel.ReadUncommitted, IsolationLevel.Snapshot, IsolationLevel.Chaos
};
foreach (var isolationLevel in isolationLevels)
{
var txOpts = new TransactionOptions {IsolationLevel = isolationLevel};
const TransactionScopeOption scope = TransactionScopeOption.Required;
var cache = Cache();
cache[1] = 1;
cache[2] = 2;
// Rollback.
using (new TransactionScope(scope, txOpts))
{
act(cache, 1);
Assert.IsNotNull(cache.Ignite.GetTransactions().Tx, "Transaction has not started.");
}
Assert.AreEqual(1, cache[1]);
Assert.AreEqual(2, cache[2]);
using (new TransactionScope(scope, txOpts))
{
act(cache, 1);
act(cache, 2);
}
Assert.AreEqual(1, cache[1]);
Assert.AreEqual(2, cache[2]);
// Commit.
using (var ts = new TransactionScope(scope, txOpts))
{
act(cache, 1);
ts.Complete();
}
Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1);
Assert.AreEqual(2, cache[2]);
using (var ts = new TransactionScope(scope, txOpts))
{
act(cache, 1);
act(cache, 2);
ts.Complete();
}
Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1);
Assert.IsTrue(!cache.ContainsKey(2) || cache[2] != 2);
}
}
[Serializable]
private class AddProcessor : ICacheEntryProcessor<int, int, int, int>
{
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value += arg;
return arg;
}
}
}
}
| |
#region license
// Copyright (C) 2017 Mikael Egevig ([email protected]). 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 disclaimer below.
// * 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 Mikael Egevig nor the names of its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
/** \file
* Defines the \c Writer class, which handles rewriting an extended grammar in its simple form.
*/
using Org.Oakie.Gardener.Diction;
namespace Org.Oakie.Gardener.Writers.Standard
{
public class Writer: Org.Oakie.Gardener.Diction.Visitor
{
Org.Oakie.Gardener.Library.Rewriter _writer;
public Writer(Org.Oakie.Gardener.Library.Rewriter writer)
{
_writer = writer;
}
/**
* Transforms an extended notation alternation node into the equivalent basic notation:
*
* X = A (B | C) D
*
* Becomes:
*
* X = A T001 D
* T001 = B
* T001 = C
*/
public object Visit(AlternationNode that)
{
// Output this node in BNF form:
// T001 -> A
// T001 -> B
// T001 -> C
string id = _writer.NextName();
// Substitute node children with "T001".
_writer.Write(" ");
_writer.Write(id);
// Create each T001 rule.
foreach (Node below in that.Below)
{
_writer.Enter(id);
_writer.Write(id);
_writer.Write(" =");
below.Visit(this);
_writer.Leave(id);
}
return null;
}
/**
* Transforms an extended notation alternation node into the equivalent basic notation:
*
* X = A *B C
*
* Becomes:
*
* X = A T C
* T = B T
* T =
*/
public object Visit(ClosureNode that)
{
// Output this node in BNF form:
// X *(A B C) Y -> X R0001 Y
// R0001 -> %
// R0001 -> A B C R0001
string id = _writer.NextName();
// Substitute children with "R0001".
_writer.Write(" ");
_writer.Write(id);
// Create first R0001 rule.
_writer.Enter(id);
_writer.Write(id);
_writer.Write(" = %");
_writer.Leave(id);
// Create second R0001 rule.
_writer.Enter(id);
_writer.Write(id);
_writer.Write(" =");
foreach (Node below in that.Below)
below.Visit(this);
_writer.Write(" ");
_writer.Write(id);
_writer.Leave(id);
return null;
}
public object Visit(EndOfFileNode that)
{
// Do nothing as end-of-file is implicit in the fact that the start production is finite in length.
return null;
}
public object Visit(GrammarNode that)
{
// Output the commands from the input grammar without changes.
// ... Output the %start command.
_writer.Enter("start");
_writer.Write("%start " + that.Start);
_writer.Leave("start");
// ... Output the %token command(s).
foreach (string key in that.Tokens.Keys)
{
_writer.Enter(key);
_writer.Write("%token " + key + " " + that.Tokens[key]);
_writer.Leave(key);
}
// Output the productions of the input grammar (while transforming them).
foreach (Node production in that.Below)
production.Visit(this);
return null;
}
/**
* Transforms an extended notation lambda/epsilon node into the equivalent basic notation:
*
* %
*
* Becomes:
*
* %
*
* :-)
*/
public object Visit(LambdaNode that)
{
_writer.Write(" %");
return null;
}
public object Visit(NonterminalNode that)
{
// Output this node in BNF format.
foreach (Node below in that.Below)
below.Visit(this);
return null;
}
public object Visit(OptionNode that)
{
// Output this node in BNF form:
// X ?(A B C) Y -> X R0001 Y
// R0001 -> %
// R0001 -> A B C
string id = _writer.NextName();
// Substitute node children with "R0001".
_writer.Write(" ");
_writer.Write(id);
// Create first R0001 rule.
_writer.Enter(id);
_writer.Write(id);
_writer.Write(" = %");
_writer.Leave(id);
// Create second R0001 rule.
_writer.Enter(id);
_writer.Write(id);
_writer.Write(" =");
foreach (Node below in that.Below)
below.Visit(this);
_writer.Leave(id);
return null;
}
public object Visit(ReferenceNode that)
{
// Output this node in BNF format:
// A
_writer.Write(" ");
_writer.Write(that.Name);
return null;
}
public object Visit(RepetitionNode that)
{
// Output this node in BNF form:
// ? = X +(A B C) Y =>
// ? = X R0001 R0002 Y
// R0001 -> A B C
// R0002 -> %
// R0002 -> R0001 R0002
string id1 = _writer.NextName();
string id2 = _writer.NextName();
// Substitute children with "R0001 R0002".
_writer.Write(" ");
_writer.Write(id1);
_writer.Write(" ");
_writer.Write(id2);
// Create first R0001 rule.
_writer.Enter(id1);
_writer.Write(id1);
_writer.Write(" =");
foreach (Node below in that.Below)
below.Visit(this);
_writer.Leave(id1);
// Create first R0002 rule.
_writer.Enter(id2);
_writer.Write(id2);
_writer.Write(" = %");
_writer.Leave(id2);
// Create second R0002 rule.
_writer.Enter(id2);
_writer.Write(id2 + " = " + id1 + " " + id2);
_writer.Leave(id2);
return null;
}
public object Visit(ProductionNode that)
{
_writer.Enter(that.Name);
_writer.Write(that.Name);
_writer.Write(" =");
foreach (Node below in that.Below)
below.Visit(this);
_writer.Leave(that.Name);
return null;
}
public object Visit(SequenceNode that)
{
foreach (Node below in that.Below)
below.Visit(this);
return null;
}
public object Visit(TerminalNode that)
{
_writer.Write(" ");
if (that.Code == 0)
_writer.Write("\"");
_writer.Write(that.Name);
if (that.Code == 0)
_writer.Write("\"");
return null;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ReplaceMethodWithProperty
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = nameof(ReplaceMethodWithPropertyCodeRefactoringProvider)), Shared]
internal class ReplaceMethodWithPropertyCodeRefactoringProvider : CodeRefactoringProvider
{
private const string GetPrefix = "Get";
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
var service = document.GetLanguageService<IReplaceMethodWithPropertyService>();
if (service == null)
{
return;
}
var cancellationToken = context.CancellationToken;
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var position = context.Span.Start;
var token = root.FindToken(position);
if (!token.Span.Contains(context.Span))
{
return;
}
var methodDeclaration = service.GetMethodDeclaration(token);
if (methodDeclaration == null)
{
return;
}
// Ok, we're in the signature of the method. Now see if the method is viable to be
// replaced with a property.
var methodName = service.GetMethodName(methodDeclaration);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration) as IMethodSymbol;
if (!IsValidGetMethod(methodSymbol))
{
return;
}
var hasGetPrefix = HasGetPrefix(methodName);
var propertyName = hasGetPrefix
? methodName.Substring(GetPrefix.Length)
: methodName;
var nameChanged = hasGetPrefix;
// Looks good!
context.RegisterRefactoring(new ReplaceMethodWithPropertyCodeAction(
string.Format(FeaturesResources.Replace_0_with_property, methodName),
c => ReplaceMethodsWithProperty(context.Document, propertyName, nameChanged, methodSymbol, setMethod: null, cancellationToken: c),
methodName));
// If this method starts with 'Get' see if there's an associated 'Set' method we could
// replace as well.
if (hasGetPrefix)
{
var setMethod = FindSetMethod(methodSymbol);
if (setMethod != null)
{
context.RegisterRefactoring(new ReplaceMethodWithPropertyCodeAction(
string.Format(FeaturesResources.Replace_0_and_1_with_property, methodName, setMethod.Name),
c => ReplaceMethodsWithProperty(context.Document, propertyName, nameChanged, methodSymbol, setMethod, cancellationToken: c),
methodName + "-get/set"));
}
}
}
private static bool HasGetPrefix(SyntaxToken identifier)
{
return HasGetPrefix(identifier.ValueText);
}
private static bool HasGetPrefix(string text)
{
return HasPrefix(text, GetPrefix);
}
private static bool HasPrefix(string text, string prefix)
{
return text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && text.Length > prefix.Length && !char.IsLower(text[prefix.Length]);
}
private IMethodSymbol FindSetMethod(IMethodSymbol getMethod)
{
var containingType = getMethod.ContainingType;
var setMethodName = "Set" + getMethod.Name.Substring(GetPrefix.Length);
var setMethod = containingType.GetMembers()
.OfType<IMethodSymbol>()
.Where(m => setMethodName.Equals(m.Name, StringComparison.OrdinalIgnoreCase))
.Where(m => IsValidSetMethod(m, getMethod))
.FirstOrDefault();
return setMethod;
}
private static bool IsValidGetMethod(IMethodSymbol getMethod)
{
return getMethod != null &&
getMethod.ContainingType != null &&
!getMethod.IsGenericMethod &&
!getMethod.IsAsync &&
getMethod.Parameters.Length == 0 &&
!getMethod.ReturnsVoid &&
getMethod.DeclaringSyntaxReferences.Length == 1;
}
private static bool IsValidSetMethod(IMethodSymbol setMethod, IMethodSymbol getMethod)
{
return IsValidSetMethod(setMethod) &&
setMethod.Parameters.Length == 1 &&
setMethod.Parameters[0].RefKind == RefKind.None &&
Equals(setMethod.Parameters[0].Type, getMethod.ReturnType) &&
setMethod.IsAbstract == getMethod.IsAbstract;
}
private static bool IsValidSetMethod(IMethodSymbol setMethod)
{
return setMethod != null &&
!setMethod.IsGenericMethod &&
!setMethod.IsAsync &&
setMethod.ReturnsVoid &&
setMethod.DeclaringSyntaxReferences.Length == 1;
}
private async Task<Solution> ReplaceMethodsWithProperty(
Document document,
string propertyName,
bool nameChanged,
IMethodSymbol getMethod,
IMethodSymbol setMethod,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var originalSolution = document.Project.Solution;
var getMethodReferences = await SymbolFinder.FindReferencesAsync(getMethod, originalSolution, cancellationToken).ConfigureAwait(false);
var setMethodReferences = setMethod == null
? SpecializedCollections.EmptyEnumerable<ReferencedSymbol>()
: await SymbolFinder.FindReferencesAsync(setMethod, originalSolution, cancellationToken).ConfigureAwait(false);
// Get the warnings we'd like to put at the definition site.
var definitionWarning = GetDefinitionIssues(getMethodReferences);
var getReferencesByDocument = getMethodReferences.SelectMany(r => r.Locations).ToLookup(loc => loc.Document);
var setReferencesByDocument = setMethodReferences.SelectMany(r => r.Locations).ToLookup(loc => loc.Document);
// References and definitions can overlap (for example, references to one method
// inside the definition of another). So we do a multi phase rewrite. We first
// rewrite all references to point at the property instead. Then we remove all
// the actual method definitions and replace them with the new properties.
var updatedSolution = originalSolution;
updatedSolution = await UpdateReferencesAsync(updatedSolution, propertyName, nameChanged, getReferencesByDocument, setReferencesByDocument, cancellationToken).ConfigureAwait(false);
updatedSolution = await ReplaceGetMethodsAndRemoveSetMethodsAsync(originalSolution, updatedSolution, propertyName, nameChanged, getMethodReferences, setMethodReferences, updateSetMethod: setMethod != null, cancellationToken: cancellationToken).ConfigureAwait(false);
return updatedSolution;
}
private async Task<Solution> UpdateReferencesAsync(Solution updatedSolution, string propertyName, bool nameChanged, ILookup<Document, ReferenceLocation> getReferencesByDocument, ILookup<Document, ReferenceLocation> setReferencesByDocument, CancellationToken cancellationToken)
{
var allReferenceDocuments = getReferencesByDocument.Concat(setReferencesByDocument).Select(g => g.Key).Distinct();
foreach (var referenceDocument in allReferenceDocuments)
{
cancellationToken.ThrowIfCancellationRequested();
updatedSolution = await UpdateReferencesInDocumentAsync(
propertyName, nameChanged, updatedSolution, referenceDocument,
getReferencesByDocument[referenceDocument],
setReferencesByDocument[referenceDocument],
cancellationToken).ConfigureAwait(false);
}
return updatedSolution;
}
private async Task<Solution> UpdateReferencesInDocumentAsync(
string propertyName,
bool nameChanged,
Solution updatedSolution,
Document originalDocument,
IEnumerable<ReferenceLocation> getReferences,
IEnumerable<ReferenceLocation> setReferences,
CancellationToken cancellationToken)
{
var root = await originalDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(root, originalDocument.Project.Solution.Workspace);
var service = originalDocument.GetLanguageService<IReplaceMethodWithPropertyService>();
ReplaceGetReferences(propertyName, nameChanged, getReferences, root, editor, service, cancellationToken);
ReplaceSetReferences(propertyName, nameChanged, setReferences, root, editor, service, cancellationToken);
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(originalDocument.Id, editor.GetChangedRoot());
return updatedSolution;
}
private static void ReplaceGetReferences(
string propertyName, bool nameChanged,
IEnumerable<ReferenceLocation> getReferences,
SyntaxNode root, SyntaxEditor editor,
IReplaceMethodWithPropertyService service,
CancellationToken cancellationToken)
{
if (getReferences != null)
{
foreach (var referenceLocation in getReferences)
{
cancellationToken.ThrowIfCancellationRequested();
var location = referenceLocation.Location;
var nameToken = root.FindToken(location.SourceSpan.Start);
if (referenceLocation.IsImplicit)
{
// Warn the user that we can't properly replace this method with a property.
editor.ReplaceNode(nameToken.Parent, nameToken.Parent.WithAdditionalAnnotations(
ConflictAnnotation.Create(FeaturesResources.Method_referenced_implicitly)));
}
else
{
service.ReplaceGetReference(editor, nameToken, propertyName, nameChanged);
}
}
}
}
private static void ReplaceSetReferences(
string propertyName, bool nameChanged,
IEnumerable<ReferenceLocation> setReferences,
SyntaxNode root, SyntaxEditor editor,
IReplaceMethodWithPropertyService service,
CancellationToken cancellationToken)
{
if (setReferences != null)
{
foreach (var referenceLocation in setReferences)
{
cancellationToken.ThrowIfCancellationRequested();
var location = referenceLocation.Location;
var nameToken = root.FindToken(location.SourceSpan.Start);
if (referenceLocation.IsImplicit)
{
// Warn the user that we can't properly replace this method with a property.
editor.ReplaceNode(nameToken.Parent, nameToken.Parent.WithAdditionalAnnotations(
ConflictAnnotation.Create(FeaturesResources.Method_referenced_implicitly)));
}
else
{
service.ReplaceSetReference(editor, nameToken, propertyName, nameChanged);
}
}
}
}
private async Task<Solution> ReplaceGetMethodsAndRemoveSetMethodsAsync(
Solution originalSolution,
Solution updatedSolution,
string propertyName,
bool nameChanged,
IEnumerable<ReferencedSymbol> getMethodReferences,
IEnumerable<ReferencedSymbol> setMethodReferences,
bool updateSetMethod,
CancellationToken cancellationToken)
{
var getDefinitionsByDocumentId = await GetDefinitionsByDocumentIdAsync(originalSolution, getMethodReferences, cancellationToken).ConfigureAwait(false);
var setDefinitionsByDocumentId = await GetDefinitionsByDocumentIdAsync(originalSolution, setMethodReferences, cancellationToken).ConfigureAwait(false);
var documentIds = getDefinitionsByDocumentId.Keys.Concat(setDefinitionsByDocumentId.Keys).Distinct();
foreach (var documentId in documentIds)
{
cancellationToken.ThrowIfCancellationRequested();
var getDefinitions = getDefinitionsByDocumentId[documentId];
var setDefinitions = setDefinitionsByDocumentId[documentId];
updatedSolution = await ReplaceGetMethodsAndRemoveSetMethodsAsync(
propertyName, nameChanged, updatedSolution, documentId, getDefinitions, setDefinitions, updateSetMethod, cancellationToken).ConfigureAwait(false);
}
return updatedSolution;
}
private async Task<Solution> ReplaceGetMethodsAndRemoveSetMethodsAsync(
string propertyName,
bool nameChanged,
Solution updatedSolution,
DocumentId documentId,
MultiDictionary<DocumentId, IMethodSymbol>.ValueSet originalGetDefinitions,
MultiDictionary<DocumentId, IMethodSymbol>.ValueSet originalSetDefinitions,
bool updateSetMethod,
CancellationToken cancellationToken)
{
var updatedDocument = updatedSolution.GetDocument(documentId);
var compilation = await updatedDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
// We've already gone and updated all references. So now re-resolve all the definitions
// in the current compilation to find their updated location.
var getSetPairs = await GetGetSetPairsAsync(
updatedSolution, compilation, documentId, originalGetDefinitions, updateSetMethod, cancellationToken).ConfigureAwait(false);
var service = updatedDocument.GetLanguageService<IReplaceMethodWithPropertyService>();
var semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(root, updatedSolution.Workspace);
// First replace all the get methods with properties.
foreach (var getSetPair in getSetPairs)
{
cancellationToken.ThrowIfCancellationRequested();
service.ReplaceGetMethodWithProperty(editor, semanticModel, getSetPair, propertyName, nameChanged);
}
// Then remove all the set methods.
foreach (var originalSetMethod in originalSetDefinitions)
{
cancellationToken.ThrowIfCancellationRequested();
var setMethod = GetSymbolInCurrentCompilation(compilation, originalSetMethod, cancellationToken);
var setMethodDeclaration = await GetMethodDeclarationAsync(setMethod, cancellationToken).ConfigureAwait(false);
var setMethodDocument = updatedSolution.GetDocument(setMethodDeclaration?.SyntaxTree);
if (setMethodDocument?.Id == documentId)
{
service.RemoveSetMethod(editor, setMethodDeclaration);
}
}
return updatedSolution.WithDocumentSyntaxRoot(documentId, editor.GetChangedRoot());
}
private async Task<List<GetAndSetMethods>> GetGetSetPairsAsync(
Solution updatedSolution,
Compilation compilation,
DocumentId documentId,
MultiDictionary<DocumentId, IMethodSymbol>.ValueSet originalDefinitions,
bool updateSetMethod,
CancellationToken cancellationToken)
{
var result = new List<GetAndSetMethods>();
foreach (var originalDefinition in originalDefinitions)
{
cancellationToken.ThrowIfCancellationRequested();
var getMethod = GetSymbolInCurrentCompilation(compilation, originalDefinition, cancellationToken);
if (IsValidGetMethod(getMethod))
{
var setMethod = updateSetMethod ? FindSetMethod(getMethod) : null;
var getMethodDeclaration = await GetMethodDeclarationAsync(getMethod, cancellationToken).ConfigureAwait(false);
var setMethodDeclaration = await GetMethodDeclarationAsync(setMethod, cancellationToken).ConfigureAwait(false);
if (getMethodDeclaration != null && updatedSolution.GetDocument(getMethodDeclaration.SyntaxTree)?.Id == documentId)
{
result.Add(new GetAndSetMethods(getMethod, setMethod, getMethodDeclaration, setMethodDeclaration));
}
}
}
return result;
}
private static TSymbol GetSymbolInCurrentCompilation<TSymbol>(Compilation compilation, TSymbol originalDefinition, CancellationToken cancellationToken)
where TSymbol : class, ISymbol
{
return originalDefinition.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).GetAnySymbol() as TSymbol;
}
private async Task<SyntaxNode> GetMethodDeclarationAsync(IMethodSymbol method, CancellationToken cancellationToken)
{
if (method == null)
{
return null;
}
Debug.Assert(method.DeclaringSyntaxReferences.Length == 1);
var reference = method.DeclaringSyntaxReferences[0];
return await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
}
private async Task<MultiDictionary<DocumentId, IMethodSymbol>> GetDefinitionsByDocumentIdAsync(
Solution originalSolution,
IEnumerable<ReferencedSymbol> referencedSymbols,
CancellationToken cancellationToken)
{
var result = new MultiDictionary<DocumentId, IMethodSymbol>();
foreach (var referencedSymbol in referencedSymbols)
{
cancellationToken.ThrowIfCancellationRequested();
var definition = referencedSymbol.Definition as IMethodSymbol;
if (definition?.DeclaringSyntaxReferences.Length > 0)
{
var syntax = await definition.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
if (syntax != null)
{
var document = originalSolution.GetDocument(syntax.SyntaxTree);
if (document != null)
{
result.Add(document.Id, definition);
}
}
}
}
return result;
}
private string GetDefinitionIssues(IEnumerable<ReferencedSymbol> getMethodReferences)
{
// TODO: add things to be concerned about here. For example:
// 1. If any of the referenced symbols are from metadata.
// 2. If a symbol is referenced implicitly.
// 3. if the methods have attributes on them.
return null;
}
private class ReplaceMethodWithPropertyCodeAction : CodeAction.SolutionChangeAction
{
public ReplaceMethodWithPropertyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution, string equivalenceKey)
: base(title, createChangedSolution, equivalenceKey)
{
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class tk2dSpritePickerPopup : EditorWindow
{
class PresentationParams
{
public int border = 12;
public int tileSep = 8;
public int labelHeight = 15;
public int labelOffset = 4;
public int scrollbarWidth = 16;
public int tileSizeMin = 32;
public int tileSizeMax = 512;
public int numTilesPerRow = 0;
public int tileHeight = 0;
public int tileWidth = 0;
public int numRows = 0;
int tileSizeInt = 128;
public Vector2 rectDims;
public void Update(int numTiles) {
tileSizeInt = TileSize;
int w = Screen.width - scrollbarWidth - border * 2;
numTilesPerRow = Mathf.Max((w + tileSep) / (tileSizeInt + tileSep), 1);
numRows = (numTiles + numTilesPerRow - 1) / numTilesPerRow;
tileWidth = tileSizeInt + tileSep;
tileHeight = tileSizeInt + tileSep + labelOffset + labelHeight;
rectDims = new Vector2(w, numRows * tileHeight + border * 2);
}
public int TileSize
{
get { return tk2dPreferences.inst.spriteThumbnailSize; }
set { tk2dPreferences.inst.spriteThumbnailSize = Mathf.Clamp(value, tileSizeMin, tileSizeMax); }
}
public int GetYForIndex(int index)
{
int tileSep = 8;
int labelHeight = 15;
int tileHeight = tileSizeInt + tileSep + labelOffset + labelHeight;
return tileHeight * (index / numTilesPerRow);
}
}
PresentationParams presentParams = new PresentationParams();
tk2dSpriteGuiUtility.SpriteChangedCallback callback = null;
object callbackData = null;
tk2dSpriteCollectionData spriteCollection = null;
List<tk2dSpriteDefinition> selectedDefinitions = new List<tk2dSpriteDefinition>();
string searchFilter = "";
int selectedIndex = -1;
bool makeSelectionVisible = false;
Vector2 scroll = Vector2.zero;
tk2dSpriteThumbnailCache spriteThumbnailRenderer = null;
tk2dSpriteDefinition SelectedDefinition
{
get {
for (int i = 0; i < selectedDefinitions.Count; ++i)
if (i == selectedIndex) return selectedDefinitions[i];
return null;
}
}
void OnEnable()
{
UpdateFilter();
}
void OnDestroy()
{
if (spriteThumbnailRenderer != null)
{
spriteThumbnailRenderer.Destroy();
spriteThumbnailRenderer = null;
}
tk2dGrid.Done();
}
void PerformSelection()
{
tk2dSpriteDefinition def = SelectedDefinition;
if (def != null)
{
int spriteIndex = -1;
for (int i = 0; i < spriteCollection.inst.spriteDefinitions.Length; ++i)
if (spriteCollection.inst.spriteDefinitions[i] == def)
spriteIndex = i;
if (spriteIndex != -1 && callback != null)
callback( spriteCollection, spriteIndex, callbackData );
}
}
void UpdateFilter()
{
if (spriteCollection == null)
{
selectedDefinitions.Clear();
}
else
{
tk2dSpriteDefinition selectedSprite = SelectedDefinition;
string s = searchFilter.ToLower();
if (s != "")
selectedDefinitions = (from d in spriteCollection.inst.spriteDefinitions where d.Valid && d.name.ToLower().IndexOf(s) != -1 orderby d.name select d).ToList();
else
selectedDefinitions = (from d in spriteCollection.inst.spriteDefinitions where d.Valid orderby d.name select d).ToList();
selectedIndex = -1;
for (int i = 0; i < selectedDefinitions.Count; ++i)
{
if (selectedSprite == selectedDefinitions[i])
{
selectedIndex = i;
break;
}
}
}
}
void HandleKeyboardShortcuts() {
Event ev = Event.current;
int numTilesPerRow = presentParams.numTilesPerRow;
int newSelectedIndex = selectedIndex;
if (ev.type == EventType.KeyDown)
{
switch (ev.keyCode)
{
case KeyCode.Escape:
if (searchFilter.Length > 0)
{
searchFilter = "";
UpdateFilter();
newSelectedIndex = selectedIndex; // avoid it doing any processing later
}
else
{
Close();
}
ev.Use();
break;
case KeyCode.Return:
{
PerformSelection();
ev.Use();
Close();
break;
}
case KeyCode.RightArrow: newSelectedIndex++;break;
case KeyCode.LeftArrow: newSelectedIndex--; break;
case KeyCode.DownArrow: if (newSelectedIndex + numTilesPerRow < selectedDefinitions.Count) newSelectedIndex += numTilesPerRow; break;
case KeyCode.UpArrow: if (newSelectedIndex - numTilesPerRow >= 0) newSelectedIndex -= numTilesPerRow; break;
case KeyCode.Home: newSelectedIndex = 0; break;
case KeyCode.End: newSelectedIndex = selectedDefinitions.Count - 1; break;
default:
return; // unused key
}
newSelectedIndex = Mathf.Clamp(newSelectedIndex, 0, selectedDefinitions.Count - 1);
if (newSelectedIndex != selectedIndex)
{
selectedIndex = newSelectedIndex;
ev.Use();
makeSelectionVisible = true;
}
}
}
void OnGUI()
{
HandleKeyboardShortcuts();
presentParams.Update(selectedDefinitions.Count);
if (makeSelectionVisible) {
scroll.y = presentParams.GetYForIndex(selectedIndex);
makeSelectionVisible = false;
}
GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height));
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
GUILayout.Label("Collection: ");
tk2dSpriteCollectionData newSpriteCollection = tk2dSpriteGuiUtility.SpriteCollectionList(spriteCollection);
if (newSpriteCollection != spriteCollection)
{
spriteCollection = newSpriteCollection;
searchFilter = "";
UpdateFilter();
}
GUILayout.Space(8);
string searchControlName = "tk2dSpritePickerSearch";
GUI.SetNextControlName(searchControlName);
string newSearchFilter = GUILayout.TextField(searchFilter, tk2dEditorSkin.ToolbarSearch, GUILayout.Width(140));
if (GUIUtility.keyboardControl == 0) {
GUI.FocusControl(searchControlName);
}
if (newSearchFilter != searchFilter)
{
searchFilter = newSearchFilter;
UpdateFilter();
}
if (searchFilter.Length > 0)
{
if (GUILayout.Button("", tk2dEditorSkin.ToolbarSearchClear, GUILayout.ExpandWidth(false)))
{
searchFilter = "";
UpdateFilter();
}
}
else
{
GUILayout.Label("", tk2dEditorSkin.ToolbarSearchRightCap);
}
GUILayout.FlexibleSpace();
presentParams.TileSize = (int)EditorGUILayout.Slider(presentParams.TileSize, presentParams.tileSizeMin, presentParams.tileSizeMax, GUILayout.Width(120));
GUILayout.EndHorizontal();
if (selectedIndex < 0 || selectedIndex >= selectedDefinitions.Count)
{
if (selectedDefinitions.Count == 0) selectedIndex = -1;
else selectedIndex = 0;
}
if (spriteCollection != null)
DrawSpriteCollection(spriteCollection);
GUILayout.EndArea();
}
void DrawSpriteCollection(tk2dSpriteCollectionData spriteCollection)
{
Event ev = Event.current;
int tileSize = presentParams.TileSize;
scroll = GUILayout.BeginScrollView(scroll);
Rect r = GUILayoutUtility.GetRect(presentParams.rectDims.x, presentParams.rectDims.y);
if (ev.type == EventType.MouseDown && ev.button == 0 && r.Contains(ev.mousePosition))
{
int selX = ((int)ev.mousePosition.x - presentParams.border) / presentParams.tileWidth;
int selY = ((int)ev.mousePosition.y - presentParams.border) / presentParams.tileHeight;
int selId = selY * presentParams.numTilesPerRow + selX;
if (selX < presentParams.numTilesPerRow && selY < presentParams.numRows) {
selectedIndex = Mathf.Clamp(selId, 0, selectedDefinitions.Count - 1);
Repaint();
}
if (ev.clickCount == 2)
{
PerformSelection();
Close();
}
ev.Use();
}
r.x += presentParams.border;
r.y += presentParams.border;
if (spriteThumbnailRenderer == null)
spriteThumbnailRenderer = new tk2dSpriteThumbnailCache();
int ix = 0;
float x = r.x;
float y = r.y;
int index = 0;
foreach (tk2dSpriteDefinition def in selectedDefinitions)
{
Rect spriteRect = new Rect(x, y, tileSize, tileSize);
tk2dGrid.Draw(spriteRect, Vector2.zero);
spriteThumbnailRenderer.DrawSpriteTextureInRect(spriteRect, def, Color.white);
Rect labelRect = new Rect(x, y + tileSize + presentParams.labelOffset, tileSize, presentParams.labelHeight);
if (selectedIndex == index)
{
GUI.Label(labelRect, "", tk2dEditorSkin.Selection);
}
GUI.Label(labelRect, def.name, EditorStyles.miniLabel);
if (++ix >= presentParams.numTilesPerRow)
{
ix = 0;
x = r.x;
y += presentParams.tileHeight;
}
else
{
x += presentParams.tileWidth;
}
index++;
}
GUILayout.EndScrollView();
}
void InitForSpriteInCollection(tk2dSpriteCollectionData sc, int spriteId)
{
spriteCollection = sc;
searchFilter = "";
UpdateFilter();
tk2dSpriteDefinition def = (spriteId >= 0 && spriteId < sc.Count) ? sc.inst.spriteDefinitions[spriteId] : null;
selectedIndex = -1;
for (int i = 0; i < selectedDefinitions.Count; ++i) {
if (selectedDefinitions[i] == def) {
selectedIndex = i;
break;
}
}
if (selectedIndex != -1) {
makeSelectionVisible = true;
}
}
public static void DoPickSprite(tk2dSpriteCollectionData spriteCollection, int spriteId, string title, tk2dSpriteGuiUtility.SpriteChangedCallback callback, object callbackData)
{
tk2dSpritePickerPopup popup = EditorWindow.GetWindow(typeof(tk2dSpritePickerPopup), true, title, true) as tk2dSpritePickerPopup;
popup.InitForSpriteInCollection(spriteCollection, spriteId);
popup.callback = callback;
popup.callbackData = callbackData;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.Resources;
using NuGet.VisualStudio.Resources;
namespace NuGet.VisualStudio
{
public class VsPackageManager : PackageManager, IVsPackageManager
{
private readonly ISharedPackageRepository _sharedRepository;
private readonly IDictionary<string, IProjectManager> _projects;
private readonly ISolutionManager _solutionManager;
private readonly IFileSystemProvider _fileSystemProvider;
private readonly IDeleteOnRestartManager _deleteOnRestartManager;
private readonly VsPackageInstallerEvents _packageEvents;
private bool _bindingRedirectEnabled = true;
private readonly IVsFrameworkMultiTargeting _frameworkMultiTargeting;
private bool _repositoryOperationPending;
public VsPackageManager(ISolutionManager solutionManager,
IPackageRepository sourceRepository,
IFileSystemProvider fileSystemProvider,
IFileSystem fileSystem,
ISharedPackageRepository sharedRepository,
IDeleteOnRestartManager deleteOnRestartManager,
VsPackageInstallerEvents packageEvents,
IVsFrameworkMultiTargeting frameworkMultiTargeting = null)
: base(sourceRepository, new DefaultPackagePathResolver(fileSystem), fileSystem, sharedRepository)
{
_solutionManager = solutionManager;
_sharedRepository = sharedRepository;
_packageEvents = packageEvents;
_fileSystemProvider = fileSystemProvider;
_deleteOnRestartManager = deleteOnRestartManager;
_frameworkMultiTargeting = frameworkMultiTargeting;
_projects = new Dictionary<string, IProjectManager>(StringComparer.OrdinalIgnoreCase);
}
public bool BindingRedirectEnabled
{
get { return _bindingRedirectEnabled; }
set { _bindingRedirectEnabled = value; }
}
internal void EnsureCached(Project project)
{
string projectUniqueName = project.GetUniqueName();
if (_projects.ContainsKey(projectUniqueName))
{
return;
}
_projects[projectUniqueName] = CreateProjectManager(project);
}
public virtual IProjectManager GetProjectManager(Project project)
{
EnsureCached(project);
IProjectManager projectManager;
bool projectExists = _projects.TryGetValue(project.GetUniqueName(), out projectManager);
Debug.Assert(projectExists, "Unknown project");
return projectManager;
}
private IProjectManager CreateProjectManager(Project project)
{
// Create the project system
IProjectSystem projectSystem = VsProjectSystemFactory.CreateProjectSystem(project, _fileSystemProvider);
var repository = new PackageReferenceRepository(projectSystem, project.GetProperName(), _sharedRepository);
// Ensure the logger is null while registering the repository
FileSystem.Logger = null;
Logger = null;
// Ensure that this repository is registered with the shared repository if it needs to be
repository.RegisterIfNecessary();
// The source repository of the project is an aggregate since it might need to look for all
// available packages to perform updates on dependent packages
var sourceRepository = CreateProjectManagerSourceRepository();
var projectManager = new ProjectManager(sourceRepository, PathResolver, projectSystem, repository);
// The package reference repository also provides constraints for packages (via the allowedVersions attribute)
projectManager.ConstraintProvider = repository;
return projectManager;
}
public void InstallPackage(
IEnumerable<Project> projects,
IPackage package,
IEnumerable<PackageOperation> operations,
bool ignoreDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener packageOperationEventListener)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
if (projects == null)
{
throw new ArgumentNullException("projects");
}
using (StartInstallOperation(package.Id, package.Version.ToString()))
{
ExecuteOperationsWithPackage(
projects,
package,
operations,
projectManager => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions),
logger,
packageOperationEventListener);
}
}
public virtual void InstallPackage(
IProjectManager projectManager,
string packageId,
SemanticVersion version,
bool ignoreDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
InstallPackage(projectManager, packageId, version, ignoreDependencies, allowPrereleaseVersions,
skipAssemblyReferences: false, logger: logger);
}
public void InstallPackage(
IProjectManager projectManager,
string packageId,
SemanticVersion version,
bool ignoreDependencies,
bool allowPrereleaseVersions,
bool skipAssemblyReferences,
ILogger logger)
{
try
{
InitializeLogger(logger, projectManager);
IPackage package = PackageRepositoryHelper.ResolvePackage(SourceRepository, LocalRepository, packageId, version, allowPrereleaseVersions);
using (StartInstallOperation(packageId, package.Version.ToString()))
{
if (skipAssemblyReferences)
{
package = new SkipAssemblyReferencesPackage(package);
}
RunSolutionAction(() =>
{
InstallPackage(
package,
projectManager != null ? projectManager.Project.TargetFramework : null,
ignoreDependencies,
allowPrereleaseVersions);
AddPackageReference(projectManager, package, ignoreDependencies, allowPrereleaseVersions);
});
}
}
finally
{
ClearLogger(projectManager);
}
}
public void InstallPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, bool ignoreDependencies,
bool allowPrereleaseVersions, ILogger logger)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
projectManager.DependencyVersion = DependencyVersion;
using (StartInstallOperation(package.Id, package.Version.ToString()))
{
ExecuteOperationsWithPackage(
projectManager,
package,
operations,
() => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions),
logger);
}
}
public void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies)
{
UninstallPackage(projectManager, packageId, version, forceRemove, removeDependencies, NullLogger.Instance);
}
public virtual void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies, ILogger logger)
{
EventHandler<PackageOperationEventArgs> uninstallingHandler =
(sender, e) => _packageEvents.NotifyUninstalling(e);
EventHandler<PackageOperationEventArgs> uninstalledHandler =
(sender, e) => _packageEvents.NotifyUninstalled(e);
try
{
InitializeLogger(logger, projectManager);
bool appliesToProject;
IPackage package = FindLocalPackage(projectManager,
packageId,
version,
CreateAmbiguousUninstallException,
out appliesToProject);
PackageUninstalling += uninstallingHandler;
PackageUninstalled += uninstalledHandler;
if (appliesToProject)
{
RemovePackageReference(projectManager, packageId, forceRemove, removeDependencies);
}
else
{
UninstallPackage(package, forceRemove, removeDependencies);
}
}
finally
{
PackageUninstalling -= uninstallingHandler;
PackageUninstalled -= uninstalledHandler;
ClearLogger(projectManager);
}
}
public void UpdatePackage(
IEnumerable<Project> projects,
IPackage package,
IEnumerable<PackageOperation> operations,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener packageOperationEventListener)
{
if (operations == null)
{
throw new ArgumentNullException("operations");
}
if (projects == null)
{
throw new ArgumentNullException("projects");
}
using (StartUpdateOperation(package.Id, package.Version.ToString()))
{
ExecuteOperationsWithPackage(
projects,
package,
operations,
projectManager => UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions),
logger,
packageOperationEventListener);
}
}
public virtual void UpdatePackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackage(projectManager,
packageId,
() => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger);
}
private void UpdatePackage(IProjectManager projectManager, string packageId, Action projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
try
{
InitializeLogger(logger, projectManager);
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
// Find the package we're going to update to
IPackage newPackage = resolvePackage();
if (newPackage != null && package.Version != newPackage.Version)
{
using (StartUpdateOperation(packageId, newPackage.Version.ToString()))
{
if (appliesToProject)
{
RunSolutionAction(projectAction);
}
else
{
// We might be updating a solution only package
UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions);
}
}
}
else
{
Logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId);
}
}
finally
{
ClearLogger(projectManager);
}
}
public void UpdatePackages(IProjectManager projectManager, IEnumerable<IPackage> packages, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
if (packages == null)
{
throw new ArgumentNullException("packages");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
using (StartUpdateOperation(packageId: null, packageVersion: null))
{
ExecuteOperationsWithPackage(
projectManager,
null,
operations,
() =>
{
foreach (var package in packages)
{
UpdatePackageReference(projectManager, package, updateDependencies, allowPrereleaseVersions);
}
},
logger);
}
}
public void UpdatePackage(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, versionSpec, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void UpdatePackage(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void UpdatePackages(bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(updateDependencies, safeUpdate: false, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener);
}
public void UpdatePackages(IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(projectManager, updateDependencies, safeUpdate: false, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger);
}
public void UpdateSolutionPackages(IEnumerable<IPackage> packages, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
if (packages == null)
{
throw new ArgumentNullException("packages");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
try
{
InitializeLogger(logger, null);
RunSolutionAction(() =>
{
// update all packages in the 'packages' folder
foreach (var operation in operations)
{
Execute(operation);
}
if (eventListener == null)
{
eventListener = NullPackageOperationEventListener.Instance;
}
foreach (Project project in _solutionManager.GetProjects())
{
IProjectManager projectManager = GetProjectManager(project);
var oldWhatIfValue = projectManager.WhatIf;
try
{
eventListener.OnBeforeAddPackageReference(project);
InitializeLogger(logger, projectManager);
foreach (var package in packages)
{
// only perform update when the local package exists and has smaller version than the new version
var localPackage = projectManager.LocalRepository.FindPackage(package.Id);
if (localPackage != null && localPackage.Version < package.Version)
{
UpdatePackageReference(projectManager, package, updateDependencies, allowPrereleaseVersions);
}
}
ClearLogger(projectManager);
}
catch (Exception ex)
{
eventListener.OnAddPackageReferenceError(project, ex);
}
finally
{
projectManager.WhatIf = oldWhatIfValue;
eventListener.OnAfterAddPackageReference(project);
}
}
});
}
finally
{
ClearLogger(null);
}
}
public void SafeUpdatePackages(IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(projectManager, updateDependencies, safeUpdate: true, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger);
}
public void SafeUpdatePackage(string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, GetSafeRange(projectManager, packageId), updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, GetSafeRange(packageId), allowPrereleaseVersions: false, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void SafeUpdatePackage(IProjectManager projectManager, string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackage(projectManager,
packageId,
() => UpdatePackageReference(projectManager, packageId, GetSafeRange(projectManager, packageId), updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, GetSafeRange(packageId), allowPrereleaseVersions: false, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger);
}
public void SafeUpdatePackages(bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(updateDependencies, safeUpdate: true, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener);
}
// Reinstall all packages in all projects
public void ReinstallPackages(
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener eventListener)
{
//1) Reinstall solution packages first
//2) On Each Project, call UninstallAllPackages(IProjectManager, Dictionary<Tuple<string, SemanticVersion>, bool>, out packagesInSourceRepository). And, create a dictionary <projectManager, packages>
//3) Append all packagesInSourceRepository into allPackagesInSourceRepository
//4) Call InstallWalker.ResolveOperations(allPackagesInSourceRepository, out IList<IPackage> packagesByDependencyOrder)
//5) Call for each entry in Dictionary<projectManager, packages>
// InitializeLogger, RunSolutionAction( call projectManager.AddPackageReference(IPackage, ..., ...)
// Change it to array so that the enumeration is not modified during enumeration to reinstall solution packages
var packages = LocalRepository.GetPackages().ToArray();
foreach (var package in packages)
{
if (!IsProjectLevel(package))
{
ReinstallSolutionPackage(package, updateDependencies, allowPrereleaseVersions, logger);
}
}
// Now, take care of project-level packages
var packagesInProject = new Dictionary<IProjectManager, HashSet<IPackage>>();
var verifiedPackagesInSourceRepository = new Dictionary<PackageName, IPackage>();
HashSet<IPackage> allPackagesToBeReinstalled = new HashSet<IPackage>();
// first uninstall all the packages from each project
RunActionOnProjects(
_solutionManager.GetProjects(),
project =>
{
IProjectManager projectManager = GetProjectManager(project);
HashSet<IPackage> packagesToBeReinstalled;
UninstallPackagesForReinstall(projectManager, updateDependencies, logger, verifiedPackagesInSourceRepository, out packagesToBeReinstalled);
Debug.Assert(!packagesInProject.ContainsKey(projectManager));
packagesInProject[projectManager] = packagesToBeReinstalled;
allPackagesToBeReinstalled.AddRange(packagesToBeReinstalled);
},
logger,
eventListener ?? NullPackageOperationEventListener.Instance);
// NOTE THAT allowPrereleaseVersions should be true for pre-release packages alone, even if the user did not specify it
// since we are trying to reinstall packages here. However, ResolveOperations below will take care of this problem via allowPrereleaseVersionsBasedOnPackage parameter
var installWalker = new InstallWalker(LocalRepository, SourceRepository, null, logger ?? NullLogger.Instance,
ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions,
dependencyVersion: DependencyVersion);
IList<IPackage> packagesUninstalledInDependencyOrder;
var operations = installWalker.ResolveOperations(allPackagesToBeReinstalled, out packagesUninstalledInDependencyOrder, allowPrereleaseVersionsBasedOnPackage: true);
ExecuteOperationsWithPackage(
_solutionManager.GetProjects(),
null,
operations,
projectManager =>
{
foreach (var package in packagesUninstalledInDependencyOrder)
{
HashSet<IPackage> packagesToBeReinstalled;
if (packagesInProject.TryGetValue(projectManager, out packagesToBeReinstalled) && packagesToBeReinstalled.Contains(package))
{
AddPackageReference(projectManager, package, ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions || !package.IsReleaseVersion());
}
}
},
logger,
eventListener);
}
// Reinstall all packages in the specified project
public void ReinstallPackages(
IProjectManager projectManager,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
//1) Call UninstallPackagesForReinstall(IProjectManager, Empty Dictionary, out packagesUninstalledForReinstallation)
//2) Call InstallWalker.ResolveOperations(packagesInSourceRepository, out IList<IPackage> packagesByDependencyOrder)
//3) Call ExecuteOperationsWithPackage( call projectManager.AddPackageReference(IPackage, ..., ...)
HashSet<IPackage> packagesToBeReinstalled;
UninstallPackagesForReinstall(projectManager, updateDependencies, logger, new Dictionary<PackageName, IPackage>(), out packagesToBeReinstalled);
// NOTE THAT allowPrereleaseVersions should be true for pre-release packages alone, even if the user did not specify it
// since we are trying to reinstall packages here. However, ResolveOperations below will take care of this problem via allowPrereleaseVersionsBasedOnPackage parameter
var installWalker = new InstallWalker(projectManager.LocalRepository, SourceRepository, projectManager.Project.TargetFramework, logger ?? NullLogger.Instance,
ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions,
dependencyVersion: DependencyVersion);
IList<IPackage> packagesUninstalledInDependencyOrder;
var operations = installWalker.ResolveOperations(packagesToBeReinstalled, out packagesUninstalledInDependencyOrder, allowPrereleaseVersionsBasedOnPackage: true);
ExecuteOperationsWithPackage(
projectManager,
null,
operations,
() =>
{
foreach (var package in packagesUninstalledInDependencyOrder)
{
AddPackageReference(projectManager, package, ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions || !package.IsReleaseVersion());
}
},
logger);
}
/// <summary>
/// Reinstall the specified package in all projects.
/// </summary>
public void ReinstallPackage(
string packageId,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener eventListener)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
if (appliesToProject)
{
ReinstallPackageToAllProjects(packageId, updateDependencies, allowPrereleaseVersions, logger, eventListener);
}
else
{
ReinstallSolutionPackage(package, updateDependencies, allowPrereleaseVersions, logger);
}
}
/// <summary>
/// Reinstall the specified package in the specified project.
/// </summary>
public void ReinstallPackage(
IProjectManager projectManager,
string packageId,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
if (appliesToProject)
{
ReinstallPackageInProject(projectManager, package, updateDependencies, allowPrereleaseVersions, logger);
}
else
{
ReinstallSolutionPackage(package, updateDependencies, allowPrereleaseVersions, logger);
}
}
/// <summary>
/// Reinstall the specified package in the specified project, taking care of logging too.
/// </summary>
private void ReinstallPackageInProject(
IProjectManager projectManager,
IPackage package,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
logger = logger ?? NullLogger.Instance;
IDisposable disposableAction = StartReinstallOperation(package.Id, package.Version.ToString());
try
{
InitializeLogger(logger, projectManager);
logger.Log(MessageLevel.Info, VsResources.ReinstallProjectPackage, package, projectManager.Project.ProjectName);
// Before we start reinstalling, need to make sure the package exists in the source repository.
// Otherwise, the package will be uninstalled and can't be reinstalled.
if (SourceRepository.Exists(package))
{
RunSolutionAction(
() =>
{
UninstallPackage(
projectManager,
package.Id,
package.Version,
forceRemove: true,
removeDependencies: updateDependencies,
logger: logger);
InstallPackage(
projectManager,
package.Id,
package.Version,
ignoreDependencies: !updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions || !package.IsReleaseVersion(),
logger: logger);
});
}
else
{
logger.Log(
MessageLevel.Warning,
VsResources.PackageRestoreSkipForProject,
package.GetFullName(),
projectManager.Project.ProjectName);
}
}
finally
{
ClearLogger(projectManager);
disposableAction.Dispose();
}
}
// Reinstall one package in all projects.
// We need to uninstall the package from all projects BEFORE
// reinstalling it back, so that the package will be refreshed from source repository.
private void ReinstallPackageToAllProjects(
string packageId,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener eventListener)
{
logger = logger ?? NullLogger.Instance;
eventListener = eventListener ?? NullPackageOperationEventListener.Instance;
var projectsHasPackage = new Dictionary<Project, SemanticVersion>();
var versionsChecked = new Dictionary<SemanticVersion, bool>();
// first uninstall from all projects that has the package installed
RunActionOnProjects(
_solutionManager.GetProjects(),
project =>
{
IProjectManager projectManager = GetProjectManager(project);
// find the package version installed in this project
IPackage projectPackage = projectManager.LocalRepository.FindPackage(packageId);
if (projectPackage != null)
{
bool packageExistInSource;
if (!versionsChecked.TryGetValue(projectPackage.Version, out packageExistInSource))
{
// version has not been checked, so check it here
packageExistInSource = SourceRepository.Exists(packageId, projectPackage.Version);
// mark the version as checked so that we don't have to check again if we
// encounter another project with the same version.
versionsChecked[projectPackage.Version] = packageExistInSource;
}
if (packageExistInSource)
{
// save the version installed in this project so that we can restore the correct version later
projectsHasPackage.Add(project, projectPackage.Version);
UninstallPackage(
projectManager,
packageId,
version: null,
forceRemove: true,
removeDependencies: updateDependencies,
logger: logger);
}
else
{
logger.Log(
MessageLevel.Warning,
VsResources.PackageRestoreSkipForProject,
projectPackage.GetFullName(),
project.Name);
}
}
},
logger,
eventListener);
// now reinstall back to all the affected projects
RunActionOnProjects(
projectsHasPackage.Keys,
project =>
{
var projectManager = GetProjectManager(project);
if (!projectManager.LocalRepository.Exists(packageId))
{
SemanticVersion oldVersion = projectsHasPackage[project];
using (StartReinstallOperation(packageId, oldVersion.ToString()))
{
InstallPackage(
projectManager,
packageId,
version: oldVersion,
ignoreDependencies: !updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions || !String.IsNullOrEmpty(oldVersion.SpecialVersion),
logger: logger);
}
}
},
logger,
eventListener);
}
private void UninstallPackagesForReinstall(
IProjectManager projectManager,
bool updateDependencies,
ILogger logger,
Dictionary<PackageName, IPackage> verifiedPackagesInSourceRepository,
out HashSet<IPackage> packagesToBeReinstalled)
{
packagesToBeReinstalled = new HashSet<IPackage>();
logger = logger ?? NullLogger.Instance;
try
{
InitializeLogger(logger, projectManager);
var packages = projectManager.LocalRepository.GetPackages().ToArray();
foreach(IPackage package in packages)
{
IDisposable disposableAction = StartReinstallOperation(package.Id, package.Version.ToString());
try
{
logger.Log(MessageLevel.Info, VsResources.ReinstallProjectPackage, package, projectManager.Project.ProjectName);
IPackage packageInSourceRepository;
PackageName packageName = new PackageName(package.Id, package.Version);
if (!verifiedPackagesInSourceRepository.TryGetValue(packageName, out packageInSourceRepository))
{
packageInSourceRepository = SourceRepository.FindPackage(package.Id, package.Version);
verifiedPackagesInSourceRepository[packageName] = packageInSourceRepository;
}
if (packageInSourceRepository != null)
{
packagesToBeReinstalled.Add(packageInSourceRepository);
RunSolutionAction(
() =>
{
// We set remove dependencies to false since we will remove all the packages anyways
UninstallPackage(
projectManager,
package.Id,
package.Version,
forceRemove: true,
removeDependencies: false,
logger: logger);
});
}
else
{
logger.Log(
MessageLevel.Warning,
VsResources.PackageRestoreSkipForProject,
package.GetFullName(),
projectManager.Project.ProjectName);
}
}
catch (PackageNotInstalledException e)
{
logger.Log(MessageLevel.Warning, ExceptionUtility.Unwrap(e).Message);
}
catch (Exception e)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message);
}
finally
{
ClearLogger(projectManager);
disposableAction.Dispose();
}
}
}
finally
{
ClearLogger(projectManager);
}
}
private static PackageAction ReverseAction(PackageAction packageAction)
{
return packageAction == PackageAction.Install ?
PackageAction.Uninstall :
PackageAction.Install;
}
private void ReinstallSolutionPackage(
IPackage package,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
logger = logger ?? NullLogger.Instance;
var disposableAction = StartReinstallOperation(package.Id, package.Version.ToString());
try
{
InitializeLogger(logger);
logger.Log(MessageLevel.Info, VsResources.ReinstallSolutionPackage, package);
if (SourceRepository.Exists(package))
{
RunSolutionAction(
() =>
{
UninstallPackage(package, forceRemove: true, removeDependencies: !updateDependencies);
// Bug 2883: We must NOT use the overload that accepts 'package' object here,
// because after the UninstallPackage() call above, the package no longer exists.
InstallPackage(package.Id, package.Version, ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions || !package.IsReleaseVersion());
});
}
else
{
logger.Log(
MessageLevel.Warning,
VsResources.PackageRestoreSkipForSolution,
package.GetFullName());
}
}
finally
{
ClearLogger();
disposableAction.Dispose();
}
}
protected override void ExecuteUninstall(IPackage package)
{
// Check if the package is in use before removing it
if (!_sharedRepository.IsReferenced(package.Id, package.Version))
{
base.ExecuteUninstall(package);
}
}
private IPackage FindLocalPackageForUpdate(IProjectManager projectManager, string packageId, out bool appliesToProject)
{
return FindLocalPackage(projectManager, packageId, null /* version */, CreateAmbiguousUpdateException, out appliesToProject);
}
private IPackage FindLocalPackage(IProjectManager projectManager,
string packageId,
SemanticVersion version,
Func<IProjectManager, IList<IPackage>, Exception> getAmbiguousMatchException,
out bool appliesToProject)
{
IPackage package = null;
bool existsInProject = false;
appliesToProject = false;
if (projectManager != null)
{
// Try the project repository first
package = projectManager.LocalRepository.FindPackage(packageId, version);
existsInProject = package != null;
}
// Fallback to the solution repository (it might be a solution only package)
if (package == null)
{
if (version != null)
{
// Get the exact package
package = LocalRepository.FindPackage(packageId, version);
}
else
{
// Get all packages by this name to see if we find an ambiguous match
var packages = LocalRepository.FindPackagesById(packageId).ToList();
if (packages.Count > 1)
{
throw getAmbiguousMatchException(projectManager, packages);
}
// Pick the only one of default if none match
package = packages.SingleOrDefault();
}
}
// Can't find the package in the solution or in the project then fail
if (package == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackage, packageId));
}
appliesToProject = IsProjectLevel(package);
if (appliesToProject)
{
if (!existsInProject)
{
if (_sharedRepository.IsReferenced(package.Id, package.Version))
{
// If the package doesn't exist in the project and is referenced by other projects
// then fail.
if (projectManager != null)
{
if (version == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
package.Id,
projectManager.Project.ProjectName));
}
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
package.GetFullName(),
projectManager.Project.ProjectName));
}
}
else
{
// The operation applies to solution level since it's not installed in the current project
// but it is installed in some other project
appliesToProject = false;
}
}
}
// Can't have a project level operation if no project was specified
if (appliesToProject && projectManager == null)
{
throw new InvalidOperationException(VsResources.ProjectNotSpecified);
}
return package;
}
internal IPackage FindLocalPackage(string packageId, out bool appliesToProject)
{
// It doesn't matter if there are multiple versions of the package installed at solution level,
// we just want to know that one exists.
var packages = LocalRepository.FindPackagesById(packageId).OrderByDescending(p => p.Version).ToList();
// Can't find the package in the solution.
if (!packages.Any())
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackage, packageId));
}
foreach (IPackage package in packages)
{
appliesToProject = IsProjectLevel(package);
if (!appliesToProject)
{
if (packages.Count > 1)
{
throw CreateAmbiguousUpdateException(projectManager: null, packages: packages);
}
}
else if (!_sharedRepository.IsReferenced(package.Id, package.Version))
{
Logger.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture,
VsResources.Warning_PackageNotReferencedByAnyProject, package.Id, package.Version));
// Try next package
continue;
}
// Found a package with package Id as 'packageId' which is installed in at least 1 project
return package;
}
// There are one or more packages with package Id as 'packageId'
// BUT, none of them is installed in a project
// it's probably a borked install.
throw new PackageNotInstalledException(
String.Format(CultureInfo.CurrentCulture,
VsResources.PackageNotInstalledInAnyProject, packageId));
}
/// <summary>
/// Check to see if this package applies to a project based on 2 criteria:
/// 1. The package has project content (i.e. content that can be applied to a project lib or content files)
/// 2. The package is referenced by any other project
/// 3. The package has at least one dependecy
///
/// This logic will probably fail in one edge case. If there is a meta package that applies to a project
/// that ended up not being installed in any of the projects and it only exists at solution level.
/// If this happens, then we think that the following operation applies to the solution instead of showing an error.
/// To solve that edge case we'd have to walk the graph to find out what the package applies to.
///
/// Technically, the third condition is not totally accurate because a solution-level package can depend on another
/// solution-level package. However, doing that check here is expensive and we haven't seen such a package.
/// This condition here is more geared towards guarding against metadata packages, i.e. we shouldn't treat metadata packages
/// as solution-level ones.
/// </summary>
public bool IsProjectLevel(IPackage package)
{
return package.HasProjectContent() ||
package.DependencySets.SelectMany(p => p.Dependencies).Any() ||
_sharedRepository.IsReferenced(package.Id, package.Version);
}
private Exception CreateAmbiguousUpdateException(IProjectManager projectManager, IList<IPackage> packages)
{
if (projectManager != null && packages.Any(IsProjectLevel))
{
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
packages[0].Id,
projectManager.Project.ProjectName));
}
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousUpdate,
packages[0].Id));
}
private Exception CreateAmbiguousUninstallException(IProjectManager projectManager, IList<IPackage> packages)
{
if (projectManager != null && packages.Any(IsProjectLevel))
{
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousProjectLevelUninstal,
packages[0].Id,
projectManager.Project.ProjectName));
}
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousUninstall,
packages[0].Id));
}
private void RemovePackageReference(IProjectManager projectManager, string packageId, bool forceRemove, bool removeDependencies)
{
RunProjectAction(projectManager, () => projectManager.RemovePackageReference(packageId, forceRemove, removeDependencies));
}
// If the remote package is already determined, consider using the overload which directly takes in the remote package
// Can avoid calls FindPackage calls to source repository
private void UpdatePackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions)
{
string versionString = version == null ? null : version.ToString();
using (StartUpdateOperation(packageId, versionString))
{
RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, version, updateDependencies, allowPrereleaseVersions));
}
}
private void UpdatePackageReference(IProjectManager projectManager, string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions)
{
using (StartUpdateOperation(packageId, packageVersion: null))
{
RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, versionSpec, updateDependencies, allowPrereleaseVersions));
}
}
private void UpdatePackageReference(IProjectManager projectManager, IPackage package, bool updateDependencies, bool allowPrereleaseVersions)
{
using (StartUpdateOperation(package.Id, package.Version.ToString()))
{
RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(package, updateDependencies, allowPrereleaseVersions));
}
}
private void AddPackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.AddPackageReference(packageId, version, ignoreDependencies, allowPrereleaseVersions));
}
private void AddPackageReference(IProjectManager projectManager, IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions));
}
private void ExecuteOperationsWithPackage(IEnumerable<Project> projects, IPackage package, IEnumerable<PackageOperation> operations, Action<IProjectManager> projectAction, ILogger logger, IPackageOperationEventListener eventListener)
{
if (eventListener == null)
{
eventListener = NullPackageOperationEventListener.Instance;
}
ExecuteOperationsWithPackage(
null,
package,
operations,
() =>
{
bool successfulAtLeastOnce = false;
foreach (var project in projects)
{
try
{
eventListener.OnBeforeAddPackageReference(project);
IProjectManager projectManager = GetProjectManager(project);
InitializeLogger(logger, projectManager);
projectAction(projectManager);
successfulAtLeastOnce = true;
ClearLogger(projectManager);
}
catch (Exception ex)
{
eventListener.OnAddPackageReferenceError(project, ex);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
// Throw an exception only if all the update failed for all projects
// so we rollback any solution level operations that might have happened
if (projects.Any() && !successfulAtLeastOnce)
{
throw new InvalidOperationException(VsResources.OperationFailed);
}
},
logger);
}
private void ExecuteOperationsWithPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, Action action, ILogger logger)
{
try
{
InitializeLogger(logger, projectManager);
RunSolutionAction(() =>
{
if (operations.Any())
{
foreach (var operation in operations)
{
Execute(operation);
}
}
else if (package != null && LocalRepository.Exists(package))
{
Logger.Log(MessageLevel.Info, VsResources.Log_PackageAlreadyInstalled, package.GetFullName());
}
action();
});
}
finally
{
ClearLogger(projectManager);
}
}
private Project GetProject(IProjectManager projectManager)
{
// We only support project systems that implement IVsProjectSystem
var vsProjectSystem = projectManager.Project as IVsProjectSystem;
if (vsProjectSystem == null)
{
return null;
}
// Find the project by it's unique name
return _solutionManager.GetProject(vsProjectSystem.UniqueName);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "If we failed to add binding redirects we don't want it to stop the install/update.")]
private void AddBindingRedirects(IProjectManager projectManager)
{
// Find the project by it's unique name
Project project = GetProject(projectManager);
// If we can't find the project or it doesn't support binding redirects then don't add any redirects
if (project == null || !project.SupportsBindingRedirects())
{
return;
}
try
{
RuntimeHelpers.AddBindingRedirects(_solutionManager, project, _fileSystemProvider, _frameworkMultiTargeting);
}
catch (Exception e)
{
// If there was an error adding binding redirects then print a warning and continue
Logger.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, VsResources.Warning_FailedToAddBindingRedirects, projectManager.Project.ProjectName, e.Message));
}
}
private void InitializeLogger(ILogger logger, IProjectManager projectManager = null)
{
// Setup logging on all of our objects
Logger = logger;
FileSystem.Logger = logger;
if (projectManager != null)
{
projectManager.Logger = logger;
projectManager.Project.Logger = logger;
}
}
private void ClearLogger(IProjectManager projectManager = null)
{
// clear logging on all of our objects
Logger = null;
FileSystem.Logger = null;
if (projectManager != null)
{
projectManager.Logger = null;
projectManager.Project.Logger = null;
}
}
/// <summary>
/// Runs the specified action and rolls back any installed packages if on failure.
/// </summary>
private void RunSolutionAction(Action action)
{
var packagesAdded = new List<IPackage>();
EventHandler<PackageOperationEventArgs> installHandler = (sender, e) =>
{
// Record packages that we are installing so that if one fails, we can rollback
packagesAdded.Add(e.Package);
_packageEvents.NotifyInstalling(e);
};
EventHandler<PackageOperationEventArgs> installedHandler = (sender, e) =>
{
_packageEvents.NotifyInstalled(e);
};
PackageInstalling += installHandler;
PackageInstalled += installedHandler;
try
{
// Execute the action
action();
}
catch
{
if (packagesAdded.Any())
{
// Only print the rollback warning if we have something to rollback
Logger.Log(MessageLevel.Warning, VsResources.Warning_RollingBack);
}
// Don't log anything during the rollback
Logger = null;
// Rollback the install if it fails
Uninstall(packagesAdded);
throw;
}
finally
{
// Remove the event handler
PackageInstalling -= installHandler;
PackageInstalled -= installedHandler;
}
}
/// <summary>
/// Runs the action on projects and log any error that may occur.
/// </summary>
private void RunActionOnProjects(
IEnumerable<Project> projects,
Action<Project> action,
ILogger logger,
IPackageOperationEventListener eventListener)
{
foreach (var project in projects)
{
try
{
eventListener.OnBeforeAddPackageReference(project);
action(project);
}
catch (Exception exception)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(exception).Message);
eventListener.OnAddPackageReferenceError(project, exception);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
}
/// <summary>
/// Runs action on the project manager and rollsback any package installs if it fails.
/// </summary>
private void RunProjectAction(IProjectManager projectManager, Action action)
{
if (projectManager == null)
{
return;
}
// Keep track of what was added and removed
var packagesAdded = new Stack<IPackage>();
var packagesRemoved = new List<IPackage>();
EventHandler<PackageOperationEventArgs> removeHandler = (sender, e) =>
{
packagesRemoved.Add(e.Package);
_packageEvents.NotifyReferenceRemoved(e);
};
EventHandler<PackageOperationEventArgs> addingHandler = (sender, e) =>
{
packagesAdded.Push(e.Package);
_packageEvents.NotifyReferenceAdded(e);
// If this package doesn't exist at solution level (it might not be because of leveling)
// then we need to install it.
if (!LocalRepository.Exists(e.Package))
{
if (WhatIf)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_InstallPackage, e.Package);
}
else
{
ExecuteInstall(e.Package);
}
}
};
// Try to get the project for this project manager
Project project = GetProject(projectManager);
IVsProjectBuildSystem build = null;
if (project != null)
{
build = project.ToVsProjectBuildSystem();
}
// Add the handlers
projectManager.PackageReferenceRemoved += removeHandler;
projectManager.PackageReferenceAdding += addingHandler;
try
{
if (build != null)
{
// Start a batch edit so there is no background compilation until we're done
// processing project actions
build.StartBatchEdit();
}
action();
if (!WhatIf && BindingRedirectEnabled && projectManager.Project.IsBindingRedirectSupported)
{
// Only add binding redirects if install was successful
AddBindingRedirects(projectManager);
}
}
catch
{
// We need to Remove the handlers here since we're going to attempt
// a rollback and we don't want modify the collections while rolling back.
projectManager.PackageReferenceRemoved -= removeHandler;
projectManager.PackageReferenceAdding -= addingHandler;
// When things fail attempt a rollback
RollbackProjectActions(projectManager, packagesAdded, packagesRemoved);
// Rollback solution packages
Uninstall(packagesAdded);
// Clear removed packages so we don't try to remove them again (small optimization)
packagesRemoved.Clear();
throw;
}
finally
{
if (build != null)
{
// End the batch edit when we are done.
build.EndBatchEdit();
}
// Remove the handlers
projectManager.PackageReferenceRemoved -= removeHandler;
projectManager.PackageReferenceAdding -= addingHandler;
// Remove any packages that would be removed as a result of updating a dependency or the package itself
// We can execute the uninstall directly since we don't need to resolve dependencies again.
Uninstall(packagesRemoved);
}
}
private static void RollbackProjectActions(IProjectManager projectManager, IEnumerable<IPackage> packagesAdded, IEnumerable<IPackage> packagesRemoved)
{
// Disable logging when rolling back project operations
projectManager.Logger = null;
foreach (var package in packagesAdded)
{
// Remove each package that was added
projectManager.RemovePackageReference(package, forceRemove: false, removeDependencies: false);
}
foreach (var package in packagesRemoved)
{
// Add each package that was removed
projectManager.AddPackageReference(package, ignoreDependencies: true, allowPrereleaseVersions: true);
}
}
private void Uninstall(IEnumerable<IPackage> packages)
{
// Packages added to the sequence are added in the order in which they were visited. However for operations on satellite packages to work correctly,
// we need to ensure they are always uninstalled prior to the corresponding core package. To address this, we run it by Reduce which reorders it for us and ensures it
// returns the minimal set of operations required.
var packageOperations = packages.Select(p => new PackageOperation(p, PackageAction.Uninstall))
.Reduce();
foreach (var operation in packageOperations)
{
if (WhatIf)
{
Logger.Log(
MessageLevel.Info,
NuGet.Resources.NuGetResources.Log_UninstallPackage,
operation.Package);
}
else
{
ExecuteUninstall(operation.Package);
}
}
}
private void UpdatePackage(
string packageId,
Action<IProjectManager> projectAction,
Func<IPackage> resolvePackage,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener eventListener)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
if (appliesToProject)
{
eventListener = eventListener ?? NullPackageOperationEventListener.Instance;
foreach (var project in _solutionManager.GetProjects())
{
IProjectManager projectManager = GetProjectManager(project);
var oldWhatIfValue = projectManager.WhatIf;
try
{
InitializeLogger(logger, projectManager);
projectManager.WhatIf = WhatIf;
if (projectManager.LocalRepository.Exists(packageId))
{
eventListener.OnBeforeAddPackageReference(project);
try
{
RunSolutionAction(() => projectAction(projectManager));
}
catch (Exception e)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message);
eventListener.OnAddPackageReferenceError(project, e);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
}
finally
{
projectManager.WhatIf = oldWhatIfValue;
ClearLogger(projectManager);
}
}
}
else
{
// Find the package we're going to update to
IPackage newPackage = resolvePackage();
if (newPackage != null && package.Version != newPackage.Version)
{
IDisposable operationDisposable = StartUpdateOperation(newPackage.Id, newPackage.Version.ToString());
try
{
InitializeLogger(logger, projectManager: null);
// We might be updating a solution only package
UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions);
}
finally
{
ClearLogger(projectManager: null);
operationDisposable.Dispose();
}
}
else
{
logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId);
}
}
}
private void UpdatePackages(IProjectManager projectManager, bool updateDependencies, bool safeUpdate, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(projectManager.LocalRepository, package =>
{
if (safeUpdate)
{
SafeUpdatePackage(projectManager, package.Id, updateDependencies, allowPrereleaseVersions, logger);
}
else
{
UpdatePackage(projectManager, package.Id, version: null, updateDependencies: updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions, logger: logger);
}
}, logger);
}
private void UpdatePackages(bool updateDependencies, bool safeUpdate, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(LocalRepository, package =>
{
if (safeUpdate)
{
SafeUpdatePackage(package.Id, updateDependencies, allowPrereleaseVersions, logger, eventListener);
}
else
{
UpdatePackage(package.Id, version: null, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener);
}
},
logger);
}
private void UpdatePackages(IPackageRepository localRepository, Action<IPackage> updateAction, ILogger logger)
{
// BUGBUG: TargetFramework should be passed for more efficient package walking
var packageSorter = new PackageSorter(targetFramework: null);
// Get the packages in reverse dependency order then run update on each one i.e. if A -> B run Update(A) then Update(B)
var packages = packageSorter.GetPackagesByDependencyOrder(localRepository).Reverse();
foreach (var package in packages)
{
// While updating we might remove packages that were initially in the list. e.g.
// A 1.0 -> B 2.0, A 2.0 -> [], since updating to A 2.0 removes B, we end up skipping it.
if (localRepository.Exists(package.Id))
{
try
{
updateAction(package);
}
catch (PackageNotInstalledException e)
{
logger.Log(MessageLevel.Warning, ExceptionUtility.Unwrap(e).Message);
}
catch (Exception e)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message);
}
}
}
}
private IPackageRepository CreateProjectManagerSourceRepository()
{
// The source repo for the project manager is the aggregate of the shared repo and the selected repo.
// For dependency resolution, we want VS to look for packages in the selected source and then use the fallback logic
var fallbackRepository = SourceRepository as FallbackRepository;
if (fallbackRepository != null)
{
var primaryRepositories = new[] { _sharedRepository, fallbackRepository.SourceRepository.Clone() };
return new FallbackRepository(new AggregateRepository(primaryRepositories), fallbackRepository.DependencyResolver);
}
return new AggregateRepository(new[] { _sharedRepository, SourceRepository.Clone() });
}
private IVersionSpec GetSafeRange(string packageId)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
return VersionUtility.GetSafeRange(package.Version);
}
private IVersionSpec GetSafeRange(IProjectManager projectManager, string packageId)
{
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
return VersionUtility.GetSafeRange(package.Version);
}
protected override void OnUninstalled(PackageOperationEventArgs e)
{
base.OnUninstalled(e);
_deleteOnRestartManager.MarkPackageDirectoryForDeletion(e.Package);
}
private IDisposable StartInstallOperation(string packageId, string packageVersion)
{
return StartOperation(RepositoryOperationNames.Install, packageId, packageVersion);
}
private IDisposable StartUpdateOperation(string packageId, string packageVersion)
{
return StartOperation(RepositoryOperationNames.Update, packageId, packageVersion);
}
private IDisposable StartReinstallOperation(string packageId, string packageVersion)
{
return StartOperation(RepositoryOperationNames.Reinstall, packageId, packageVersion);
}
private IDisposable StartOperation(string operation, string packageId, string mainPackageVersion)
{
// If there's a pending operation, don't allow another one to start.
// This is for the Reinstall case. Because Reinstall just means
// uninstalling and installing, we don't want the child install operation
// to override Reinstall value.
if (_repositoryOperationPending)
{
return DisposableAction.NoOp;
}
_repositoryOperationPending = true;
return DisposableAction.All(
SourceRepository.StartOperation(operation, packageId, mainPackageVersion),
new DisposableAction(() => _repositoryOperationPending = false));
}
}
}
| |
using J2N.Collections;
using System.Diagnostics;
using System.Reflection;
using JCG = J2N.Collections.Generic;
namespace YAF.Lucene.Net.Util.Fst
{
/*
* 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 PackedInt32s = YAF.Lucene.Net.Util.Packed.PackedInt32s;
using PagedGrowableWriter = YAF.Lucene.Net.Util.Packed.PagedGrowableWriter;
/// <summary>
/// Used to dedup states (lookup already-frozen states)
/// </summary>
internal sealed class NodeHash<T>
{
private PagedGrowableWriter table;
private long count;
private long mask;
private readonly FST<T> fst;
private readonly FST.Arc<T> scratchArc = new FST.Arc<T>();
private readonly FST.BytesReader input;
// LUCENENET specific - optimize the Hash methods
// by only calling StructuralEqualityComparer.GetHashCode() if the value is a reference type
private readonly static bool tIsValueType = typeof(T).GetTypeInfo().IsValueType;
public NodeHash(FST<T> fst, FST.BytesReader input)
{
table = new PagedGrowableWriter(16, 1 << 30, 8, PackedInt32s.COMPACT);
mask = 15;
this.fst = fst;
this.input = input;
}
private bool NodesEqual(Builder.UnCompiledNode<T> node, long address)
{
fst.ReadFirstRealTargetArc(address, scratchArc, input);
if (scratchArc.BytesPerArc != 0 && node.NumArcs != scratchArc.NumArcs)
{
return false;
}
for (int arcUpto = 0; arcUpto < node.NumArcs; arcUpto++)
{
Builder.Arc<T> arc = node.Arcs[arcUpto];
if (arc.IsFinal != scratchArc.IsFinal ||
arc.Label != scratchArc.Label ||
((Builder.CompiledNode)arc.Target).Node != scratchArc.Target ||
!(tIsValueType ? JCG.EqualityComparer<T>.Default.Equals(arc.Output, scratchArc.Output) : StructuralEqualityComparer.Default.Equals(arc.Output, scratchArc.Output)) ||
!(tIsValueType ? JCG.EqualityComparer<T>.Default.Equals(arc.NextFinalOutput, scratchArc.NextFinalOutput) : StructuralEqualityComparer.Default.Equals(arc.NextFinalOutput, scratchArc.NextFinalOutput))
)
{
return false;
}
if (scratchArc.IsLast)
{
if (arcUpto == node.NumArcs - 1)
{
return true;
}
else
{
return false;
}
}
fst.ReadNextRealArc(scratchArc, input);
}
return false;
}
/// <summary>
/// hash code for an unfrozen node. this must be identical
/// to the frozen case (below)!!
/// </summary>
private long Hash(Builder.UnCompiledNode<T> node)
{
const int PRIME = 31;
//System.out.println("hash unfrozen");
long h = 0;
// TODO: maybe if number of arcs is high we can safely subsample?
for (int arcIdx = 0; arcIdx < node.NumArcs; arcIdx++)
{
Builder.Arc<T> arc = node.Arcs[arcIdx];
h = PRIME * h + arc.Label;
long n = ((Builder.CompiledNode)arc.Target).Node;
h = PRIME * h + (int)(n ^ (n >> 32));
// LUCENENET specific - optimize the Hash methods
// by only calling StructuralEqualityComparer.GetHashCode() if the value is a reference type
h = PRIME * h + (tIsValueType ? JCG.EqualityComparer<T>.Default.GetHashCode(arc.Output) : StructuralEqualityComparer.Default.GetHashCode(arc.Output));
h = PRIME * h + (tIsValueType ? JCG.EqualityComparer<T>.Default.GetHashCode(arc.NextFinalOutput) : StructuralEqualityComparer.Default.GetHashCode(arc.NextFinalOutput));
if (arc.IsFinal)
{
h += 17;
}
}
//System.out.println(" ret " + (h&Integer.MAX_VALUE));
return h & long.MaxValue;
}
/// <summary>
/// hash code for a frozen node
/// </summary>
private long Hash(long node)
{
const int PRIME = 31;
//System.out.println("hash frozen node=" + node);
long h = 0;
fst.ReadFirstRealTargetArc(node, scratchArc, input);
while (true)
{
//System.out.println(" label=" + scratchArc.label + " target=" + scratchArc.target + " h=" + h + " output=" + fst.outputs.outputToString(scratchArc.output) + " next?=" + scratchArc.flag(4) + " final?=" + scratchArc.isFinal() + " pos=" + in.getPosition());
h = PRIME * h + scratchArc.Label;
h = PRIME * h + (int)(scratchArc.Target ^ (scratchArc.Target >> 32));
// LUCENENET specific - optimize the Hash methods
// by only calling StructuralEqualityComparer.Default.GetHashCode() if the value is a reference type
h = PRIME * h + (tIsValueType ? JCG.EqualityComparer<T>.Default.GetHashCode(scratchArc.Output) : StructuralEqualityComparer.Default.GetHashCode(scratchArc.Output));
h = PRIME * h + (tIsValueType ? JCG.EqualityComparer<T>.Default.GetHashCode(scratchArc.NextFinalOutput) : StructuralEqualityComparer.Default.GetHashCode(scratchArc.NextFinalOutput));
if (scratchArc.IsFinal)
{
h += 17;
}
if (scratchArc.IsLast)
{
break;
}
fst.ReadNextRealArc(scratchArc, input);
}
//System.out.println(" ret " + (h&Integer.MAX_VALUE));
return h & long.MaxValue;
}
public long Add(Builder.UnCompiledNode<T> nodeIn)
{
//System.out.println("hash: add count=" + count + " vs " + table.size() + " mask=" + mask);
long h = Hash(nodeIn);
long pos = h & mask;
int c = 0;
while (true)
{
long v = table.Get(pos);
if (v == 0)
{
// freeze & add
long node = fst.AddNode(nodeIn);
//System.out.println(" now freeze node=" + node);
long hashNode = Hash(node);
Debug.Assert(hashNode == h, "frozenHash=" + hashNode + " vs h=" + h);
count++;
table.Set(pos, node);
// Rehash at 2/3 occupancy:
if (count > 2 * table.Count / 3)
{
Rehash();
}
return node;
}
else if (NodesEqual(nodeIn, v))
{
// same node is already here
return v;
}
// quadratic probe
pos = (pos + (++c)) & mask;
}
}
/// <summary>
/// called only by rehash
/// </summary>
private void AddNew(long address)
{
long pos = Hash(address) & mask;
int c = 0;
while (true)
{
if (table.Get(pos) == 0)
{
table.Set(pos, address);
break;
}
// quadratic probe
pos = (pos + (++c)) & mask;
}
}
private void Rehash()
{
PagedGrowableWriter oldTable = table;
table = new PagedGrowableWriter(2 * oldTable.Count, 1 << 30, PackedInt32s.BitsRequired(count), PackedInt32s.COMPACT);
mask = table.Count - 1;
for (long idx = 0; idx < oldTable.Count; idx++)
{
long address = oldTable.Get(idx);
if (address != 0)
{
AddNew(address);
}
}
}
}
}
| |
using System;
using System.IO;
using System.Text;
namespace ForieroEngine.MIDIUnified.Midi
{
/// <summary>
/// Represents an individual MIDI event
/// </summary>
public class MidiEvent
{
/// <summary>The MIDI command code</summary>
private MidiCommandCode commandCode;
private int channel;
private int deltaTime;
private long absoluteTime;
/// <summary>
/// Creates a MidiEvent from a raw message received using
/// the MME MIDI In APIs
/// </summary>
/// <param name="rawMessage">The short MIDI message</param>
/// <returns>A new MIDI Event</returns>
public static MidiEvent FromRawMessage(int rawMessage)
{
long absoluteTime = 0;
int b = rawMessage & 0xFF;
int data1 = (rawMessage >> 8) & 0xFF;
int data2 = (rawMessage >> 16) & 0xFF;
MidiCommandCode commandCode;
int channel = 1;
if ((b & 0xF0) == 0xF0)
{
// both bytes are used for command code in this case
commandCode = (MidiCommandCode)b;
}
else
{
commandCode = (MidiCommandCode)(b & 0xF0);
channel = (b & 0x0F) + 1;
}
MidiEvent me;
switch (commandCode)
{
case MidiCommandCode.NoteOn:
case MidiCommandCode.NoteOff:
case MidiCommandCode.KeyAfterTouch:
if (data2 > 0 && commandCode == MidiCommandCode.NoteOn)
{
me = new NoteOnEvent(absoluteTime, channel, data1, data2, 0);
}
else
{
me = new NoteEvent(absoluteTime, channel, commandCode, data1, data2);
}
break;
case MidiCommandCode.ControlChange:
me = new ControlChangeEvent(absoluteTime,channel,(MidiController)data1,data2);
break;
case MidiCommandCode.PatchChange:
me = new PatchChangeEvent(absoluteTime,channel,data1);
break;
case MidiCommandCode.ChannelAfterTouch:
me = new ChannelAfterTouchEvent(absoluteTime,channel,data1);
break;
case MidiCommandCode.PitchWheelChange:
me = new PitchWheelChangeEvent(absoluteTime, channel, data1 + (data2 << 7));
break;
case MidiCommandCode.TimingClock:
case MidiCommandCode.StartSequence:
case MidiCommandCode.ContinueSequence:
case MidiCommandCode.StopSequence:
case MidiCommandCode.AutoSensing:
me = new MidiEvent(absoluteTime,channel,commandCode);
break;
case MidiCommandCode.MetaEvent:
case MidiCommandCode.Sysex:
default:
throw new FormatException(String.Format("Unsupported MIDI Command Code for Raw Message {0}", commandCode));
}
return me;
}
/// <summary>
/// Constructs a MidiEvent from a BinaryStream
/// </summary>
/// <param name="br">The binary stream of MIDI data</param>
/// <param name="previous">The previous MIDI event (pass null for first event)</param>
/// <returns>A new MidiEvent</returns>
public static MidiEvent ReadNextEvent(BinaryReader br, MidiEvent previous)
{
int deltaTime = MidiEvent.ReadVarInt(br);
MidiCommandCode commandCode;
int channel = 1;
byte b = br.ReadByte();
if((b & 0x80) == 0)
{
// a running command - command & channel are same as previous
commandCode = previous.CommandCode;
channel = previous.Channel;
br.BaseStream.Position--; // need to push this back
}
else
{
if((b & 0xF0) == 0xF0)
{
// both bytes are used for command code in this case
commandCode = (MidiCommandCode) b;
}
else
{
commandCode = (MidiCommandCode) (b & 0xF0);
channel = (b & 0x0F) + 1;
}
}
MidiEvent me;
switch(commandCode)
{
case MidiCommandCode.NoteOn:
me = new NoteOnEvent(br);
break;
case MidiCommandCode.NoteOff:
case MidiCommandCode.KeyAfterTouch:
me = new NoteEvent(br);
break;
case MidiCommandCode.ControlChange:
me = new ControlChangeEvent(br);
break;
case MidiCommandCode.PatchChange:
me = new PatchChangeEvent(br);
break;
case MidiCommandCode.ChannelAfterTouch:
me = new ChannelAfterTouchEvent(br);
break;
case MidiCommandCode.PitchWheelChange:
me = new PitchWheelChangeEvent(br);
break;
case MidiCommandCode.TimingClock:
case MidiCommandCode.StartSequence:
case MidiCommandCode.ContinueSequence:
case MidiCommandCode.StopSequence:
me = new MidiEvent();
break;
case MidiCommandCode.Sysex:
me = SysexEvent.ReadSysexEvent(br);
break;
case MidiCommandCode.MetaEvent:
me = MetaEvent.ReadMetaEvent(br);
break;
default:
throw new FormatException(String.Format("Unsupported MIDI Command Code {0:X2}",(byte) commandCode));
}
me.channel = channel;
me.deltaTime = deltaTime;
me.commandCode = commandCode;
return me;
}
/// <summary>
/// Converts this MIDI event to a short message (32 bit integer) that
/// can be sent by the Windows MIDI out short message APIs
/// Cannot be implemented for all MIDI messages
/// </summary>
/// <returns>A short message</returns>
public virtual int GetAsShortMessage()
{
return (channel - 1) + (int)commandCode;
}
/// <summary>
/// Default constructor
/// </summary>
protected MidiEvent()
{
}
/// <summary>
/// Creates a MIDI event with specified parameters
/// </summary>
/// <param name="absoluteTime">Absolute time of this event</param>
/// <param name="channel">MIDI channel number</param>
/// <param name="commandCode">MIDI command code</param>
public MidiEvent(long absoluteTime, int channel, MidiCommandCode commandCode)
{
this.absoluteTime = absoluteTime;
this.Channel = channel;
this.commandCode = commandCode;
}
/// <summary>
/// The MIDI Channel Number for this event (1-16)
/// </summary>
public virtual int Channel
{
get
{
return channel;
}
set
{
if ((value < 1) || (value > 16))
{
throw new ArgumentOutOfRangeException("value", value,
String.Format("Channel must be 1-16 (Got {0})",value));
}
channel = value;
}
}
/// <summary>
/// The Delta time for this event
/// </summary>
public int DeltaTime
{
get
{
return deltaTime;
}
}
/// <summary>
/// The absolute time for this event
/// </summary>
public long AbsoluteTime
{
get
{
return absoluteTime;
}
set
{
absoluteTime = value;
}
}
/// <summary>
/// The command code for this event
/// </summary>
public MidiCommandCode CommandCode
{
get
{
return commandCode;
}
}
/// <summary>
/// Data1
/// </summary>
public int Data1
{
get
{
return (GetAsShortMessage() >> 8) & 0xFF;
}
}
/// <summary>
/// Data2
/// </summary>
public int Data2
{
get
{
return (GetAsShortMessage() >> 16) & 0xFF;
}
}
/// <summary>
/// Whether this is a note off event
/// </summary>
public static bool IsNoteOff(MidiEvent midiEvent)
{
if (midiEvent != null)
{
if (midiEvent.CommandCode == MidiCommandCode.NoteOn)
{
NoteEvent ne = (NoteEvent)midiEvent;
return (ne.Velocity == 0);
}
return (midiEvent.CommandCode == MidiCommandCode.NoteOff);
}
return false;
}
/// <summary>
/// Whether this is a note on event
/// </summary>
public static bool IsNoteOn(MidiEvent midiEvent)
{
if (midiEvent != null)
{
if (midiEvent.CommandCode == MidiCommandCode.NoteOn)
{
NoteEvent ne = (NoteEvent)midiEvent;
return (ne.Velocity > 0);
}
}
return false;
}
/// <summary>
/// Determines if this is an end track event
/// </summary>
public static bool IsEndTrack(MidiEvent midiEvent)
{
if (midiEvent != null)
{
MetaEvent me = midiEvent as MetaEvent;
if (me != null)
{
return me.MetaEventType == MetaEventType.EndTrack;
}
}
return false;
}
/// <summary>
/// Displays a summary of the MIDI event
/// </summary>
/// <returns>A string containing a brief description of this MIDI event</returns>
public override string ToString()
{
if(commandCode >= MidiCommandCode.Sysex)
return String.Format("{0} {1}",absoluteTime,commandCode);
else
return String.Format("{0} {1} Ch: {2}", absoluteTime, commandCode, channel);
}
/// <summary>
/// Utility function that can read a variable length integer from a binary stream
/// </summary>
/// <param name="br">The binary stream</param>
/// <returns>The integer read</returns>
public static int ReadVarInt(BinaryReader br)
{
int value = 0;
byte b;
for(int n = 0; n < 4; n++)
{
b = br.ReadByte();
value <<= 7;
value += (b & 0x7F);
if((b & 0x80) == 0)
{
return value;
}
}
throw new FormatException("Invalid Var Int");
}
/// <summary>
/// Writes a variable length integer to a binary stream
/// </summary>
/// <param name="writer">Binary stream</param>
/// <param name="value">The value to write</param>
public static void WriteVarInt(BinaryWriter writer, int value)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value", value, "Cannot write a negative Var Int");
}
if (value > 0x0FFFFFFF)
{
throw new ArgumentOutOfRangeException("value", value, "Maximum allowed Var Int is 0x0FFFFFFF");
}
int n = 0;
byte[] buffer = new byte[4];
do
{
buffer[n++] = (byte)(value & 0x7F);
value >>= 7;
} while (value > 0);
while (n > 0)
{
n--;
if(n > 0)
writer.Write((byte) (buffer[n] | 0x80));
else
writer.Write(buffer[n]);
}
}
/// <summary>
/// Exports this MIDI event's data
/// Overriden in derived classes, but they should call this version
/// </summary>
/// <param name="absoluteTime">Absolute time used to calculate delta.
/// Is updated ready for the next delta calculation</param>
/// <param name="writer">Stream to write to</param>
public virtual void Export(ref long absoluteTime, BinaryWriter writer)
{
if (this.absoluteTime < absoluteTime)
{
throw new FormatException("Can't export unsorted MIDI events");
}
WriteVarInt(writer,(int) (this.absoluteTime - absoluteTime));
absoluteTime = this.absoluteTime;
int output = (int) commandCode;
if (commandCode != MidiCommandCode.MetaEvent)
{
output += (channel - 1);
}
writer.Write((byte)output);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.XPath;
namespace MS.Internal.Xml.XPath
{
internal class XPathParser
{
private XPathScanner _scanner;
private XPathParser(XPathScanner scanner)
{
_scanner = scanner;
}
public static AstNode ParseXPathExpresion(string xpathExpresion)
{
XPathScanner scanner = new XPathScanner(xpathExpresion);
XPathParser parser = new XPathParser(scanner);
AstNode result = parser.ParseExpresion(null);
if (scanner.Kind != XPathScanner.LexKind.Eof)
{
throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText);
}
return result;
}
public static AstNode ParseXPathPattern(string xpathPattern)
{
XPathScanner scanner = new XPathScanner(xpathPattern);
XPathParser parser = new XPathParser(scanner);
AstNode result = parser.ParsePattern();
if (scanner.Kind != XPathScanner.LexKind.Eof)
{
throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText);
}
return result;
}
// --------------- Expression Parsing ----------------------
//The recursive is like
//ParseOrExpr->ParseAndExpr->ParseEqualityExpr->ParseRelationalExpr...->ParseFilterExpr->ParsePredicate->ParseExpresion
//So put 200 limitation here will max cause about 2000~3000 depth stack.
private int _parseDepth = 0;
private const int MaxParseDepth = 200;
private AstNode ParseExpresion(AstNode qyInput)
{
if (++_parseDepth > MaxParseDepth)
{
throw XPathException.Create(SR.Xp_QueryTooComplex);
}
AstNode result = ParseOrExpr(qyInput);
--_parseDepth;
return result;
}
//>> OrExpr ::= ( OrExpr 'or' )? AndExpr
private AstNode ParseOrExpr(AstNode qyInput)
{
AstNode opnd = ParseAndExpr(qyInput);
do
{
if (!TestOp("or"))
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.OR, opnd, ParseAndExpr(qyInput));
} while (true);
}
//>> AndExpr ::= ( AndExpr 'and' )? EqualityExpr
private AstNode ParseAndExpr(AstNode qyInput)
{
AstNode opnd = ParseEqualityExpr(qyInput);
do
{
if (!TestOp("and"))
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.AND, opnd, ParseEqualityExpr(qyInput));
} while (true);
}
//>> EqualityOp ::= '=' | '!='
//>> EqualityExpr ::= ( EqualityExpr EqualityOp )? RelationalExpr
private AstNode ParseEqualityExpr(AstNode qyInput)
{
AstNode opnd = ParseRelationalExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Eq ? Operator.Op.EQ :
_scanner.Kind == XPathScanner.LexKind.Ne ? Operator.Op.NE :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseRelationalExpr(qyInput));
} while (true);
}
//>> RelationalOp ::= '<' | '>' | '<=' | '>='
//>> RelationalExpr ::= ( RelationalExpr RelationalOp )? AdditiveExpr
private AstNode ParseRelationalExpr(AstNode qyInput)
{
AstNode opnd = ParseAdditiveExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Lt ? Operator.Op.LT :
_scanner.Kind == XPathScanner.LexKind.Le ? Operator.Op.LE :
_scanner.Kind == XPathScanner.LexKind.Gt ? Operator.Op.GT :
_scanner.Kind == XPathScanner.LexKind.Ge ? Operator.Op.GE :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseAdditiveExpr(qyInput));
} while (true);
}
//>> AdditiveOp ::= '+' | '-'
//>> AdditiveExpr ::= ( AdditiveExpr AdditiveOp )? MultiplicativeExpr
private AstNode ParseAdditiveExpr(AstNode qyInput)
{
AstNode opnd = ParseMultiplicativeExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Plus ? Operator.Op.PLUS :
_scanner.Kind == XPathScanner.LexKind.Minus ? Operator.Op.MINUS :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseMultiplicativeExpr(qyInput));
} while (true);
}
//>> MultiplicativeOp ::= '*' | 'div' | 'mod'
//>> MultiplicativeExpr ::= ( MultiplicativeExpr MultiplicativeOp )? UnaryExpr
private AstNode ParseMultiplicativeExpr(AstNode qyInput)
{
AstNode opnd = ParseUnaryExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Star ? Operator.Op.MUL :
TestOp("div") ? Operator.Op.DIV :
TestOp("mod") ? Operator.Op.MOD :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseUnaryExpr(qyInput));
} while (true);
}
//>> UnaryExpr ::= UnionExpr | '-' UnaryExpr
private AstNode ParseUnaryExpr(AstNode qyInput)
{
bool minus = false;
while (_scanner.Kind == XPathScanner.LexKind.Minus)
{
NextLex();
minus = !minus;
}
if (minus)
{
return new Operator(Operator.Op.MUL, ParseUnionExpr(qyInput), new Operand(-1));
}
else
{
return ParseUnionExpr(qyInput);
}
}
//>> UnionExpr ::= ( UnionExpr '|' )? PathExpr
private AstNode ParseUnionExpr(AstNode qyInput)
{
AstNode opnd = ParsePathExpr(qyInput);
do
{
if (_scanner.Kind != XPathScanner.LexKind.Union)
{
return opnd;
}
NextLex();
AstNode opnd2 = ParsePathExpr(qyInput);
CheckNodeSet(opnd.ReturnType);
CheckNodeSet(opnd2.ReturnType);
opnd = new Operator(Operator.Op.UNION, opnd, opnd2);
} while (true);
}
private static bool IsNodeType(XPathScanner scaner)
{
return (
scaner.Prefix.Length == 0 && (
scaner.Name == "node" ||
scaner.Name == "text" ||
scaner.Name == "processing-instruction" ||
scaner.Name == "comment"
)
);
}
//>> PathOp ::= '/' | '//'
//>> PathExpr ::= LocationPath |
//>> FilterExpr ( PathOp RelativeLocationPath )?
private AstNode ParsePathExpr(AstNode qyInput)
{
AstNode opnd;
if (IsPrimaryExpr(_scanner))
{ // in this moment we should distinct LocationPas vs FilterExpr (which starts from is PrimaryExpr)
opnd = ParseFilterExpr(qyInput);
if (_scanner.Kind == XPathScanner.LexKind.Slash)
{
NextLex();
opnd = ParseRelativeLocationPath(opnd);
}
else if (_scanner.Kind == XPathScanner.LexKind.SlashSlash)
{
NextLex();
opnd = ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, opnd));
}
}
else
{
opnd = ParseLocationPath(null);
}
return opnd;
}
//>> FilterExpr ::= PrimaryExpr | FilterExpr Predicate
private AstNode ParseFilterExpr(AstNode qyInput)
{
AstNode opnd = ParsePrimaryExpr(qyInput);
while (_scanner.Kind == XPathScanner.LexKind.LBracket)
{
// opnd must be a query
opnd = new Filter(opnd, ParsePredicate(opnd));
}
return opnd;
}
//>> Predicate ::= '[' Expr ']'
private AstNode ParsePredicate(AstNode qyInput)
{
AstNode opnd;
// we have predicates. Check that input type is NodeSet
CheckNodeSet(qyInput.ReturnType);
PassToken(XPathScanner.LexKind.LBracket);
opnd = ParseExpresion(qyInput);
PassToken(XPathScanner.LexKind.RBracket);
return opnd;
}
//>> LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
private AstNode ParseLocationPath(AstNode qyInput)
{
if (_scanner.Kind == XPathScanner.LexKind.Slash)
{
NextLex();
AstNode opnd = new Root();
if (IsStep(_scanner.Kind))
{
opnd = ParseRelativeLocationPath(opnd);
}
return opnd;
}
else if (_scanner.Kind == XPathScanner.LexKind.SlashSlash)
{
NextLex();
return ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, new Root()));
}
else
{
return ParseRelativeLocationPath(qyInput);
}
} // ParseLocationPath
//>> PathOp ::= '/' | '//'
//>> RelativeLocationPath ::= ( RelativeLocationPath PathOp )? Step
private AstNode ParseRelativeLocationPath(AstNode qyInput)
{
AstNode opnd = qyInput;
do
{
opnd = ParseStep(opnd);
if (XPathScanner.LexKind.SlashSlash == _scanner.Kind)
{
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd);
}
else if (XPathScanner.LexKind.Slash == _scanner.Kind)
{
NextLex();
}
else
{
break;
}
}
while (true);
return opnd;
}
private static bool IsStep(XPathScanner.LexKind lexKind)
{
return (
lexKind == XPathScanner.LexKind.Dot ||
lexKind == XPathScanner.LexKind.DotDot ||
lexKind == XPathScanner.LexKind.At ||
lexKind == XPathScanner.LexKind.Axe ||
lexKind == XPathScanner.LexKind.Star ||
lexKind == XPathScanner.LexKind.Name // NodeTest is also Name
);
}
//>> Step ::= '.' | '..' | ( AxisName '::' | '@' )? NodeTest Predicate*
private AstNode ParseStep(AstNode qyInput)
{
AstNode opnd;
if (XPathScanner.LexKind.Dot == _scanner.Kind)
{ //>> '.'
NextLex();
opnd = new Axis(Axis.AxisType.Self, qyInput);
}
else if (XPathScanner.LexKind.DotDot == _scanner.Kind)
{ //>> '..'
NextLex();
opnd = new Axis(Axis.AxisType.Parent, qyInput);
}
else
{ //>> ( AxisName '::' | '@' )? NodeTest Predicate*
Axis.AxisType axisType = Axis.AxisType.Child;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.At: //>> '@'
axisType = Axis.AxisType.Attribute;
NextLex();
break;
case XPathScanner.LexKind.Axe: //>> AxisName '::'
axisType = GetAxis();
NextLex();
break;
}
XPathNodeType nodeType = (
axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute :
// axisType == Axis.AxisType.Namespace ? XPathNodeType.Namespace : // No Idea why it's this way but otherwise Axes doesn't work
/* default: */ XPathNodeType.Element
);
opnd = ParseNodeTest(qyInput, axisType, nodeType);
while (XPathScanner.LexKind.LBracket == _scanner.Kind)
{
opnd = new Filter(opnd, ParsePredicate(opnd));
}
}
return opnd;
}
//>> NodeTest ::= NameTest | 'comment ()' | 'text ()' | 'node ()' | 'processing-instruction (' Literal ? ')'
private AstNode ParseNodeTest(AstNode qyInput, Axis.AxisType axisType, XPathNodeType nodeType)
{
string nodeName, nodePrefix;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.Name:
if (_scanner.CanBeFunction && IsNodeType(_scanner))
{
nodePrefix = string.Empty;
nodeName = string.Empty;
nodeType = (
_scanner.Name == "comment" ? XPathNodeType.Comment :
_scanner.Name == "text" ? XPathNodeType.Text :
_scanner.Name == "node" ? XPathNodeType.All :
_scanner.Name == "processing-instruction" ? XPathNodeType.ProcessingInstruction :
/* default: */ XPathNodeType.Root
);
Debug.Assert(nodeType != XPathNodeType.Root);
NextLex();
PassToken(XPathScanner.LexKind.LParens);
if (nodeType == XPathNodeType.ProcessingInstruction)
{
if (_scanner.Kind != XPathScanner.LexKind.RParens)
{ //>> 'processing-instruction (' Literal ')'
CheckToken(XPathScanner.LexKind.String);
nodeName = _scanner.StringValue;
NextLex();
}
}
PassToken(XPathScanner.LexKind.RParens);
}
else
{
nodePrefix = _scanner.Prefix;
nodeName = _scanner.Name;
NextLex();
if (nodeName == "*")
{
nodeName = string.Empty;
}
}
break;
case XPathScanner.LexKind.Star:
nodePrefix = string.Empty;
nodeName = string.Empty;
NextLex();
break;
default:
throw XPathException.Create(SR.Xp_NodeSetExpected, _scanner.SourceText);
}
return new Axis(axisType, qyInput, nodePrefix, nodeName, nodeType);
}
private static bool IsPrimaryExpr(XPathScanner scanner)
{
return (
scanner.Kind == XPathScanner.LexKind.String ||
scanner.Kind == XPathScanner.LexKind.Number ||
scanner.Kind == XPathScanner.LexKind.Dollar ||
scanner.Kind == XPathScanner.LexKind.LParens ||
scanner.Kind == XPathScanner.LexKind.Name && scanner.CanBeFunction && !IsNodeType(scanner)
);
}
//>> PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall
private AstNode ParsePrimaryExpr(AstNode qyInput)
{
Debug.Assert(IsPrimaryExpr(_scanner));
AstNode opnd = null;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.String:
opnd = new Operand(_scanner.StringValue);
NextLex();
break;
case XPathScanner.LexKind.Number:
opnd = new Operand(_scanner.NumberValue);
NextLex();
break;
case XPathScanner.LexKind.Dollar:
NextLex();
CheckToken(XPathScanner.LexKind.Name);
opnd = new Variable(_scanner.Name, _scanner.Prefix);
NextLex();
break;
case XPathScanner.LexKind.LParens:
NextLex();
opnd = ParseExpresion(qyInput);
if (opnd.Type != AstNode.AstType.ConstantOperand)
{
opnd = new Group(opnd);
}
PassToken(XPathScanner.LexKind.RParens);
break;
case XPathScanner.LexKind.Name:
if (_scanner.CanBeFunction && !IsNodeType(_scanner))
{
opnd = ParseMethod(null);
}
break;
}
Debug.Assert(opnd != null, "IsPrimaryExpr() was true. We should recognize this lex.");
return opnd;
}
private AstNode ParseMethod(AstNode qyInput)
{
List<AstNode> argList = new List<AstNode>();
string name = _scanner.Name;
string prefix = _scanner.Prefix;
PassToken(XPathScanner.LexKind.Name);
PassToken(XPathScanner.LexKind.LParens);
if (_scanner.Kind != XPathScanner.LexKind.RParens)
{
do
{
argList.Add(ParseExpresion(qyInput));
if (_scanner.Kind == XPathScanner.LexKind.RParens)
{
break;
}
PassToken(XPathScanner.LexKind.Comma);
} while (true);
}
PassToken(XPathScanner.LexKind.RParens);
if (prefix.Length == 0)
{
ParamInfo pi;
if (s_functionTable.TryGetValue(name, out pi))
{
int argCount = argList.Count;
if (argCount < pi.Minargs)
{
throw XPathException.Create(SR.Xp_InvalidNumArgs, name, _scanner.SourceText);
}
if (pi.FType == Function.FunctionType.FuncConcat)
{
for (int i = 0; i < argCount; i++)
{
AstNode arg = (AstNode)argList[i];
if (arg.ReturnType != XPathResultType.String)
{
arg = new Function(Function.FunctionType.FuncString, arg);
}
argList[i] = arg;
}
}
else
{
if (pi.Maxargs < argCount)
{
throw XPathException.Create(SR.Xp_InvalidNumArgs, name, _scanner.SourceText);
}
if (pi.ArgTypes.Length < argCount)
{
argCount = pi.ArgTypes.Length; // argument we have the type specified (can be < pi.Minargs)
}
for (int i = 0; i < argCount; i++)
{
AstNode arg = (AstNode)argList[i];
if (
pi.ArgTypes[i] != XPathResultType.Any &&
pi.ArgTypes[i] != arg.ReturnType
)
{
switch (pi.ArgTypes[i])
{
case XPathResultType.NodeSet:
if (!(arg is Variable) && !(arg is Function && arg.ReturnType == XPathResultType.Any))
{
throw XPathException.Create(SR.Xp_InvalidArgumentType, name, _scanner.SourceText);
}
break;
case XPathResultType.String:
arg = new Function(Function.FunctionType.FuncString, arg);
break;
case XPathResultType.Number:
arg = new Function(Function.FunctionType.FuncNumber, arg);
break;
case XPathResultType.Boolean:
arg = new Function(Function.FunctionType.FuncBoolean, arg);
break;
}
argList[i] = arg;
}
}
}
return new Function(pi.FType, argList);
}
}
return new Function(prefix, name, argList);
}
// --------------- Pattern Parsing ----------------------
//>> Pattern ::= ( Pattern '|' )? LocationPathPattern
private AstNode ParsePattern()
{
AstNode opnd = ParseLocationPathPattern();
do
{
if (_scanner.Kind != XPathScanner.LexKind.Union)
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.UNION, opnd, ParseLocationPathPattern());
} while (true);
}
//>> LocationPathPattern ::= '/' | RelativePathPattern | '//' RelativePathPattern | '/' RelativePathPattern
//>> | IdKeyPattern (('/' | '//') RelativePathPattern)?
private AstNode ParseLocationPathPattern()
{
AstNode opnd = null;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.Slash:
NextLex();
opnd = new Root();
if (_scanner.Kind == XPathScanner.LexKind.Eof || _scanner.Kind == XPathScanner.LexKind.Union)
{
return opnd;
}
break;
case XPathScanner.LexKind.SlashSlash:
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, new Root());
break;
case XPathScanner.LexKind.Name:
if (_scanner.CanBeFunction)
{
opnd = ParseIdKeyPattern();
if (opnd != null)
{
switch (_scanner.Kind)
{
case XPathScanner.LexKind.Slash:
NextLex();
break;
case XPathScanner.LexKind.SlashSlash:
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd);
break;
default:
return opnd;
}
}
}
break;
}
return ParseRelativePathPattern(opnd);
}
//>> IdKeyPattern ::= 'id' '(' Literal ')' | 'key' '(' Literal ',' Literal ')'
private AstNode ParseIdKeyPattern()
{
Debug.Assert(_scanner.CanBeFunction);
List<AstNode> argList = new List<AstNode>();
if (_scanner.Prefix.Length == 0)
{
if (_scanner.Name == "id")
{
ParamInfo pi = (ParamInfo)s_functionTable["id"];
NextLex();
PassToken(XPathScanner.LexKind.LParens);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(_scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.RParens);
return new Function(pi.FType, argList);
}
if (_scanner.Name == "key")
{
NextLex();
PassToken(XPathScanner.LexKind.LParens);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(_scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.Comma);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(_scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.RParens);
return new Function("", "key", argList);
}
}
return null;
}
//>> PathOp ::= '/' | '//'
//>> RelativePathPattern ::= ( RelativePathPattern PathOp )? StepPattern
private AstNode ParseRelativePathPattern(AstNode qyInput)
{
AstNode opnd = ParseStepPattern(qyInput);
if (XPathScanner.LexKind.SlashSlash == _scanner.Kind)
{
NextLex();
opnd = ParseRelativePathPattern(new Axis(Axis.AxisType.DescendantOrSelf, opnd));
}
else if (XPathScanner.LexKind.Slash == _scanner.Kind)
{
NextLex();
opnd = ParseRelativePathPattern(opnd);
}
return opnd;
}
//>> StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate*
//>> ChildOrAttributeAxisSpecifier ::= @ ? | ('child' | 'attribute') '::'
private AstNode ParseStepPattern(AstNode qyInput)
{
AstNode opnd;
Axis.AxisType axisType = Axis.AxisType.Child;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.At: //>> '@'
axisType = Axis.AxisType.Attribute;
NextLex();
break;
case XPathScanner.LexKind.Axe: //>> AxisName '::'
axisType = GetAxis();
if (axisType != Axis.AxisType.Child && axisType != Axis.AxisType.Attribute)
{
throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText);
}
NextLex();
break;
}
XPathNodeType nodeType = (
axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute :
/* default: */ XPathNodeType.Element
);
opnd = ParseNodeTest(qyInput, axisType, nodeType);
while (XPathScanner.LexKind.LBracket == _scanner.Kind)
{
opnd = new Filter(opnd, ParsePredicate(opnd));
}
return opnd;
}
// --------------- Helper methods ----------------------
void CheckToken(XPathScanner.LexKind t)
{
if (_scanner.Kind != t)
{
throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText);
}
}
void PassToken(XPathScanner.LexKind t)
{
CheckToken(t);
NextLex();
}
void NextLex()
{
_scanner.NextLex();
}
private bool TestOp(string op)
{
return (
_scanner.Kind == XPathScanner.LexKind.Name &&
_scanner.Prefix.Length == 0 &&
_scanner.Name.Equals(op)
);
}
void CheckNodeSet(XPathResultType t)
{
if (t != XPathResultType.NodeSet && t != XPathResultType.Any)
{
throw XPathException.Create(SR.Xp_NodeSetExpected, _scanner.SourceText);
}
}
// ----------------------------------------------------------------
private static readonly XPathResultType[] s_temparray1 = { };
private static readonly XPathResultType[] s_temparray2 = { XPathResultType.NodeSet };
private static readonly XPathResultType[] s_temparray3 = { XPathResultType.Any };
private static readonly XPathResultType[] s_temparray4 = { XPathResultType.String };
private static readonly XPathResultType[] s_temparray5 = { XPathResultType.String, XPathResultType.String };
private static readonly XPathResultType[] s_temparray6 = { XPathResultType.String, XPathResultType.Number, XPathResultType.Number };
private static readonly XPathResultType[] s_temparray7 = { XPathResultType.String, XPathResultType.String, XPathResultType.String };
private static readonly XPathResultType[] s_temparray8 = { XPathResultType.Boolean };
private static readonly XPathResultType[] s_temparray9 = { XPathResultType.Number };
private class ParamInfo
{
private Function.FunctionType _ftype;
private int _minargs;
private int _maxargs;
private XPathResultType[] _argTypes;
public Function.FunctionType FType { get { return _ftype; } }
public int Minargs { get { return _minargs; } }
public int Maxargs { get { return _maxargs; } }
public XPathResultType[] ArgTypes { get { return _argTypes; } }
internal ParamInfo(Function.FunctionType ftype, int minargs, int maxargs, XPathResultType[] argTypes)
{
_ftype = ftype;
_minargs = minargs;
_maxargs = maxargs;
_argTypes = argTypes;
}
} //ParamInfo
private static Dictionary<string, ParamInfo> s_functionTable = CreateFunctionTable();
private static Dictionary<string, ParamInfo> CreateFunctionTable()
{
Dictionary<string, ParamInfo> table = new Dictionary<string, ParamInfo>(36);
table.Add("last", new ParamInfo(Function.FunctionType.FuncLast, 0, 0, s_temparray1));
table.Add("position", new ParamInfo(Function.FunctionType.FuncPosition, 0, 0, s_temparray1));
table.Add("name", new ParamInfo(Function.FunctionType.FuncName, 0, 1, s_temparray2));
table.Add("namespace-uri", new ParamInfo(Function.FunctionType.FuncNameSpaceUri, 0, 1, s_temparray2));
table.Add("local-name", new ParamInfo(Function.FunctionType.FuncLocalName, 0, 1, s_temparray2));
table.Add("count", new ParamInfo(Function.FunctionType.FuncCount, 1, 1, s_temparray2));
table.Add("id", new ParamInfo(Function.FunctionType.FuncID, 1, 1, s_temparray3));
table.Add("string", new ParamInfo(Function.FunctionType.FuncString, 0, 1, s_temparray3));
table.Add("concat", new ParamInfo(Function.FunctionType.FuncConcat, 2, 100, s_temparray4));
table.Add("starts-with", new ParamInfo(Function.FunctionType.FuncStartsWith, 2, 2, s_temparray5));
table.Add("contains", new ParamInfo(Function.FunctionType.FuncContains, 2, 2, s_temparray5));
table.Add("substring-before", new ParamInfo(Function.FunctionType.FuncSubstringBefore, 2, 2, s_temparray5));
table.Add("substring-after", new ParamInfo(Function.FunctionType.FuncSubstringAfter, 2, 2, s_temparray5));
table.Add("substring", new ParamInfo(Function.FunctionType.FuncSubstring, 2, 3, s_temparray6));
table.Add("string-length", new ParamInfo(Function.FunctionType.FuncStringLength, 0, 1, s_temparray4));
table.Add("normalize-space", new ParamInfo(Function.FunctionType.FuncNormalize, 0, 1, s_temparray4));
table.Add("translate", new ParamInfo(Function.FunctionType.FuncTranslate, 3, 3, s_temparray7));
table.Add("boolean", new ParamInfo(Function.FunctionType.FuncBoolean, 1, 1, s_temparray3));
table.Add("not", new ParamInfo(Function.FunctionType.FuncNot, 1, 1, s_temparray8));
table.Add("true", new ParamInfo(Function.FunctionType.FuncTrue, 0, 0, s_temparray8));
table.Add("false", new ParamInfo(Function.FunctionType.FuncFalse, 0, 0, s_temparray8));
table.Add("lang", new ParamInfo(Function.FunctionType.FuncLang, 1, 1, s_temparray4));
table.Add("number", new ParamInfo(Function.FunctionType.FuncNumber, 0, 1, s_temparray3));
table.Add("sum", new ParamInfo(Function.FunctionType.FuncSum, 1, 1, s_temparray2));
table.Add("floor", new ParamInfo(Function.FunctionType.FuncFloor, 1, 1, s_temparray9));
table.Add("ceiling", new ParamInfo(Function.FunctionType.FuncCeiling, 1, 1, s_temparray9));
table.Add("round", new ParamInfo(Function.FunctionType.FuncRound, 1, 1, s_temparray9));
return table;
}
private static Dictionary<string, Axis.AxisType> s_AxesTable = CreateAxesTable();
private static Dictionary<string, Axis.AxisType> CreateAxesTable()
{
Dictionary<string, Axis.AxisType> table = new Dictionary<string, Axis.AxisType>(13);
table.Add("ancestor", Axis.AxisType.Ancestor);
table.Add("ancestor-or-self", Axis.AxisType.AncestorOrSelf);
table.Add("attribute", Axis.AxisType.Attribute);
table.Add("child", Axis.AxisType.Child);
table.Add("descendant", Axis.AxisType.Descendant);
table.Add("descendant-or-self", Axis.AxisType.DescendantOrSelf);
table.Add("following", Axis.AxisType.Following);
table.Add("following-sibling", Axis.AxisType.FollowingSibling);
table.Add("namespace", Axis.AxisType.Namespace);
table.Add("parent", Axis.AxisType.Parent);
table.Add("preceding", Axis.AxisType.Preceding);
table.Add("preceding-sibling", Axis.AxisType.PrecedingSibling);
table.Add("self", Axis.AxisType.Self);
return table;
}
private Axis.AxisType GetAxis()
{
Debug.Assert(_scanner.Kind == XPathScanner.LexKind.Axe);
Axis.AxisType axis;
if (!s_AxesTable.TryGetValue(_scanner.Name, out axis))
{
throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText);
}
return axis;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableDictionaryTest : ImmutableDictionaryTestBase
{
[Fact]
public void AddExistingKeySameValueTest()
{
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft");
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void AddExistingKeyDifferentValueTest()
{
AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void UnorderedChangeTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("Johnny"));
Assert.False(map.ContainsKey("johnny"));
var newMap = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, newMap.Count);
Assert.True(newMap.ContainsKey("Johnny"));
Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive
}
[Fact]
public void ToSortedTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
var sortedMap = map.ToImmutableSortedDictionary(StringComparer.Ordinal);
Assert.Equal(sortedMap.Count, map.Count);
CollectionAssertAreEquivalent<KeyValuePair<string, string>>(sortedMap.ToList(), map.ToList());
}
[Fact]
public void SetItemUpdateEqualKeyTest()
{
var map = Empty<string, int>().WithComparers(StringComparer.OrdinalIgnoreCase)
.SetItem("A", 1);
map = map.SetItem("a", 2);
Assert.Equal("a", map.Keys.Single());
}
/// <summary>
/// Verifies that the specified value comparer is applied when
/// checking for equality.
/// </summary>
[Fact]
public void SetItemUpdateEqualKeyWithValueEqualityByComparer()
{
var map = Empty<string, CaseInsensitiveString>().WithComparers(StringComparer.OrdinalIgnoreCase, new MyStringOrdinalComparer());
string key = "key";
var value1 = "Hello";
var value2 = "hello";
map = map.SetItem(key, new CaseInsensitiveString(value1));
map = map.SetItem(key, new CaseInsensitiveString(value2));
Assert.Equal(value2, map[key].Value);
Assert.Same(map, map.SetItem(key, new CaseInsensitiveString(value2)));
}
[Fact]
public override void EmptyTest()
{
base.EmptyTest();
this.EmptyTestHelperHash(Empty<int, bool>(), 5);
}
[Fact]
public void ContainsValueTest()
{
this.ContainsValueTestHelper(ImmutableDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper());
}
[Fact]
public void EnumeratorWithHashCollisionsTest()
{
var emptyMap = Empty<int, GenericParameterHelper>(new BadHasher<int>());
this.EnumeratorTestHelper(emptyMap);
}
[Fact]
public void Create()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
var dictionary = ImmutableDictionary.Create<string, string>();
Assert.Equal(0, dictionary.Count);
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableDictionary.Create<string, string>(keyComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableDictionary.Create(keyComparer, valueComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = ImmutableDictionary.CreateRange(pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableDictionary.CreateRange(keyComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableDictionary.CreateRange(keyComparer, valueComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void ToImmutableDictionary()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
ImmutableDictionary<string, string> dictionary = pairs.ToImmutableDictionary();
Assert.Equal(1, dictionary.Count);
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableDictionary(keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableDictionary(keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = pairs.ToImmutableDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant());
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
var list = new int[] { 1, 2 };
var intDictionary = list.ToImmutableDictionary(n => (double)n);
Assert.Equal(1, intDictionary[1.0]);
Assert.Equal(2, intDictionary[2.0]);
Assert.Equal(2, intDictionary.Count);
var stringIntDictionary = list.ToImmutableDictionary(n => n.ToString(), StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, stringIntDictionary.KeyComparer);
Assert.Equal(1, stringIntDictionary["1"]);
Assert.Equal(2, stringIntDictionary["2"]);
Assert.Equal(2, intDictionary.Count);
Assert.Throws<ArgumentNullException>(() => list.ToImmutableDictionary<int, int>(null));
Assert.Throws<ArgumentNullException>(() => list.ToImmutableDictionary<int, int, int>(null, v => v));
Assert.Throws<ArgumentNullException>(() => list.ToImmutableDictionary<int, int, int>(k => k, null));
list.ToDictionary(k => k, v => v, null); // verifies BCL behavior is to not throw.
list.ToImmutableDictionary(k => k, v => v, null, null);
}
[Fact]
public void ToImmutableDictionaryOptimized()
{
var dictionary = ImmutableDictionary.Create<string, string>();
var result = dictionary.ToImmutableDictionary();
Assert.Same(dictionary, result);
var cultureComparer = StringComparer.CurrentCulture;
result = dictionary.WithComparers(cultureComparer, StringComparer.OrdinalIgnoreCase);
Assert.Same(cultureComparer, result.KeyComparer);
Assert.Same(StringComparer.OrdinalIgnoreCase, result.ValueComparer);
}
[Fact]
public void WithComparers()
{
var map = ImmutableDictionary.Create<string, string>().Add("a", "1").Add("B", "1");
Assert.Same(EqualityComparer<string>.Default, map.KeyComparer);
Assert.True(map.ContainsKey("a"));
Assert.False(map.ContainsKey("A"));
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
var cultureComparer = StringComparer.CurrentCulture;
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(cultureComparer, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void WithComparersCollisions()
{
// First check where collisions have matching values.
var map = ImmutableDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1");
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(1, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.Equal("1", map["a"]);
// Now check where collisions have conflicting values.
map = ImmutableDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3");
Assert.Throws<ArgumentException>(() => map.WithComparers(StringComparer.OrdinalIgnoreCase));
// Force all values to be considered equal.
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(EverythingEqual<string>.Default, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void CollisionExceptionMessageContainsKey()
{
var map = ImmutableDictionary.Create<string, string>()
.Add("firstKey", "1").Add("secondKey", "2");
var exception = Assert.Throws<ArgumentException>(() => map.Add("firstKey", "3"));
Assert.Contains("firstKey", exception.Message);
}
[Fact]
public void WithComparersEmptyCollection()
{
var map = ImmutableDictionary.Create<string, string>();
Assert.Same(EqualityComparer<string>.Default, map.KeyComparer);
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
}
[Fact]
public void GetValueOrDefaultOfIImmutableDictionary()
{
IImmutableDictionary<string, int> empty = ImmutableDictionary.Create<string, int>();
IImmutableDictionary<string, int> populated = ImmutableDictionary.Create<string, int>().Add("a", 5);
Assert.Equal(0, empty.GetValueOrDefault("a"));
Assert.Equal(1, empty.GetValueOrDefault("a", 1));
Assert.Equal(5, populated.GetValueOrDefault("a"));
Assert.Equal(5, populated.GetValueOrDefault("a", 1));
}
[Fact]
public void GetValueOrDefaultOfConcreteType()
{
var empty = ImmutableDictionary.Create<string, int>();
var populated = ImmutableDictionary.Create<string, int>().Add("a", 5);
Assert.Equal(0, empty.GetValueOrDefault("a"));
Assert.Equal(1, empty.GetValueOrDefault("a", 1));
Assert.Equal(5, populated.GetValueOrDefault("a"));
Assert.Equal(5, populated.GetValueOrDefault("a", 1));
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableDictionary.Create<int, int>().Add(5, 3);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableDictionary.Create<int, int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableDictionary.Create<string, int>());
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableDictionary.Create<string, string>(), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
}
protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>()
{
return ImmutableDictionaryTest.Empty<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableDictionary.Create<string, TValue>(comparer);
}
protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return ((ImmutableDictionary<TKey, TValue>)dictionary).ValueComparer;
}
internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return ((ImmutableDictionary<TKey, TValue>)dictionary).Root;
}
protected void ContainsValueTestHelper<TKey, TValue>(ImmutableDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsValue(value));
Assert.True(map.Add(key, value).ContainsValue(value));
}
private static ImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IEqualityComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null)
{
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer);
}
private void EmptyTestHelperHash<TKey, TValue>(IImmutableDictionary<TKey, TValue> empty, TKey someKey)
{
Assert.Same(EqualityComparer<TKey>.Default, ((IHashKeyCollection<TKey>)empty).KeyComparer);
}
/// <summary>
/// An ordinal comparer for case-insensitive strings.
/// </summary>
private class MyStringOrdinalComparer : EqualityComparer<CaseInsensitiveString>
{
public override bool Equals(CaseInsensitiveString x, CaseInsensitiveString y)
{
return StringComparer.Ordinal.Equals(x.Value, y.Value);
}
public override int GetHashCode(CaseInsensitiveString obj)
{
return StringComparer.Ordinal.GetHashCode(obj.Value);
}
}
/// <summary>
/// A string-wrapper that considers equality based on case insensitivity.
/// </summary>
private class CaseInsensitiveString
{
public CaseInsensitiveString(string value)
{
Value = value;
}
public string Value { get; private set; }
public override int GetHashCode()
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(this.Value);
}
public override bool Equals(object obj)
{
return StringComparer.OrdinalIgnoreCase.Equals(this.Value, ((CaseInsensitiveString)obj).Value);
}
}
}
}
| |
// 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.Threading;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using LifeTimeFX;
interface PinnedObject
{
void CleanUp();
bool IsPinned();
}
namespace GCSimulator
{
class RandomLifeTimeStrategy : LifeTimeStrategy
{
private int counter = 0;
private int mediumLifeTime = 30;
private int shortLifeTime = 3;
private int mediumDataCount = 1000000;
private int shortDataCount = 5000;
private Random rand = new Random(123456);
public RandomLifeTimeStrategy(int mediumlt, int shortlt, int mdc, int sdc)
{
mediumLifeTime = mediumlt;
shortLifeTime = shortlt;
mediumDataCount = mdc;
shortDataCount = sdc;
}
public int MediumLifeTime
{
set
{
mediumLifeTime = value;
}
}
public int ShortLifeTime
{
set
{
shortLifeTime = value;
}
}
public int NextObject(LifeTimeENUM lifeTime)
{
switch (lifeTime)
{
case LifeTimeENUM.Short:
return rand.Next() % shortDataCount;
case LifeTimeENUM.Medium:
return (rand.Next() % mediumDataCount) + shortDataCount;
case LifeTimeENUM.Long:
return 0;
}
return 0;
}
public bool ShouldDie(LifeTime o, int index)
{
counter++;
LifeTimeENUM lifeTime = o.LifeTime;
switch (lifeTime)
{
case LifeTimeENUM.Short:
if (counter % shortLifeTime == 0)
return true;
break;
case LifeTimeENUM.Medium:
if (counter % mediumLifeTime == 0)
return true;
break;
case LifeTimeENUM.Long:
return false;
}
return false;
}
}
/// <summary>
/// we might want to implement a different strategy that decide the life time of the object based on the time
/// elabsed since the last object acceess.
///
/// </summary>
class TimeBasedLifeTimeStrategy : LifeTimeStrategy
{
private int lastMediumTickCount = Environment.TickCount;
private int lastShortTickCount = Environment.TickCount;
private int lastMediumIndex = 0;
private int lastShortIndex = 0;
public int NextObject(LifeTimeENUM lifeTime)
{
switch (lifeTime)
{
case LifeTimeENUM.Short:
return lastShortIndex;
case LifeTimeENUM.Medium:
return lastMediumIndex;
case LifeTimeENUM.Long:
return 0;
}
return 0;
}
public bool ShouldDie(LifeTime o, int index)
{
LifeTimeENUM lifeTime = o.LifeTime;
// short objects will live for 20 seconds, long objects will live for more.
switch (lifeTime)
{
case LifeTimeENUM.Short:
if (Environment.TickCount - lastShortTickCount > 1) // this is in accureat enumber, since
// we will be finsh iterating throuh the short life time object in less than 1 ms , so we need
// to switch either to QueryPeroformanceCounter, or to block the loop for some time through
// Thread.Sleep, the other solution is to increase the number of objects a lot.
{
lastShortTickCount = Environment.TickCount;
lastShortIndex = index;
return true;
}
break;
case LifeTimeENUM.Medium:
if (Environment.TickCount - lastMediumTickCount > 20)
{
lastMediumTickCount = Environment.TickCount;
lastMediumIndex = index;
return true;
}
break;
case LifeTimeENUM.Long:
break;
}
return false;
}
}
class ObjectWrapper : LifeTime, PinnedObject
{
private bool pinned;
private bool weakReferenced;
private GCHandle gcHandle;
private LifeTimeENUM lifeTime;
private WeakReference weakRef;
private byte[] data;
private int dataSize;
public int DataSize
{
set
{
dataSize = value;
data = new byte[dataSize];
if (pinned)
{
gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
}
if (weakReferenced)
{
weakRef = new WeakReference(data);
}
}
}
public LifeTimeENUM LifeTime
{
get
{
return lifeTime;
}
set
{
this.lifeTime = value;
}
}
public bool IsPinned()
{
return pinned;
}
public bool IsWeak()
{
return weakReferenced;
}
public void CleanUp()
{
if (pinned)
{
gcHandle.Free();
}
}
public ObjectWrapper(bool runFinalizer, bool pinned, bool weakReferenced)
{
this.pinned = pinned;
this.weakReferenced = weakReferenced;
if (!runFinalizer)
{
GC.SuppressFinalize(this);
}
}
~ObjectWrapper()
{
// DO SOMETHING BAD IN FINALIZER
data = new byte[dataSize];
}
}
class ClientSimulator
{
[ThreadStatic]
private static ObjectLifeTimeManager lifeTimeManager;
private static int meanAllocSize = 17;
private static int mediumLifeTime = 30;
private static int shortLifeTime = 3;
private static int mediumDataSize = meanAllocSize;
private static int shortDataSize = meanAllocSize;
private static int mediumDataCount = 1000000;
private static int shortDataCount = 5000;
private static int countIters = 500;
private static float percentPinned = 0.02F;
private static float percentWeak = 0.0F;
private static int numThreads = 1;
private static bool runFinalizer = false;
private static string strategy = "Random";
private static bool noTimer = false;
private static string objectGraph = "List";
private static List<Thread> threadList = new List<Thread>();
public static void Main(string[] args)
{
bool shouldContinue = ParseArgs(args);
if (!shouldContinue)
{
return;
}
int timer = 0;
// Run the test.
for (int i = 0; i < numThreads; ++i)
{
Thread thread = new Thread(RunTest);
threadList.Add(thread);
thread.Start();
}
foreach (Thread t in threadList)
{
t.Join();
}
}
public static void RunTest(object threadInfoObj)
{
// Allocate the objects.
lifeTimeManager = new ObjectLifeTimeManager();
LifeTimeStrategy ltStrategy;
int threadMediumLifeTime = mediumLifeTime;
int threadShortLifeTime = shortLifeTime;
int threadMediumDataSize = mediumDataSize;
int threadShortDataSize = shortDataSize;
int threadMediumDataCount = mediumDataCount;
int threadShortDataCount = shortDataCount;
float threadPercentPinned = percentPinned;
float threadPercentWeak = percentWeak;
bool threadRunFinalizer = runFinalizer;
string threadStrategy = strategy;
string threadObjectGraph = objectGraph;
if (threadObjectGraph.ToLower() == "tree")
{
lifeTimeManager.SetObjectContainer(new BinaryTreeObjectContainer<LifeTime>());
}
else
{
lifeTimeManager.SetObjectContainer(new ArrayObjectContainer<LifeTime>());
}
lifeTimeManager.Init(threadShortDataCount + threadMediumDataCount);
if (threadStrategy.ToLower()=="random")
{
ltStrategy = new RandomLifeTimeStrategy(threadMediumLifeTime, threadShortLifeTime, threadMediumDataCount, threadShortDataCount);
}
else
{
// may be we need to specify the elapsed time.
ltStrategy = new TimeBasedLifeTimeStrategy();
}
lifeTimeManager.LifeTimeStrategy = ltStrategy;
lifeTimeManager.objectDied += new ObjectDiedEventHandler(objectDied);
for (int i=0; i < threadShortDataCount + threadMediumDataCount; ++i)
{
bool pinned = false;
if (threadPercentPinned!=0)
{
pinned = (i % ((int)(1/threadPercentPinned))==0);
}
bool weak = false;
if (threadPercentWeak!=0)
{
weak = (i % ((int)(1/threadPercentWeak))==0);
}
ObjectWrapper oWrapper = new ObjectWrapper(threadRunFinalizer, pinned, weak);
if (i < threadShortDataCount)
{
oWrapper.DataSize = threadShortDataSize;
oWrapper.LifeTime = LifeTimeENUM.Short;
}
else
{
oWrapper.DataSize = threadMediumDataSize;
oWrapper.LifeTime = LifeTimeENUM.Medium;
}
lifeTimeManager.AddObject(oWrapper, i);
}
for (int i = 0; i < countIters; ++i)
{
// Run the test.
lifeTimeManager.Run();
}
}
private static void objectDied(LifeTime lifeTime, int index)
{
// put a new fresh object instead;
LifeTimeENUM lifeTimeEnum;
lifeTimeEnum = lifeTime.LifeTime;
ObjectWrapper oWrapper = lifeTime as ObjectWrapper;
bool weakReferenced = oWrapper.IsWeak();
bool pinned = oWrapper.IsPinned();
if (pinned)
{
oWrapper.CleanUp();
}
oWrapper = new ObjectWrapper(runFinalizer, pinned, weakReferenced);
oWrapper.LifeTime = lifeTimeEnum;
oWrapper.DataSize = lifeTime.LifeTime == LifeTimeENUM.Short ? shortDataSize : mediumDataSize;
lifeTimeManager.AddObject(oWrapper, index);
}
/// <summary>
/// Parse the arguments, no error checking is done yet.
/// TODO: Add more error checking.
///
/// Populate variables with defaults, then overwrite them with config settings. Finally overwrite them with command line parameters
/// </summary>
public static bool ParseArgs(string[] args)
{
for (int i = 0; i < args.Length; ++i)
{
string currentArg = args[i];
string currentArgValue;
if (currentArg.StartsWith("-") || currentArg.StartsWith("/"))
{
currentArg = currentArg.Substring(1);
}
else
{
continue;
}
if (currentArg.StartsWith("?"))
{
Usage();
return false;
}
if (currentArg.StartsWith("iter") || currentArg.Equals("i")) // number of iterations
{
currentArgValue = args[++i];
countIters = Int32.Parse(currentArgValue);
}
if (currentArg.StartsWith("datasize") || currentArg.Equals("dz"))
{
currentArgValue = args[++i];
mediumDataSize = Int32.Parse(currentArgValue);
}
if (currentArg.StartsWith("sdatasize") || currentArg.Equals("sdz"))
{
currentArgValue = args[++i];
shortDataSize = Int32.Parse(currentArgValue);
}
if (currentArg.StartsWith("datacount") || currentArg.Equals("dc"))
{
currentArgValue = args[++i];
mediumDataCount = Int32.Parse(currentArgValue);
}
if (currentArg.StartsWith("sdatacount") || currentArg.Equals("sdc"))
{
currentArgValue = args[++i];
shortDataCount = Int32.Parse(currentArgValue);
}
if (currentArg.StartsWith("lifetime") || currentArg.Equals("lt"))
{
currentArgValue = args[++i];
shortLifeTime = Int32.Parse(currentArgValue);
mediumLifeTime = shortLifeTime * 10;
}
if (currentArg.StartsWith("threads") || currentArg.Equals("t"))
{
currentArgValue = args[++i];
numThreads = Int32.Parse(currentArgValue);
}
if (currentArg.StartsWith("fin") || currentArg.Equals("f"))
{
runFinalizer = true;
}
if (currentArg.StartsWith("datapinned") || currentArg.StartsWith("dp")) // percentage data pinned
{
currentArgValue = args[++i];
percentPinned = float.Parse(currentArgValue);
}
if (currentArg.StartsWith("strategy")) //strategy that if the object died or not
{
currentArgValue = args[++i];
strategy = currentArgValue;
}
if (currentArg.StartsWith("notimer"))
{
noTimer = true;
}
if (currentArg.StartsWith("dataweak") || currentArg.StartsWith("dw") )
{
currentArgValue = args[++i];
percentWeak = float.Parse(currentArgValue);
}
if (currentArg.StartsWith("objectgraph") || currentArg.StartsWith("og") )
{
currentArgValue = args[++i];
objectGraph = currentArgValue;
}
}
return true;
}
public static void Usage()
{
Console.WriteLine("GCSimulator [-?] [-i <num Iterations>] [-dz <data size in bytes>] [-lt <life time>] [-t <num threads>] [-f] [-dp <percent data pinned>]");
Console.WriteLine("Options");
Console.WriteLine("-? Display the usage and exit");
Console.WriteLine("-i [-iter] <num iterations> : specify number of iterations for the test, default is " + countIters);
Console.WriteLine("-dz [-datasize] <data size> : specify the data size in bytes, default is " + mediumDataSize);
Console.WriteLine("-sdz [sdatasize] <data size> : specify the short lived data size in bytes, default is " + shortDataSize);
Console.WriteLine("-dc [datacount] <data count> : specify the medium lived data count , default is " + mediumDataCount);
Console.WriteLine("-sdc [sdatacount] <data count> : specify the short lived data count, default is " + shortDataCount);
Console.WriteLine("-lt [-lifetime] <number> : specify the life time of the objects, default is " + shortLifeTime);
Console.WriteLine("-t [-threads] <number of threads> : specifiy number of threads , default is " + numThreads);
Console.WriteLine("-f [-fin] : specify whether to do allocation in finalizer or not, default is no");
Console.WriteLine("-dp [-datapinned] <percent of data pinned> : specify the percentage of data that we want to pin, default is " + percentPinned);
Console.WriteLine("-dw [-dataweak] <percent of data weak referenced> : specify the percentage of data that we want to weak reference, default is " + percentWeak);
Console.WriteLine("-strategy < indicate the strategy for deciding when the objects should die, right now we support only Random and Time strategy, default is Random");
Console.WriteLine("-og [-objectgraph] <List|Tree> : specify whether to use a List- or Tree-based object graph, default is " + objectGraph);
Console.WriteLine("-notimer < indicate that we do not want to run the performance timer and output any results , default is no");
}
}
}
| |
/*
* PolicyStatement.cs - Implementation of the
* "System.Security.Policy.PolicyStatement" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Security.Policy
{
#if CONFIG_POLICY_OBJECTS
#if !CONFIG_PERMISSIONS
public sealed class PolicyStatement {}
#else // CONFIG_PERMISSIONS
using System.Security.Permissions;
[Serializable]
public sealed class PolicyStatement
: ISecurityEncodable, ISecurityPolicyEncodable
{
// Internal state.
private PermissionSet permSet;
private PolicyStatementAttribute attributes;
// Constructors.
public PolicyStatement(PermissionSet permSet)
: this(permSet, PolicyStatementAttribute.Nothing) {}
public PolicyStatement(PermissionSet permSet,
PolicyStatementAttribute attributes)
{
this.permSet = permSet;
this.attributes = attributes;
}
// Properties.
public PolicyStatementAttribute Attributes
{
get
{
return attributes;
}
set
{
attributes = value;
}
}
public String AttributeString
{
get
{
switch(attributes & PolicyStatementAttribute.All)
{
case PolicyStatementAttribute.Exclusive:
return "Exclusive";
case PolicyStatementAttribute.LevelFinal:
return "LevelFinal";
case PolicyStatementAttribute.All:
return "Exclusive LevelFinal";
}
return String.Empty;
}
}
public PermissionSet PermissionSet
{
get
{
if(permSet == null)
{
permSet = new PermissionSet
(PermissionState.None);
}
return permSet.Copy();
}
set
{
if(value != null)
{
permSet = value.Copy();
}
else
{
permSet = new PermissionSet
(PermissionState.None);
}
}
}
internal PermissionSet PermissionSetNoCopy
{
get
{
if(permSet == null)
{
permSet = new PermissionSet
(PermissionState.None);
}
return permSet;
}
set
{
permSet = value;
}
}
// Make a copy of this object.
public PolicyStatement Copy()
{
return new PolicyStatement(permSet, attributes);
}
// Implement the ISecurityEncodable interface.
public void FromXml(SecurityElement et)
{
FromXml(et, null);
}
public SecurityElement ToXml()
{
return ToXml(null);
}
// Implement the ISecurityPolicyEncodable interface.
public void FromXml(SecurityElement et, PolicyLevel level)
{
if(et == null)
{
throw new ArgumentNullException("et");
}
if(et.Tag != "PolicyStatement")
{
throw new ArgumentException
(_("Security_PolicyName"));
}
if(et.Attribute("version") != "1")
{
throw new ArgumentException
(_("Security_PolicyVersion"));
}
String value = et.Attribute("Attributes");
if(value != null)
{
attributes = (PolicyStatementAttribute)
Enum.Parse(typeof(PolicyStatementAttribute), value);
}
else
{
attributes = PolicyStatementAttribute.Nothing;
}
permSet = null;
if(level != null)
{
String name = et.Attribute("PermissionSetName");
if(name != null)
{
permSet = level.GetNamedPermissionSet(value);
if(permSet == null)
{
permSet = new PermissionSet(PermissionState.None);
}
}
}
if(permSet == null)
{
SecurityElement child;
child = et.SearchForChildByTag("PermissionSet");
if(child != null)
{
String permClass;
permClass = child.Attribute("class");
if(permClass != null &&
permClass.IndexOf("NamedPermissionSet") != -1)
{
permSet = new NamedPermissionSet
("DefaultName", PermissionState.None);
}
else
{
permSet = new PermissionSet(PermissionState.None);
}
try
{
permSet.FromXml(child);
}
catch(Exception)
{
// Ignore errors during set loading.
}
}
}
if(permSet == null)
{
permSet = new PermissionSet(PermissionState.None);
}
}
public SecurityElement ToXml(PolicyLevel level)
{
SecurityElement element;
element = new SecurityElement("PolicyStatement");
element.AddAttribute
("class",
SecurityElement.Escape(typeof(PolicyStatement).
AssemblyQualifiedName));
element.AddAttribute("version", "1");
if(attributes != PolicyStatementAttribute.Nothing)
{
element.AddAttribute("Attributes", attributes.ToString());
}
if(permSet != null)
{
NamedPermissionSet namedSet;
namedSet = (permSet as NamedPermissionSet);
if(namedSet != null)
{
if(level != null &&
level.GetNamedPermissionSet(namedSet.Name) != null)
{
element.AddAttribute
("PermissionSetName",
SecurityElement.Escape(namedSet.Name));
}
else
{
element.AddChild(permSet.ToXml());
}
}
else
{
element.AddChild(permSet.ToXml());
}
}
return element;
}
}; // class PolicyStatement
#endif // CONFIG_PERMISSIONS
#endif // CONFIG_POLICY_OBJECTS
}; // namespace System.Security.Policy
| |
#region Copyright & License
//
// Copyright 2001-2005 The Apache Software Foundation
//
// 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;
namespace log4net.Core
{
/// <summary>
/// Defines the default set of levels recognized by the system.
/// </summary>
/// <remarks>
/// <para>
/// Each <see cref="LoggingEvent"/> has an associated <see cref="Level"/>.
/// </para>
/// <para>
/// Levels have a numeric <see cref="Level.Value"/> that defines the relative
/// ordering between levels. Two Levels with the same <see cref="Level.Value"/>
/// are deemed to be equivalent.
/// </para>
/// <para>
/// The levels that are recognized by log4net are set for each <see cref="log4net.Repository.ILoggerRepository"/>
/// and each repository can have different levels defined. The levels are stored
/// in the <see cref="log4net.Repository.ILoggerRepository.LevelMap"/> on the repository. Levels are
/// looked up by name from the <see cref="log4net.Repository.ILoggerRepository.LevelMap"/>.
/// </para>
/// <para>
/// When logging at level INFO the actual level used is not <see cref="Level.Info"/> but
/// the value of <c>LoggerRepository.LevelMap["INFO"]</c>. The default value for this is
/// <see cref="Level.Info"/>, but this can be changed by reconfiguring the level map.
/// </para>
/// <para>
/// Each level has a <see cref="DisplayName"/> in addition to its <see cref="Name"/>. The
/// <see cref="DisplayName"/> is the string that is written into the output log. By default
/// the display name is the same as the level name, but this can be used to alias levels
/// or to localize the log output.
/// </para>
/// <para>
/// Some of the predefined levels recognized by the system are:
/// </para>
/// <list type="bullet">
/// <item>
/// <description><see cref="Off"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Fatal"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Error"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Warn"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Info"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Debug"/>.</description>
/// </item>
/// <item>
/// <description><see cref="All"/>.</description>
/// </item>
/// </list>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
#if !NETCF
[Serializable]
#endif
sealed public class Level : IComparable
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="level">Integer value for this level, higher values represent more severe levels.</param>
/// <param name="levelName">The string name of this level.</param>
/// <param name="displayName">The display name for this level. This may be localized or otherwise different from the name</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="Level" /> class with
/// the specified level name and value.
/// </para>
/// </remarks>
public Level(int level, string levelName, string displayName)
{
if (levelName == null)
{
throw new ArgumentNullException("levelName");
}
if (displayName == null)
{
throw new ArgumentNullException("displayName");
}
m_levelValue = level;
m_levelName = string.Intern(levelName);
m_levelDisplayName = displayName;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="level">Integer value for this level, higher values represent more severe levels.</param>
/// <param name="levelName">The string name of this level.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="Level" /> class with
/// the specified level name and value.
/// </para>
/// </remarks>
public Level(int level, string levelName) : this(level, levelName, levelName)
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets the name of this level.
/// </summary>
/// <value>
/// The name of this level.
/// </value>
/// <remarks>
/// <para>
/// Gets the name of this level.
/// </para>
/// </remarks>
public string Name
{
get { return m_levelName; }
}
/// <summary>
/// Gets the value of this level.
/// </summary>
/// <value>
/// The value of this level.
/// </value>
/// <remarks>
/// <para>
/// Gets the value of this level.
/// </para>
/// </remarks>
public int Value
{
get { return m_levelValue; }
}
/// <summary>
/// Gets the display name of this level.
/// </summary>
/// <value>
/// The display name of this level.
/// </value>
/// <remarks>
/// <para>
/// Gets the display name of this level.
/// </para>
/// </remarks>
public string DisplayName
{
get { return m_levelDisplayName; }
}
#endregion Public Instance Properties
#region Override implementation of Object
/// <summary>
/// Returns the <see cref="string" /> representation of the current
/// <see cref="Level" />.
/// </summary>
/// <returns>
/// A <see cref="string" /> representation of the current <see cref="Level" />.
/// </returns>
/// <remarks>
/// <para>
/// Returns the level <see cref="Name"/>.
/// </para>
/// </remarks>
override public string ToString()
{
return m_levelName;
}
/// <summary>
/// Compares levels.
/// </summary>
/// <param name="o">The object to compare against.</param>
/// <returns><c>true</c> if the objects are equal.</returns>
/// <remarks>
/// <para>
/// Compares the levels of <see cref="Level" /> instances, and
/// defers to base class if the target object is not a <see cref="Level" />
/// instance.
/// </para>
/// </remarks>
override public bool Equals(object o)
{
Level otherLevel = o as Level;
if (otherLevel != null)
{
return m_levelValue == otherLevel.m_levelValue;
}
else
{
return base.Equals(o);
}
}
/// <summary>
/// Returns a hash code
/// </summary>
/// <returns>A hash code for the current <see cref="Level" />.</returns>
/// <remarks>
/// <para>
/// Returns a hash code suitable for use in hashing algorithms and data
/// structures like a hash table.
/// </para>
/// <para>
/// Returns the hash code of the level <see cref="Value"/>.
/// </para>
/// </remarks>
override public int GetHashCode()
{
return m_levelValue;
}
#endregion Override implementation of Object
#region Implementation of IComparable
/// <summary>
/// Compares this instance to a specified object and returns an
/// indication of their relative values.
/// </summary>
/// <param name="r">A <see cref="Level"/> instance or <see langword="null" /> to compare with this instance.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the
/// values compared. The return value has these meanings:
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
/// <item>
/// <term>Less than zero</term>
/// <description>This instance is less than <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Zero</term>
/// <description>This instance is equal to <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Greater than zero</term>
/// <description>
/// <para>This instance is greater than <paramref name="r" />.</para>
/// <para>-or-</para>
/// <para><paramref name="r" /> is <see langword="null" />.</para>
/// </description>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// <paramref name="r" /> must be an instance of <see cref="Level" />
/// or <see langword="null" />; otherwise, an exception is thrown.
/// </para>
/// </remarks>
/// <exception cref="ArgumentException"><paramref name="r" /> is not a <see cref="Level" />.</exception>
public int CompareTo(object r)
{
Level target = r as Level;
if (target != null)
{
return Compare(this, target);
}
throw new ArgumentException("Parameter: r, Value: [" + r + "] is not an instance of Level");
}
#endregion Implementation of IComparable
#region Operators
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is greater than another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is greater than
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator > (Level l, Level r)
{
return l.m_levelValue > r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is less than another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is less than
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator < (Level l, Level r)
{
return l.m_levelValue < r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is greater than or equal to another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is greater than or equal to
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator >= (Level l, Level r)
{
return l.m_levelValue >= r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is less than or equal to another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is less than or equal to
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator <= (Level l, Level r)
{
return l.m_levelValue <= r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether two specified <see cref="Level" />
/// objects have the same value.
/// </summary>
/// <param name="l">A <see cref="Level" /> or <see langword="null" />.</param>
/// <param name="r">A <see cref="Level" /> or <see langword="null" />.</param>
/// <returns>
/// <c>true</c> if the value of <paramref name="l" /> is the same as the
/// value of <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator == (Level l, Level r)
{
if (((object)l) != null && ((object)r) != null)
{
return l.m_levelValue == r.m_levelValue;
}
else
{
return ((object) l) == ((object) r);
}
}
/// <summary>
/// Returns a value indicating whether two specified <see cref="Level" />
/// objects have different values.
/// </summary>
/// <param name="l">A <see cref="Level" /> or <see langword="null" />.</param>
/// <param name="r">A <see cref="Level" /> or <see langword="null" />.</param>
/// <returns>
/// <c>true</c> if the value of <paramref name="l" /> is different from
/// the value of <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator != (Level l, Level r)
{
return !(l==r);
}
#endregion Operators
#region Public Static Methods
/// <summary>
/// Compares two specified <see cref="Level"/> instances.
/// </summary>
/// <param name="l">The first <see cref="Level"/> to compare.</param>
/// <param name="r">The second <see cref="Level"/> to compare.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the
/// two values compared. The return value has these meanings:
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
/// <item>
/// <term>Less than zero</term>
/// <description><paramref name="l" /> is less than <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Zero</term>
/// <description><paramref name="l" /> is equal to <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Greater than zero</term>
/// <description><paramref name="l" /> is greater than <paramref name="r" />.</description>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static int Compare(Level l, Level r)
{
// Reference equals
if ((object)l == (object)r)
{
return 0;
}
if (l == null && r == null)
{
return 0;
}
if (l == null)
{
return -1;
}
if (r == null)
{
return 1;
}
return l.m_levelValue - r.m_levelValue;
}
#endregion Public Static Methods
#region Public Static Fields
/// <summary>
/// The <see cref="Off" /> level designates a higher level than all the rest.
/// </summary>
public readonly static Level Off = new Level(int.MaxValue, "OFF");
/// <summary>
/// The <see cref="Emergency" /> level designates very severe error events.
/// System unusable, emergencies.
/// </summary>
public readonly static Level Emergency = new Level(120000, "EMERGENCY");
/// <summary>
/// The <see cref="Fatal" /> level designates very severe error events
/// that will presumably lead the application to abort.
/// </summary>
public readonly static Level Fatal = new Level(110000, "FATAL");
/// <summary>
/// The <see cref="Alert" /> level designates very severe error events.
/// Take immediate action, alerts.
/// </summary>
public readonly static Level Alert = new Level(100000, "ALERT");
/// <summary>
/// The <see cref="Critical" /> level designates very severe error events.
/// Critical condition, critical.
/// </summary>
public readonly static Level Critical = new Level(90000, "CRITICAL");
/// <summary>
/// The <see cref="Severe" /> level designates very severe error events.
/// </summary>
public readonly static Level Severe = new Level(80000, "SEVERE");
/// <summary>
/// The <see cref="Error" /> level designates error events that might
/// still allow the application to continue running.
/// </summary>
public readonly static Level Error = new Level(70000, "ERROR");
/// <summary>
/// The <see cref="Warn" /> level designates potentially harmful
/// situations.
/// </summary>
public readonly static Level Warn = new Level(60000, "WARN");
/// <summary>
/// The <see cref="Notice" /> level designates informational messages
/// that highlight the progress of the application at the highest level.
/// </summary>
public readonly static Level Notice = new Level(50000, "NOTICE");
/// <summary>
/// The <see cref="Info" /> level designates informational messages that
/// highlight the progress of the application at coarse-grained level.
/// </summary>
public readonly static Level Info = new Level(40000, "INFO");
/// <summary>
/// The <see cref="Debug" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Debug = new Level(30000, "DEBUG");
/// <summary>
/// The <see cref="Fine" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Fine = new Level(30000, "FINE");
/// <summary>
/// The <see cref="Trace" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Trace = new Level(20000, "TRACE");
/// <summary>
/// The <see cref="Finer" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Finer = new Level(20000, "FINER");
/// <summary>
/// The <see cref="Verbose" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Verbose = new Level(10000, "VERBOSE");
/// <summary>
/// The <see cref="Finest" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Finest = new Level(10000, "FINEST");
/// <summary>
/// The <see cref="All" /> level designates the lowest level possible.
/// </summary>
public readonly static Level All = new Level(int.MinValue, "ALL");
#endregion Public Static Fields
#region Private Instance Fields
private readonly int m_levelValue;
private readonly string m_levelName;
private readonly string m_levelDisplayName;
#endregion Private Instance Fields
}
}
| |
using System;
using System.Data;
using System.Data.Common;
using System.Data.OracleClient;
using ALinq;
using ALinq.Mapping;
using System.Reflection;
//using OracleConnection = Oracle.DataAccess.Client.OracleConnection;
namespace NorthwindDemo
{
#if !FREE
//[License("ansiboy", "AV7D47FBDE5376DFA5")]
#endif
[Provider(typeof(ALinq.Oracle.Odp.OracleProvider))]
[Database(Name = "Northwind")]
public class OdpOracleNorthwind : NorthwindDatabase
{
private string password;
public OdpOracleNorthwind(string databaseName, string systemPassword)
: base(string.Format("Data Source=vpc1;User ID={0};password={1}", databaseName, systemPassword))
{
password = systemPassword;
}
public static IDbConnection CreateConnection(string databaseName, string systemPassword, string server)
{
var str = string.Format("Data Source={0};User ID={1};password={2}",
server, databaseName, systemPassword);
var conn = new OracleConnection(str);
return conn;
}
public OdpOracleNorthwind(string connection, MappingSource mapping)
: base(connection, mapping)
{
}
public OdpOracleNorthwind(string connection)
: base(connection)
{
}
public OdpOracleNorthwind(DbConnection connection)
: base(connection)
{
}
protected override void ImportData()
{
password = "test";
var instance = new OdpOracleNorthwind("Northwind", password) { Log = Log };
var data = new NorthwindData();
instance.Regions.InsertAllOnSubmit(data.regions);
instance.Employees.InsertAllOnSubmit(data.employees);
instance.Territories.InsertAllOnSubmit(data.territories);
instance.EmployeeTerritories.InsertAllOnSubmit(data.employeeTerritories);
instance.Customers.InsertAllOnSubmit(data.customers);
instance.Shippers.InsertAllOnSubmit(data.shippers);
instance.Categories.InsertAllOnSubmit(data.categories);
instance.Suppliers.InsertAllOnSubmit(data.suppliers);
instance.Products.InsertAllOnSubmit(data.products);
instance.Orders.InsertAllOnSubmit(data.orders);
instance.OrderDetails.InsertAllOnSubmit(data.orderDetails);
instance.SubmitChanges();
}
[Function(Name = "NORTHWIND.ADD_CATEGORY")]
public void AddCategory(
[Parameter(Name = "CATEGORY_ID")]
int categoryID,
[Parameter(Name = "CATEGORY_NAME")]
string categoryName,
[Parameter(Name = "CATEGORY_DESCRIPTION")]
string categoryDescription
)
{
var result = ExecuteMethodCall(this, ((MethodInfo)(MethodBase.GetCurrentMethod())), categoryID, categoryName, categoryDescription).ReturnValue;
//return (int)result;
}
[Function(Name = "NORTHWIND.ADD_CATEGORY1")]
public void AddCategory1(
[Parameter(Name = "CATEGORY_ID")]
int categoryID,
[Parameter(Name = "CATEGORY_NAME")]
string categoryName,
[Parameter(Name = "CATEGORY_DESCRIPTION")]
string categoryDescription
)
{
var result = ExecuteMethodCall(this, ((MethodInfo)(MethodBase.GetCurrentMethod())), categoryID, categoryName, categoryDescription).ReturnValue;
//return (decimal)result;
}
[Function(Name = "NORTHWIND.ADD_CONTACT")]
public void AddContact(
[Parameter(Name = "GUID")]
Guid guid,
[Parameter(Name = "ID")]
out int id
)
{
id = 0;
ALinq.IExecuteResult result = ExecuteMethodCall(this, ((MethodInfo)(MethodBase.GetCurrentMethod())), guid, id);
id = ((int)(result.GetParameterValue(1)));
}
[Function(Name = "get_customers_count_by_region")]
public int GetCustomersCountByRegion(
[Parameter] string region)
{
var result = ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), region);
return ((int)(result.ReturnValue));
}
//[Function(Name = "NORTHWIND.PKG1.GET_CUSTOMERS_BY_CITY")]
//public ISingleResult<PartialCustomersSetResult> GetCustomersByCity(
// [Parameter(DbType = "NVarChar2(20)")]
// string city,
// [Parameter(DbType = "Cursor")]
// object mycs)
//{
// IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), city, null);
// return ((ISingleResult<PartialCustomersSetResult>)(result.ReturnValue));
//}
[Function(Name = "NORTHWIND.PKG1.GET_CUSTOMERS_BY_CITY")]
public virtual ALinq.ISingleResult<PartialCustomersSetResult> GetCustomersByCity([Parameter(Name = "CITY", DbType = "VARCHAR2")] string City, [Parameter(Name = "MYCS", DbType = "REFCURSOR")] out object Mycs)
{
Mycs = default(object);
ALinq.IExecuteResult result = this.ExecuteMethodCall(this, ((System.Reflection.MethodInfo)(System.Reflection.MethodInfo.GetCurrentMethod())), City, Mycs);
//Mycs = ((object)(result.GetParameterValue(1)));
return ((ALinq.ISingleResult<PartialCustomersSetResult>)(result.ReturnValue));
}
[Function(Name = "PKG2.SINGLE_ROWSET_MULTI_SHAPE")]
[ResultType(typeof(Customer))]
[ResultType(typeof(PartialCustomersSetResult))]
public IMultipleResults SingleRowset_MultiShape(
[Parameter] int? param,
[Parameter(DbType = "Cursor")] object mycs)
{
IExecuteResult result = ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), param, mycs);
return ((IMultipleResults)(result.ReturnValue));
}
[Function(Name = "northwind.pkg_customer_and_orders.get")]
[ResultType(typeof(Customer))]
[ResultType(typeof(Order))]
public IMultipleResults GetCustomerAndOrders(
[Parameter] string customerID,
[Parameter(DbType = "Cursor")] object mysc1,
[Parameter(DbType = "Cursor")] object mysc2)
{
IExecuteResult result = this.ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod(),
customerID, mysc1, mysc2);
return ((IMultipleResults)(result.ReturnValue));
}
[Function(Name = "NORTHWIND.FUNCTION1")]
public int? Function1()
{
IExecuteResult result = this.ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod());
var value = result.GetParameterValue(0);
return (int?)value;
}
[Function(Name = "NORTHWIND.FUNCTION2")]
public int? Function2(int number)
{
IExecuteResult result = this.ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod(), number);
var value = result.GetParameterValue(0);
return (int?)value;
}
[Function(Name = "FUN_STRING1")]
public string FUN_STRING(int number)
{
IExecuteResult result = this.ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod(), number);
var value = result.GetParameterValue(0);
return (string)value;
}
public class PartialCustomersSetResult
{
[Column]
public string CustomerID;
[Column]
public string ContactName;
[Column]
public string CompanyName;
}
[Table]
public class DUAL
{
}
//public ALinq.Table<DUAL> Dual
//{
// get { return GetTable<DUAL>(); }
//}
[Function(Name = "sysdate", IsComposable = true)]
public new DateTime Now()
{
throw new NotImplementedException();
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Runtime;
namespace Orleans
{
/// <summary>
/// Factory for accessing grains.
/// </summary>
internal class GrainFactory : IInternalGrainFactory, IGrainReferenceConverter
{
/// <summary>
/// The mapping between concrete grain interface types and delegate
/// </summary>
private readonly ConcurrentDictionary<Type, GrainReferenceCaster> casters
= new ConcurrentDictionary<Type, GrainReferenceCaster>();
/// <summary>
/// The collection of <see cref="IGrainMethodInvoker"/>s for their corresponding grain interface type.
/// </summary>
private readonly ConcurrentDictionary<Type, IGrainMethodInvoker> invokers =
new ConcurrentDictionary<Type, IGrainMethodInvoker>();
/// <summary>
/// The cache of typed system target references.
/// </summary>
private readonly Dictionary<Tuple<GrainId, Type>, Dictionary<SiloAddress, ISystemTarget>> typedSystemTargetReferenceCache =
new Dictionary<Tuple<GrainId, Type>, Dictionary<SiloAddress, ISystemTarget>>();
/// <summary>
/// The cache of type metadata.
/// </summary>
private readonly TypeMetadataCache typeCache;
private readonly IRuntimeClient runtimeClient;
private IGrainReferenceRuntime GrainReferenceRuntime => this.runtimeClient.GrainReferenceRuntime;
// Make this internal so that client code is forced to access the IGrainFactory using the
// GrainClient (to make sure they don't forget to initialize the client).
public GrainFactory(IRuntimeClient runtimeClient, TypeMetadataCache typeCache)
{
this.runtimeClient = runtimeClient;
this.typeCache = typeCache;
}
/// <summary>
/// Casts an <see cref="IAddressable"/> to a concrete <see cref="GrainReference"/> implementation.
/// </summary>
/// <param name="existingReference">The existing <see cref="IAddressable"/> reference.</param>
/// <returns>The concrete <see cref="GrainReference"/> implementation.</returns>
internal delegate object GrainReferenceCaster(IAddressable existingReference);
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithGuidKey
{
Type interfaceType = typeof(TGrainInterface);
var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix);
var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, null);
return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId));
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithIntegerKey
{
Type interfaceType = typeof(TGrainInterface);
var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix);
var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, null);
return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId));
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(string primaryKey, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithStringKey
{
Type interfaceType = typeof(TGrainInterface);
var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix);
var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey);
return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId));
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string keyExtension, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithGuidCompoundKey
{
GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension);
Type interfaceType = typeof(TGrainInterface);
var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix);
var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, keyExtension);
return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId));
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string keyExtension, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithIntegerCompoundKey
{
GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension);
Type interfaceType = typeof(TGrainInterface);
var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix);
var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, keyExtension);
return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId));
}
/// <inheritdoc />
public void BindGrainReference(IAddressable grain)
{
if (grain == null) throw new ArgumentNullException(nameof(grain));
var reference = grain as GrainReference;
if (reference == null) throw new ArgumentException("Provided grain must be a GrainReference.", nameof(grain));
reference.Bind(this.GrainReferenceRuntime);
}
/// <inheritdoc />
public GrainReference GetGrainFromKeyString(string key) => GrainReference.FromKeyString(key, this.GrainReferenceRuntime);
/// <inheritdoc />
public Task<TGrainObserverInterface> CreateObjectReference<TGrainObserverInterface>(IGrainObserver obj)
where TGrainObserverInterface : IGrainObserver
{
return Task.FromResult(this.CreateObjectReferenceImpl<TGrainObserverInterface>(obj));
}
/// <inheritdoc />
public Task DeleteObjectReference<TGrainObserverInterface>(
IGrainObserver obj) where TGrainObserverInterface : IGrainObserver
{
this.runtimeClient.DeleteObjectReference(obj);
return Task.CompletedTask;
}
/// <inheritdoc />
public TGrainObserverInterface CreateObjectReference<TGrainObserverInterface>(IAddressable obj)
where TGrainObserverInterface : IAddressable
{
return this.CreateObjectReferenceImpl<TGrainObserverInterface>(obj);
}
private TGrainObserverInterface CreateObjectReferenceImpl<TGrainObserverInterface>(IAddressable obj) where TGrainObserverInterface : IAddressable
{
var interfaceType = typeof(TGrainObserverInterface);
if (!interfaceType.IsInterface)
{
throw new ArgumentException(
$"The provided type parameter must be an interface. '{interfaceType.FullName}' is not an interface.");
}
if (!interfaceType.IsInstanceOfType(obj))
{
throw new ArgumentException($"The provided object must implement '{interfaceType.FullName}'.", nameof(obj));
}
IGrainMethodInvoker invoker;
if (!this.invokers.TryGetValue(interfaceType, out invoker))
{
invoker = this.MakeInvoker(interfaceType);
this.invokers.TryAdd(interfaceType, invoker);
}
return this.Cast<TGrainObserverInterface>(this.runtimeClient.CreateObjectReference(obj, invoker));
}
private IAddressable MakeGrainReferenceFromType(Type interfaceType, GrainId grainId)
{
return GrainReference.FromGrainId(
grainId,
this.GrainReferenceRuntime,
interfaceType.IsGenericType ? TypeUtils.GenericTypeArgsString(interfaceType.UnderlyingSystemType.FullName) : null);
}
private GrainClassData GetGrainClassData(Type interfaceType, string grainClassNamePrefix)
{
if (!GrainInterfaceUtils.IsGrainType(interfaceType))
{
throw new ArgumentException("Cannot fabricate grain-reference for non-grain type: " + interfaceType.FullName);
}
var grainTypeResolver = this.runtimeClient.GrainTypeResolver;
GrainClassData implementation;
if (!grainTypeResolver.TryGetGrainClassData(interfaceType, out implementation, grainClassNamePrefix))
{
var loadedAssemblies = grainTypeResolver.GetLoadedGrainAssemblies();
var assembliesString = string.IsNullOrEmpty(loadedAssemblies)
? string.Empty
: " Loaded grain assemblies: " + loadedAssemblies;
var grainClassPrefixString = string.IsNullOrEmpty(grainClassNamePrefix)
? string.Empty
: ", grainClassNamePrefix: " + grainClassNamePrefix;
throw new ArgumentException(
$"Cannot find an implementation class for grain interface: {interfaceType}{grainClassPrefixString}. " +
"Make sure the grain assembly was correctly deployed and loaded in the silo." + assembliesString);
}
return implementation;
}
private IGrainMethodInvoker MakeInvoker(Type interfaceType)
{
var invokerType = this.typeCache.GetGrainMethodInvokerType(interfaceType);
return (IGrainMethodInvoker)Activator.CreateInstance(invokerType);
}
/// <summary>
/// Casts the provided <paramref name="grain"/> to the specified interface
/// </summary>
/// <typeparam name="TGrainInterface">The target grain interface type.</typeparam>
/// <param name="grain">The grain reference being cast.</param>
/// <returns>
/// A reference to <paramref name="grain"/> which implements <typeparamref name="TGrainInterface"/>.
/// </returns>
public TGrainInterface Cast<TGrainInterface>(IAddressable grain)
{
var interfaceType = typeof(TGrainInterface);
return (TGrainInterface)this.Cast(grain, interfaceType);
}
/// <summary>
/// Casts the provided <paramref name="grain"/> to the provided <paramref name="interfaceType"/>.
/// </summary>
/// <param name="grain">The grain.</param>
/// <param name="interfaceType">The resulting interface type.</param>
/// <returns>A reference to <paramref name="grain"/> which implements <paramref name="interfaceType"/>.</returns>
public object Cast(IAddressable grain, Type interfaceType)
{
GrainReferenceCaster caster;
if (!this.casters.TryGetValue(interfaceType, out caster))
{
// Create and cache a caster for the interface type.
caster = this.casters.GetOrAdd(interfaceType, this.MakeCaster);
}
return caster(grain);
}
/// <summary>
/// Creates and returns a new grain reference caster.
/// </summary>
/// <param name="interfaceType">The interface which the result will cast to.</param>
/// <returns>A new grain reference caster.</returns>
private GrainReferenceCaster MakeCaster(Type interfaceType)
{
var grainReferenceType = this.typeCache.GetGrainReferenceType(interfaceType);
return GrainCasterFactory.CreateGrainReferenceCaster(interfaceType, grainReferenceType);
}
/// <summary>
/// Gets a reference to the specified system target.
/// </summary>
/// <typeparam name="TGrainInterface">The system target interface.</typeparam>
/// <param name="grainId">The id of the target.</param>
/// <param name="destination">The destination silo.</param>
/// <returns>A reference to the specified system target.</returns>
public TGrainInterface GetSystemTarget<TGrainInterface>(GrainId grainId, SiloAddress destination)
where TGrainInterface : ISystemTarget
{
Dictionary<SiloAddress, ISystemTarget> cache;
Tuple<GrainId, Type> key = Tuple.Create(grainId, typeof(TGrainInterface));
lock (this.typedSystemTargetReferenceCache)
{
if (this.typedSystemTargetReferenceCache.ContainsKey(key)) cache = this.typedSystemTargetReferenceCache[key];
else
{
cache = new Dictionary<SiloAddress, ISystemTarget>();
this.typedSystemTargetReferenceCache[key] = cache;
}
}
ISystemTarget reference;
lock (cache)
{
if (cache.ContainsKey(destination))
{
reference = cache[destination];
}
else
{
reference = this.Cast<TGrainInterface>(GrainReference.FromGrainId(grainId, this.GrainReferenceRuntime, null, destination));
cache[destination] = reference; // Store for next time
}
}
return (TGrainInterface)reference;
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(GrainId grainId) where TGrainInterface : IAddressable
{
return this.Cast<TGrainInterface>(GrainReference.FromGrainId(grainId, this.GrainReferenceRuntime));
}
/// <inheritdoc />
public GrainReference GetGrain(GrainId grainId, string genericArguments)
=> GrainReference.FromGrainId(grainId, this.GrainReferenceRuntime, genericArguments);
}
}
| |
//
// (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.Windows.Forms;
using System.Collections;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI.Selection;
using Application = Autodesk.Revit.ApplicationServices.Application;
using Element = Autodesk.Revit.DB.Element;
namespace Revit.SDK.Samples.TraverseSystem.CS
{
/// <summary>
/// Implements the Revit add-in interface IExternalCommand
/// </summary>
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
[Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
public class Command : IExternalCommand
{
/// <summary>
/// Implement this method as an external command for Revit.
/// </summary>
/// <param name="commandData">An object that is passed to the external application
/// which contains data related to the command,
/// such as the application object and active view.</param>
/// <param name="message">A message that can be set by the external application
/// which will be displayed if a failure or cancellation is returned by
/// the external command.</param>
/// <param name="elements">A set of elements to which the external application
/// can add elements that are to be highlighted in case of failure or cancellation.</param>
/// <returns>Return the status of the external command.
/// A result of Succeeded means that the API external method functioned as expected.
/// Cancelled can be used to signify that the user cancelled the external operation
/// at some point. Failure should be returned if the application is unable to proceed with
/// the operation.</returns>
public virtual Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData
, ref string message, Autodesk.Revit.DB.ElementSet elements)
{
try
{
// Verify if the active document is null
UIDocument activeDoc = commandData.Application.ActiveUIDocument;
if (activeDoc == null)
{
MessageBox.Show("There's no active document in Revit.", "No Active Document",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return Autodesk.Revit.UI.Result.Failed;
}
// Verify the number of selected elements
SelElementSet selElements = activeDoc.Selection.Elements;
if (selElements.Size != 1)
{
message = "Please select ONLY one element from current project.";
return Autodesk.Revit.UI.Result.Failed;
}
// Get the selected element
Element selectedElement = null;
foreach (Element element in selElements)
{
selectedElement = element;
break;
}
// Get the expected mechanical or piping system from selected element
// Some elements in a non-well-connected system may get lost when traversing
//the system in the direction of flow; and
// flow direction of elements in a non-well-connected system may not be right,
// therefore the sample will only support well-connected system.
MEPSystem system = ExtractMechanicalOrPipingSystem(selectedElement);
if (system == null)
{
message = "The selected element does not belong to any well-connected mechanical or piping system. " +
"The sample will not support well-connected systems for the following reasons: " +
Environment.NewLine +
"- Some elements in a non-well-connected system may get lost when traversing the system in the " +
"direction of flow" + Environment.NewLine +
"- Flow direction of elements in a non-well-connected system may not be right";
return Autodesk.Revit.UI.Result.Failed;
}
// Traverse the system and dump the traversal into an XML file
TraversalTree tree = new TraversalTree(activeDoc.Document, system);
tree.Traverse();
String fileName;
fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "traversal.xml");
tree.DumpIntoXML(fileName);
return Autodesk.Revit.UI.Result.Succeeded;
}
catch (Exception ex)
{
message = ex.Message;
return Autodesk.Revit.UI.Result.Failed;
}
}
/// <summary>
/// Get the mechanical or piping system from selected element
/// </summary>
/// <param name="selectedElement">Selected element</param>
/// <returns>The extracted mechanical or piping system. Null if no expected system is found.</returns>
private MEPSystem ExtractMechanicalOrPipingSystem(Element selectedElement)
{
MEPSystem system = null;
if (selectedElement is MEPSystem)
{
if (selectedElement is MechanicalSystem || selectedElement is PipingSystem)
{
system = selectedElement as MEPSystem;
return system;
}
}
else // Selected element is not a system
{
FamilyInstance fi = selectedElement as FamilyInstance;
//
// If selected element is a family instance, iterate its connectors and get the expected system
if (fi != null)
{
MEPModel mepModel = fi.MEPModel;
ConnectorSet connectors = null;
try
{
connectors = mepModel.ConnectorManager.Connectors;
}
catch (System.Exception)
{
system = null;
}
system = ExtractSystemFromConnectors(connectors);
}
else
{
//
// If selected element is a MEPCurve (e.g. pipe or duct),
// iterate its connectors and get the expected system
MEPCurve mepCurve = selectedElement as MEPCurve;
if (mepCurve != null)
{
ConnectorSet connectors = null;
connectors = mepCurve.ConnectorManager.Connectors;
system = ExtractSystemFromConnectors(connectors);
}
}
}
return system;
}
/// <summary>
/// Get the mechanical or piping system from the connectors of selected element
/// </summary>
/// <param name="connectors">Connectors of selected element</param>
/// <returns>The found mechanical or piping system</returns>
static private MEPSystem ExtractSystemFromConnectors(ConnectorSet connectors)
{
MEPSystem system = null;
if (connectors == null || connectors.Size == 0)
{
return null;
}
// Get well-connected mechanical or piping systems from each connector
List<MEPSystem> systems = new List<MEPSystem>();
foreach (Connector connector in connectors)
{
MEPSystem tmpSystem = connector.MEPSystem;
if (tmpSystem == null)
{
continue;
}
MechanicalSystem ms = tmpSystem as MechanicalSystem;
if (ms != null)
{
if (ms.IsWellConnected)
{
systems.Add(tmpSystem);
}
}
else
{
PipingSystem ps = tmpSystem as PipingSystem;
if (ps != null && ps.IsWellConnected)
{
systems.Add(tmpSystem);
}
}
}
// If more than one system is found, get the system contains the most elements
int countOfSystem = systems.Count;
if (countOfSystem != 0)
{
int countOfElements = 0;
foreach (MEPSystem sys in systems)
{
if (sys.Elements.Size > countOfElements)
{
system = sys;
countOfElements = sys.Elements.Size;
}
}
}
return system;
}
}
}
| |
using CSharpMath.Display;
using CSharpMath.Display.FrontEnd;
using CSharpMath.Structures;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
namespace CSharpMath.Apple {
/// <summary>Holds lots of constants for spacing between
/// various visible elements by reading a JSON file.</summary>
public class JsonMathTable<TFont, TGlyph> : FontMathTable<TFont, TGlyph>
where TFont : IFont<TGlyph> {
/// <summary>Dictionary object containing a zillion constants,
/// typically loaded from a .json file.</summary>
private readonly JToken _mathTable;
private readonly JObject _constantsDictionary;
private readonly JObject _assemblyTable;
private readonly JObject _italicTable;
public IFontMeasurer<TFont, TGlyph> FontMeasurer { get; }
public IGlyphNameProvider<TGlyph> GlyphNameProvider { get; }
public IGlyphBoundsProvider<TFont, TGlyph> GlyphBoundsProvider { get; }
protected float FontUnitsToPt(TFont font, int fontUnits) =>
fontUnits * font.PointSize / FontMeasurer.GetUnitsPerEm(font);
private float ConstantFromTable(TFont font, string constantName) =>
FontUnitsToPt(font, _constantsDictionary[constantName].Value<int>());
private float PercentFromTable(string name) =>
// different from _ConstantFromTable in that the _ConstantFromTable requires
// a font and uses _FontUnitsToPt, while this is just a straight percentage.
_constantsDictionary[name].Value<int>() / 100f;
public override float RadicalDisplayStyleVerticalGap(TFont font) =>
ConstantFromTable(font, nameof(RadicalDisplayStyleVerticalGap));
public override float RadicalVerticalGap(TFont font) =>
ConstantFromTable(font, nameof(RadicalVerticalGap));
public JsonMathTable(IFontMeasurer<TFont, TGlyph> fontMeasurer, JToken mathTable,
IGlyphNameProvider<TGlyph> glyphNameProvider,
IGlyphBoundsProvider<TFont, TGlyph> glyphBoundsProvider) {
JObject GetTable(string name) =>
_mathTable[name] as JObject ?? throw new System.ArgumentException($"Table not found: {name}", nameof(mathTable));
FontMeasurer = fontMeasurer;
GlyphNameProvider = glyphNameProvider;
GlyphBoundsProvider = glyphBoundsProvider;
_mathTable = mathTable;
_constantsDictionary = GetTable("constants");
_assemblyTable = GetTable("v_assembly");
_italicTable = GetTable("italic");
}
// different from _ConstantFromTable in that the _ConstantFromTable requires
// a font and uses _FontUnitsToPt, while this is just a straight percentage.
protected override short ScriptPercentScaleDown(TFont font) =>
_constantsDictionary[nameof(ScriptPercentScaleDown)].Value<short>();
protected override short ScriptScriptPercentScaleDown(TFont font) =>
_constantsDictionary[nameof(ScriptScriptPercentScaleDown)].Value<short>();
/*
* NSDictionary* italics = (NSDictionary*) _mathTable[kItalic];
NSString* glyphName = [self.font getGlyphName:glyph];
NSNumber* val = (NSNumber*) italics[glyphName];
// if val is nil, this returns 0.
return [self fontUnitsToPt:val.intValue];*/
public override float GetItalicCorrection(TFont font, TGlyph glyph) =>
_italicTable[GlyphNameProvider.GetGlyphName(glyph)] is JToken entry
? FontUnitsToPt(font, entry.Value<int>())
: 0;
public override float FractionDelimiterSize(TFont font) => font.PointSize * 1.01f;
public override float FractionDelimiterDisplayStyleSize(TFont font) =>
font.PointSize * 2.39f;
public override float SuperscriptBaselineDropMax(TFont font) =>
ConstantFromTable(font, nameof(SuperscriptBaselineDropMax));
public override float SubscriptBaselineDropMin(TFont font) =>
ConstantFromTable(font, nameof(SubscriptBaselineDropMin));
public override float SubscriptShiftDown(TFont font) =>
ConstantFromTable(font, nameof(SubscriptShiftDown));
public override float SubscriptTopMax(TFont font) =>
ConstantFromTable(font, nameof(SubscriptTopMax));
public override float SuperscriptShiftUp(TFont font) =>
ConstantFromTable(font, nameof(SuperscriptShiftUp));
public override float SuperscriptShiftUpCramped(TFont font) =>
ConstantFromTable(font, nameof(SuperscriptShiftUpCramped));
public override float SuperscriptBottomMin(TFont font) =>
ConstantFromTable(font, nameof(SuperscriptBottomMin));
public override float SpaceAfterScript(TFont font) =>
ConstantFromTable(font, nameof(SpaceAfterScript));
public override float SubSuperscriptGapMin(TFont font) =>
ConstantFromTable(font, nameof(SubSuperscriptGapMin));
public override float SuperscriptBottomMaxWithSubscript(TFont font) =>
ConstantFromTable(font, nameof(SuperscriptBottomMaxWithSubscript));
#region fractions
public override float FractionNumeratorDisplayStyleShiftUp(TFont font) =>
ConstantFromTable(font, nameof(FractionNumeratorDisplayStyleShiftUp));
public override float FractionNumeratorShiftUp(TFont font) =>
ConstantFromTable(font, nameof(FractionNumeratorShiftUp));
public override float StackTopDisplayStyleShiftUp(TFont font) =>
ConstantFromTable(font, nameof(StackTopDisplayStyleShiftUp));
public override float StackTopShiftUp(TFont font) =>
ConstantFromTable(font, nameof(StackTopShiftUp));
public override float FractionNumDisplayStyleGapMin(TFont font) =>
ConstantFromTable(font, nameof(FractionNumDisplayStyleGapMin));
public override float FractionNumeratorGapMin(TFont font) =>
ConstantFromTable(font, nameof(FractionNumeratorGapMin));
public override float FractionDenominatorDisplayStyleShiftDown(TFont font) =>
ConstantFromTable(font, nameof(FractionDenominatorDisplayStyleShiftDown));
public override float FractionDenominatorShiftDown(TFont font) =>
ConstantFromTable(font, nameof(FractionDenominatorShiftDown));
public override float StackBottomDisplayStyleShiftDown(TFont font) =>
ConstantFromTable(font, nameof(StackBottomDisplayStyleShiftDown));
public override float StackBottomShiftDown(TFont font) =>
ConstantFromTable(font, nameof(StackBottomShiftDown));
public override float FractionDenomDisplayStyleGapMin(TFont font) =>
ConstantFromTable(font, nameof(FractionDenomDisplayStyleGapMin));
public override float FractionDenominatorGapMin(TFont font) =>
ConstantFromTable(font, nameof(FractionDenominatorGapMin));
public override float AxisHeight(TFont font) =>
ConstantFromTable(font, nameof(AxisHeight));
public override float FractionRuleThickness(TFont font) =>
ConstantFromTable(font, nameof(FractionRuleThickness));
public override float StackDisplayStyleGapMin(TFont font) =>
ConstantFromTable(font, nameof(StackDisplayStyleGapMin));
public override float StackGapMin(TFont font) =>
ConstantFromTable(font, nameof(StackGapMin));
#endregion
#region radicals
public override float RadicalKernBeforeDegree(TFont font) =>
ConstantFromTable(font, nameof(RadicalKernBeforeDegree));
public override float RadicalKernAfterDegree(TFont font) =>
ConstantFromTable(font, nameof(RadicalKernAfterDegree));
protected override short RadicalDegreeBottomRaisePercent(TFont font) =>
_constantsDictionary[nameof(RadicalDegreeBottomRaisePercent)].Value<short>();
public override float RadicalRuleThickness(TFont font) =>
ConstantFromTable(font, nameof(RadicalRuleThickness));
public override float RadicalExtraAscender(TFont font) =>
ConstantFromTable(font, nameof(RadicalExtraAscender));
#endregion
#region glyph assembly
private const string _assemblyPartsKey = "parts";
private const string _advanceKey = "advance";
private const string _endConnectorKey = "endConnector";
private const string _startConnectorKey = "startConnector";
private const string _extenderKey = "extender";
private const string _glyphKey = "glyph";
public override IEnumerable<GlyphPart<TGlyph>>? GetVerticalGlyphAssembly(TGlyph rawGlyph, TFont font) =>
_assemblyTable[GlyphNameProvider.GetGlyphName(rawGlyph)]?[_assemblyPartsKey] is JArray parts
? parts.Select(partInfo =>
new GlyphPart<TGlyph>(
GlyphNameProvider.GetGlyph(partInfo[_glyphKey].Value<string>()),
FontUnitsToPt(font, partInfo[_advanceKey].Value<int>()),
FontUnitsToPt(font, partInfo[_startConnectorKey].Value<int>()),
FontUnitsToPt(font, partInfo[_endConnectorKey].Value<int>()),
partInfo[_extenderKey].Value<bool>()))
// Should have been defined, but let's return null
: null;
public override float MinConnectorOverlap(TFont font) => ConstantFromTable(font, nameof(MinConnectorOverlap));
private const string VerticalVariantsKey = "v_variants";
private const string HorizontalVariantsKey = "h_variants";
public override (IEnumerable<TGlyph> variants, int count) GetVerticalVariantsForGlyph(TGlyph rawGlyph) =>
GetVariantsForGlyph(rawGlyph, _mathTable[VerticalVariantsKey]);
public override (IEnumerable<TGlyph> variants, int count) GetHorizontalVariantsForGlyph(TGlyph rawGlyph) =>
GetVariantsForGlyph(rawGlyph, _mathTable[HorizontalVariantsKey]);
private (IEnumerable<TGlyph> variants, int count) GetVariantsForGlyph(TGlyph rawGlyph, JToken variants) {
var glyphName = GlyphNameProvider.GetGlyphName(rawGlyph);
var variantGlyphs = variants[glyphName];
if (!(variantGlyphs is JArray variantGlyphsArray)) {
var outputGlyph = GlyphNameProvider.GetGlyph(glyphName);
if (outputGlyph is null || !outputGlyph.Equals(rawGlyph))
throw new InvalidCodePathException
("GlyphNameProvider.GetGlyph(GlyphNameProvider.GetGlyphName(rawGlyph)) != rawGlyph");
return (new TGlyph[] { outputGlyph }, 1);
} else
return
(variantGlyphsArray.Select(variantObj =>
GlyphNameProvider.GetGlyph(((JValue)variantObj).ToString())),
variantGlyphsArray.Count);
}
public override TGlyph GetLargerGlyph(TFont font, TGlyph glyph) {
var glyphName = GlyphNameProvider.GetGlyphName(glyph);
if (_mathTable[VerticalVariantsKey][glyphName] is JArray variantGlyphs) {
foreach (var jVariant in variantGlyphs) {
var variantName = jVariant.ToString();
if (variantName != glyphName) {
//return the first glyph with a different name.
return GlyphNameProvider.GetGlyph(variantName);
}
}
}
return glyph;
}
#endregion
public override float UpperLimitGapMin(TFont font) =>
ConstantFromTable(font, nameof(UpperLimitGapMin));
public override float UpperLimitBaselineRiseMin(TFont font) =>
ConstantFromTable(font, nameof(UpperLimitBaselineRiseMin));
public override float LowerLimitGapMin(TFont font) =>
ConstantFromTable(font, nameof(LowerLimitGapMin));
public override float LowerLimitBaselineDropMin(TFont font) =>
ConstantFromTable(font, nameof(LowerLimitBaselineDropMin));
#region overline/underline
public override float UnderbarVerticalGap(TFont font) =>
ConstantFromTable(font, nameof(UnderbarVerticalGap));
public override float UnderbarRuleThickness(TFont font) =>
ConstantFromTable(font, nameof(UnderbarRuleThickness));
public override float OverbarVerticalGap(TFont font) =>
ConstantFromTable(font, nameof(OverbarVerticalGap));
public override float OverbarExtraAscender(TFont font) =>
ConstantFromTable(font, nameof(OverbarExtraAscender));
public override float OverbarRuleThickness(TFont font) =>
ConstantFromTable(font, nameof(OverbarRuleThickness));
#endregion
public override float AccentBaseHeight(TFont font) =>
ConstantFromTable(font, nameof(AccentBaseHeight));
public override float GetTopAccentAdjustment(TFont font, TGlyph glyph) {
var nameValue = _mathTable["accents"][GlyphNameProvider.GetGlyphName(glyph)];
if (nameValue != null) {
return FontUnitsToPt(font, nameValue.Value<int>());
} else {
// If no top accent is defined then it is the center of the advance width.
using var glyphs = new Structures.RentedArray<TGlyph>(glyph);
var (_, Total) = GlyphBoundsProvider.GetAdvancesForGlyphs(font, glyphs.Result, 1);
return Total / 2;
}
}
}
}
| |
/* Copyright (c) 2006-2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser [email protected]
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
using System;
using System.Xml;
using System.Collections;
using System.Text;
using Google.GData.Client;
using System.Globalization;
namespace Google.GData.Extensions
{
/// <summary>
/// GData schema extension describing a period of time.
/// </summary>
public class When : IExtensionElementFactory
{
/// <summary>
/// Event start time (required).
/// </summary>
private DateTime startTime;
/// <summary>
/// Event end time (optional).
/// </summary>
private DateTime endTime;
/// <summary>
/// String description of the event times.
/// </summary>
private String valueString;
/// <summary>
/// flag, indicating if an all day status
/// </summary>
private bool fAllDay;
/// <summary>
/// reminder object to set reminder durations
/// </summary>
private ExtensionCollection<Reminder> reminders;
/// <summary>
/// Constructs a new instance of a When object.
/// </summary>
public When() : base()
{
}
/// <summary>
/// Constructs a new instance of a When object with provided data.
/// </summary>
/// <param name="start">The beginning of the event.</param>
/// <param name="end">The end of the event.</param>
public When(DateTime start, DateTime end) : this()
{
this.StartTime = start;
this.EndTime = end;
}
/// <summary>
/// Constructs a new instance of a When object with provided data.
/// </summary>
/// <param name="start">The beginning of the event.</param>
/// <param name="end">The end of the event.</param>
/// <param name="allDay">A flag to indicate an all day event.</param>
public When(DateTime start, DateTime end, bool allDay) : this(start, end)
{
this.AllDay = allDay;
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public DateTime StartTime</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public DateTime StartTime
{
get { return startTime; }
set { startTime = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public DateTime EndTime</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public DateTime EndTime
{
get { return endTime; }
set { endTime = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>reminder accessor</summary>
//////////////////////////////////////////////////////////////////////
public ExtensionCollection<Reminder> Reminders
{
get
{
if (this.reminders == null)
{
this.reminders = new ExtensionCollection<Reminder>(null);
}
return this.reminders;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string ValueString</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public String ValueString
{
get { return valueString; }
set { valueString = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method to the allday event flag</summary>
/// <returns>true if it's an all day event</returns>
//////////////////////////////////////////////////////////////////////
public bool AllDay
{
get { return this.fAllDay; }
set { this.fAllDay = value; }
}
#region overloaded from IExtensionElementFactory
//////////////////////////////////////////////////////////////////////
/// <summary>Parses an xml node to create a Where object.</summary>
/// <param name="node">the node to parse node</param>
/// <param name="parser">the xml parser to use if we need to dive deeper</param>
/// <returns>the created Where object</returns>
//////////////////////////////////////////////////////////////////////
public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser)
{
Tracing.TraceCall();
When when = null;
if (node != null)
{
object localname = node.LocalName;
if (!localname.Equals(this.XmlName) ||
!node.NamespaceURI.Equals(this.XmlNameSpace))
{
return null;
}
}
bool startTimeFlag = false, endTimeFlag = false;
when = new When();
if (node != null)
{
if (node.Attributes != null)
{
String value = node.Attributes[GDataParserNameTable.XmlAttributeStartTime] != null ?
node.Attributes[GDataParserNameTable.XmlAttributeStartTime].Value : null;
if (value != null)
{
startTimeFlag = true;
when.startTime = DateTime.Parse(value);
when.AllDay = (value.IndexOf('T') == -1);
}
value = node.Attributes[GDataParserNameTable.XmlAttributeEndTime] != null ?
node.Attributes[GDataParserNameTable.XmlAttributeEndTime].Value : null;
if (value != null)
{
endTimeFlag = true;
when.endTime = DateTime.Parse(value);
when.AllDay = when.AllDay && (value.IndexOf('T') == -1);
}
if (node.Attributes[GDataParserNameTable.XmlAttributeValueString] != null)
{
when.valueString = node.Attributes[GDataParserNameTable.XmlAttributeValueString].Value;
}
}
// single event, g:reminder is inside g:when
if (node.HasChildNodes)
{
XmlNode whenChildNode = node.FirstChild;
IExtensionElementFactory f = new Reminder() as IExtensionElementFactory;
while (whenChildNode != null)
{
if (whenChildNode is XmlElement)
{
if (String.Compare(whenChildNode.NamespaceURI, f.XmlNameSpace, true, CultureInfo.InvariantCulture) == 0)
{
if (String.Compare(whenChildNode.LocalName, f.XmlName, true, CultureInfo.InvariantCulture) == 0)
{
Reminder r = f.CreateInstance(whenChildNode, null) as Reminder;
when.Reminders.Add(r);
}
}
}
whenChildNode = whenChildNode.NextSibling;
}
}
}
if (!startTimeFlag)
{
throw new ClientFeedException("g:when/@startTime is required.");
}
if (endTimeFlag && when.startTime.CompareTo(when.endTime) > 0)
{
throw new ClientFeedException("g:when/@startTime must be less than or equal to g:when/@endTime.");
}
return when;
}
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.
/// </summary>
//////////////////////////////////////////////////////////////////////
public string XmlName
{
get { return GDataParserNameTable.XmlWhenElement; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public string XmlNameSpace
{
get { return BaseNameTable.gNamespace; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public string XmlPrefix
{
get { return BaseNameTable.gDataPrefix; }
}
#endregion
#region overloaded for persistence
/// <summary>
/// Persistence method for the When object
/// </summary>
/// <param name="writer">the xmlwriter to write into</param>
public void Save(XmlWriter writer)
{
if (Utilities.IsPersistable(this.valueString) ||
Utilities.IsPersistable(this.startTime) ||
Utilities.IsPersistable(this.endTime))
{
writer.WriteStartElement(BaseNameTable.gDataPrefix, XmlName, BaseNameTable.gNamespace);
if (startTime != new DateTime(1, 1, 1))
{
string date = this.fAllDay ? Utilities.LocalDateInUTC(this.startTime)
: Utilities.LocalDateTimeInUTC(this.startTime);
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeStartTime, date);
}
else
{
throw new ClientFeedException("g:when/@startTime is required.");
}
if (endTime != new DateTime(1, 1, 1))
{
string date = this.fAllDay ? Utilities.LocalDateInUTC(this.endTime)
: Utilities.LocalDateTimeInUTC(this.endTime);
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeEndTime, date);
}
if (Utilities.IsPersistable(this.valueString))
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeValueString, this.valueString);
}
if (this.reminders != null)
{
foreach (Reminder r in this.Reminders)
{
r.Save(writer);
}
}
writer.WriteEndElement();
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.